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,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Features/LanguageServer/Protocol/Handler/Definitions/GoToTypeDefinitionHandler.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentTypeDefinitionName)] internal class GoToTypeDefinitionHandler : AbstractGoToDefinitionHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToTypeDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) : base(metadataAsSourceFileService) { } public override string Method => LSP.Methods.TextDocumentTypeDefinitionName; public override Task<LSP.Location[]> HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) => GetDefinitionAsync(request, typeOnly: true, context, 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; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentTypeDefinitionName)] internal class GoToTypeDefinitionHandler : AbstractGoToDefinitionHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToTypeDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) : base(metadataAsSourceFileService) { } public override string Method => LSP.Methods.TextDocumentTypeDefinitionName; public override Task<LSP.Location[]> HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) => GetDefinitionAsync(request, typeOnly: true, context, cancellationToken); } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/VisualStudio/Core/Def/EditorConfigSettings/SettingsEditorFactory.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.ComponentModel.Composition; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.TextManager.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { [Export(typeof(SettingsEditorFactory))] [Guid(SettingsEditorFactoryGuidString)] internal sealed class SettingsEditorFactory : IVsEditorFactory, IDisposable { public static readonly Guid SettingsEditorFactoryGuid = new(SettingsEditorFactoryGuidString); public const string SettingsEditorFactoryGuidString = "68b46364-d378-42f2-9e72-37d86c5f4468"; public const string Extension = ".editorconfig"; private readonly ISettingsAggregator _settingsDataProviderFactory; private readonly VisualStudioWorkspace _workspace; private readonly IWpfTableControlProvider _controlProvider; private readonly ITableManagerProvider _tableMangerProvider; private readonly IVsEditorAdaptersFactoryService _vsEditorAdaptersFactoryService; private readonly IThreadingContext _threadingContext; private ServiceProvider? _vsServiceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SettingsEditorFactory(VisualStudioWorkspace workspace, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider, IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService, IThreadingContext threadingContext) { _settingsDataProviderFactory = workspace.Services.GetRequiredService<ISettingsAggregator>(); _workspace = workspace; _controlProvider = controlProvider; _tableMangerProvider = tableMangerProvider; _vsEditorAdaptersFactoryService = vsEditorAdaptersFactoryService; _threadingContext = threadingContext; } public void Dispose() { if (_vsServiceProvider is not null) { _vsServiceProvider.Dispose(); _vsServiceProvider = null; } } public int CreateEditorInstance(uint grfCreateDoc, string filePath, string pszPhysicalView, IVsHierarchy pvHier, uint itemid, IntPtr punkDocDataExisting, out IntPtr ppunkDocView, out IntPtr ppunkDocData, out string? pbstrEditorCaption, out Guid pguidCmdUI, out int pgrfCDW) { // Initialize to null ppunkDocView = IntPtr.Zero; ppunkDocData = IntPtr.Zero; pguidCmdUI = SettingsEditorFactoryGuid; pgrfCDW = 0; pbstrEditorCaption = null; if (!_workspace.CurrentSolution.Projects.Any(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic)) { // If there are no VB or C# projects loaded in the solution (so an editorconfig file in a C++ project) then we want their // editorfactory to present the file instead of use showing ours return VSConstants.VS_E_UNSUPPORTEDFORMAT; } if (!_workspace.CurrentSolution.Projects.Any(p => p.AnalyzerConfigDocuments.Any(editorconfig => StringComparer.OrdinalIgnoreCase.Equals(editorconfig.FilePath, filePath)))) { // If the user is simply opening an editorconfig file that does not apply to the current solution we just want to show the text view return VSConstants.VS_E_UNSUPPORTEDFORMAT; } // Validate inputs if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) { return VSConstants.E_INVALIDARG; } IVsTextLines? textBuffer = null; if (punkDocDataExisting == IntPtr.Zero) { Assumes.NotNull(_vsServiceProvider); if (_vsServiceProvider.TryGetService<SLocalRegistry, ILocalRegistry>(out var localRegistry)) { var textLinesGuid = typeof(IVsTextLines).GUID; _ = localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref textLinesGuid, 1 /*CLSCTX_INPROC_SERVER*/, out var ptr); try { textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines; } finally { _ = Marshal.Release(ptr); // Release RefCount from CreateInstance call } if (textBuffer is IObjectWithSite objectWithSite) { var oleServiceProvider = _vsServiceProvider.GetService<IOleServiceProvider>(); objectWithSite.SetSite(oleServiceProvider); } } } else { textBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines; if (textBuffer == null) { return VSConstants.VS_E_INCOMPATIBLEDOCDATA; } } if (textBuffer is null) { throw new InvalidOperationException("unable to acquire text buffer"); } // Create the editor var newEditor = new SettingsEditorPane(_vsEditorAdaptersFactoryService, _threadingContext, _settingsDataProviderFactory, _controlProvider, _tableMangerProvider, filePath, textBuffer, _workspace); ppunkDocView = Marshal.GetIUnknownForObject(newEditor); ppunkDocData = Marshal.GetIUnknownForObject(textBuffer); pbstrEditorCaption = ""; return VSConstants.S_OK; } public int SetSite(IOleServiceProvider psp) { _vsServiceProvider = new ServiceProvider(psp); return VSConstants.S_OK; } public int Close() => VSConstants.S_OK; public int MapLogicalView(ref Guid rguidLogicalView, out string? pbstrPhysicalView) { pbstrPhysicalView = null; // initialize out parameter // we support only a single physical view if (VSConstants.LOGVIEWID_Primary == rguidLogicalView) { return VSConstants.S_OK; // primary view uses NULL as pbstrPhysicalView } else { return VSConstants.E_NOTIMPL; // you must return E_NOTIMPL for any unrecognized rguidLogicalView values } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.TextManager.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { [Export(typeof(SettingsEditorFactory))] [Guid(SettingsEditorFactoryGuidString)] internal sealed class SettingsEditorFactory : IVsEditorFactory, IDisposable { public static readonly Guid SettingsEditorFactoryGuid = new(SettingsEditorFactoryGuidString); public const string SettingsEditorFactoryGuidString = "68b46364-d378-42f2-9e72-37d86c5f4468"; public const string Extension = ".editorconfig"; private readonly ISettingsAggregator _settingsDataProviderFactory; private readonly VisualStudioWorkspace _workspace; private readonly IWpfTableControlProvider _controlProvider; private readonly ITableManagerProvider _tableMangerProvider; private readonly IVsEditorAdaptersFactoryService _vsEditorAdaptersFactoryService; private readonly IThreadingContext _threadingContext; private ServiceProvider? _vsServiceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SettingsEditorFactory(VisualStudioWorkspace workspace, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider, IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService, IThreadingContext threadingContext) { _settingsDataProviderFactory = workspace.Services.GetRequiredService<ISettingsAggregator>(); _workspace = workspace; _controlProvider = controlProvider; _tableMangerProvider = tableMangerProvider; _vsEditorAdaptersFactoryService = vsEditorAdaptersFactoryService; _threadingContext = threadingContext; } public void Dispose() { if (_vsServiceProvider is not null) { _vsServiceProvider.Dispose(); _vsServiceProvider = null; } } public int CreateEditorInstance(uint grfCreateDoc, string filePath, string pszPhysicalView, IVsHierarchy pvHier, uint itemid, IntPtr punkDocDataExisting, out IntPtr ppunkDocView, out IntPtr ppunkDocData, out string? pbstrEditorCaption, out Guid pguidCmdUI, out int pgrfCDW) { // Initialize to null ppunkDocView = IntPtr.Zero; ppunkDocData = IntPtr.Zero; pguidCmdUI = SettingsEditorFactoryGuid; pgrfCDW = 0; pbstrEditorCaption = null; if (!_workspace.CurrentSolution.Projects.Any(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic)) { // If there are no VB or C# projects loaded in the solution (so an editorconfig file in a C++ project) then we want their // editorfactory to present the file instead of use showing ours return VSConstants.VS_E_UNSUPPORTEDFORMAT; } if (!_workspace.CurrentSolution.Projects.Any(p => p.AnalyzerConfigDocuments.Any(editorconfig => StringComparer.OrdinalIgnoreCase.Equals(editorconfig.FilePath, filePath)))) { // If the user is simply opening an editorconfig file that does not apply to the current solution we just want to show the text view return VSConstants.VS_E_UNSUPPORTEDFORMAT; } // Validate inputs if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) { return VSConstants.E_INVALIDARG; } IVsTextLines? textBuffer = null; if (punkDocDataExisting == IntPtr.Zero) { Assumes.NotNull(_vsServiceProvider); if (_vsServiceProvider.TryGetService<SLocalRegistry, ILocalRegistry>(out var localRegistry)) { var textLinesGuid = typeof(IVsTextLines).GUID; _ = localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref textLinesGuid, 1 /*CLSCTX_INPROC_SERVER*/, out var ptr); try { textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines; } finally { _ = Marshal.Release(ptr); // Release RefCount from CreateInstance call } if (textBuffer is IObjectWithSite objectWithSite) { var oleServiceProvider = _vsServiceProvider.GetService<IOleServiceProvider>(); objectWithSite.SetSite(oleServiceProvider); } } } else { textBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines; if (textBuffer == null) { return VSConstants.VS_E_INCOMPATIBLEDOCDATA; } } if (textBuffer is null) { throw new InvalidOperationException("unable to acquire text buffer"); } // Create the editor var newEditor = new SettingsEditorPane(_vsEditorAdaptersFactoryService, _threadingContext, _settingsDataProviderFactory, _controlProvider, _tableMangerProvider, filePath, textBuffer, _workspace); ppunkDocView = Marshal.GetIUnknownForObject(newEditor); ppunkDocData = Marshal.GetIUnknownForObject(textBuffer); pbstrEditorCaption = ""; return VSConstants.S_OK; } public int SetSite(IOleServiceProvider psp) { _vsServiceProvider = new ServiceProvider(psp); return VSConstants.S_OK; } public int Close() => VSConstants.S_OK; public int MapLogicalView(ref Guid rguidLogicalView, out string? pbstrPhysicalView) { pbstrPhysicalView = null; // initialize out parameter // we support only a single physical view if (VSConstants.LOGVIEWID_Primary == rguidLogicalView) { return VSConstants.S_OK; // primary view uses NULL as pbstrPhysicalView } else { return VSConstants.E_NOTIMPL; // you must return E_NOTIMPL for any unrecognized rguidLogicalView values } } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/EditorFeatures/CSharpTest2/Recommendations/BaseKeywordRecommenderTests.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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class BaseKeywordRecommenderTests : 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 TestNotInTopLevelMethod() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"void Goo() { $$ }"); } [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() { await VerifyAbsenceAsync( @"System.Console.WriteLine(); $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration() { await VerifyAbsenceAsync( @"int i = 0; $$", options: CSharp9ParseOptions); } [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 TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRecordConstructorInitializer() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync(@" record C { public C() : $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStructConstructorInitializer() { await VerifyAbsenceAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync( @"struct C { new internal ErrorCode Code { get { return (ErrorCode)$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyMethod() { await VerifyKeywordAsync( SourceCodeKind.Regular, AddInsideMethod( @"$$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(16335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/16335")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InExpressionBodyAccessor() { await VerifyKeywordAsync(@" class B { public virtual int T { get => bas$$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
// 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class BaseKeywordRecommenderTests : 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 TestNotInTopLevelMethod() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"void Goo() { $$ }"); } [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() { await VerifyAbsenceAsync( @"System.Console.WriteLine(); $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration() { await VerifyAbsenceAsync( @"int i = 0; $$", options: CSharp9ParseOptions); } [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 TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRecordConstructorInitializer() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync(@" record C { public C() : $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStructConstructorInitializer() { await VerifyAbsenceAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync( @"struct C { new internal ErrorCode Code { get { return (ErrorCode)$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyMethod() { await VerifyKeywordAsync( SourceCodeKind.Regular, AddInsideMethod( @"$$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(16335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/16335")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InExpressionBodyAccessor() { await VerifyKeywordAsync(@" class B { public virtual int T { get => bas$$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/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.Text; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal static class Extensions { private static readonly SymbolDisplayFormat s_typeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); private static readonly SymbolDisplayFormat s_memberDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); public static string GetMemberNavInfoNameOrEmpty(this ISymbol memberSymbol) { return memberSymbol != null ? memberSymbol.ToDisplayString(s_memberDisplayFormat) : string.Empty; } public static string GetNamespaceNavInfoNameOrEmpty(this INamespaceSymbol namespaceSymbol) { if (namespaceSymbol == null) { return string.Empty; } return !namespaceSymbol.IsGlobalNamespace ? namespaceSymbol.ToDisplayString() : string.Empty; } public static string GetTypeNavInfoNameOrEmpty(this ITypeSymbol typeSymbol) { return typeSymbol != null ? typeSymbol.ToDisplayString(s_typeDisplayFormat) : string.Empty; } public static string GetProjectDisplayName(this Project project) { // If the project name is unambiguous within the solution, use that name. Otherwise, use the unique name // provided by IVsSolution3.GetUniqueUINameOfProject. This covers all cases except for a single solution // with two or more multi-targeted projects with the same name and same targets. // // https://github.com/dotnet/roslyn/pull/43800 // http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949113 if (IsUnambiguousProjectNameInSolution(project)) { return project.Name; } else if (project.Solution.Workspace is VisualStudioWorkspace workspace && workspace.GetHierarchy(project.Id) is { } hierarchy && (IVsSolution3)ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution)) is { } solution) { if (ErrorHandler.Succeeded(solution.GetUniqueUINameOfProject(hierarchy, out var name)) && name != null) { return name; } } return project.Name; // Local functions static bool IsUnambiguousProjectNameInSolution(Project project) { foreach (var other in project.Solution.Projects) { if (other.Id == project.Id) continue; if (other.Name == project.Name) { // Another project with the same name was found in the solution. This project name is _not_ // unambiguous. return false; } } return true; } } public static bool IsVenus(this Project project) { if (project.Solution.Workspace is not VisualStudioWorkspaceImpl workspace) { return false; } foreach (var documentId in project.DocumentIds) { if (workspace.TryGetContainedDocument(documentId) != null) { return true; } } return false; } /// <summary> /// Returns a display name for the given project, walking its parent IVsHierarchy chain and /// pre-pending the names of parenting hierarchies (except the solution). /// </summary> public static string GetProjectNavInfoName(this Project project) { var result = project.Name; if (project.Solution.Workspace is not VisualStudioWorkspace workspace) { return result; } var hierarchy = workspace.GetHierarchy(project.Id); if (hierarchy == null) { return result; } if (!hierarchy.TryGetName(out result)) { return result; } if (hierarchy.TryGetParentHierarchy(out var parentHierarchy) && !(parentHierarchy is IVsSolution)) { var builder = new StringBuilder(result); while (parentHierarchy != null && !(parentHierarchy is IVsSolution)) { if (parentHierarchy.TryGetName(out var parentName)) { builder.Insert(0, parentName + "\\"); } if (!parentHierarchy.TryGetParentHierarchy(out parentHierarchy)) { break; } } result = builder.ToString(); } return result; } } }
// 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.Text; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal static class Extensions { private static readonly SymbolDisplayFormat s_typeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); private static readonly SymbolDisplayFormat s_memberDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); public static string GetMemberNavInfoNameOrEmpty(this ISymbol memberSymbol) { return memberSymbol != null ? memberSymbol.ToDisplayString(s_memberDisplayFormat) : string.Empty; } public static string GetNamespaceNavInfoNameOrEmpty(this INamespaceSymbol namespaceSymbol) { if (namespaceSymbol == null) { return string.Empty; } return !namespaceSymbol.IsGlobalNamespace ? namespaceSymbol.ToDisplayString() : string.Empty; } public static string GetTypeNavInfoNameOrEmpty(this ITypeSymbol typeSymbol) { return typeSymbol != null ? typeSymbol.ToDisplayString(s_typeDisplayFormat) : string.Empty; } public static string GetProjectDisplayName(this Project project) { // If the project name is unambiguous within the solution, use that name. Otherwise, use the unique name // provided by IVsSolution3.GetUniqueUINameOfProject. This covers all cases except for a single solution // with two or more multi-targeted projects with the same name and same targets. // // https://github.com/dotnet/roslyn/pull/43800 // http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949113 if (IsUnambiguousProjectNameInSolution(project)) { return project.Name; } else if (project.Solution.Workspace is VisualStudioWorkspace workspace && workspace.GetHierarchy(project.Id) is { } hierarchy && (IVsSolution3)ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution)) is { } solution) { if (ErrorHandler.Succeeded(solution.GetUniqueUINameOfProject(hierarchy, out var name)) && name != null) { return name; } } return project.Name; // Local functions static bool IsUnambiguousProjectNameInSolution(Project project) { foreach (var other in project.Solution.Projects) { if (other.Id == project.Id) continue; if (other.Name == project.Name) { // Another project with the same name was found in the solution. This project name is _not_ // unambiguous. return false; } } return true; } } public static bool IsVenus(this Project project) { if (project.Solution.Workspace is not VisualStudioWorkspaceImpl workspace) { return false; } foreach (var documentId in project.DocumentIds) { if (workspace.TryGetContainedDocument(documentId) != null) { return true; } } return false; } /// <summary> /// Returns a display name for the given project, walking its parent IVsHierarchy chain and /// pre-pending the names of parenting hierarchies (except the solution). /// </summary> public static string GetProjectNavInfoName(this Project project) { var result = project.Name; if (project.Solution.Workspace is not VisualStudioWorkspace workspace) { return result; } var hierarchy = workspace.GetHierarchy(project.Id); if (hierarchy == null) { return result; } if (!hierarchy.TryGetName(out result)) { return result; } if (hierarchy.TryGetParentHierarchy(out var parentHierarchy) && !(parentHierarchy is IVsSolution)) { var builder = new StringBuilder(result); while (parentHierarchy != null && !(parentHierarchy is IVsSolution)) { if (parentHierarchy.TryGetName(out var parentName)) { builder.Insert(0, parentName + "\\"); } if (!parentHierarchy.TryGetParentHierarchy(out parentHierarchy)) { break; } } result = builder.ToString(); } return result; } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./docs/compilers/API Notes/10-29-19.md
## API Review Notes for September 30th, 2019 ### Changes reviewed Starting commit: `38c90f8401f9e3ee5fb7c82aac36f6b85fdda979` Ending Commit: `b8a5611e3db4f7ac3b5e1404b129304b5baf843e` ### Notes IVariableDeclarationOperation: - What does scripting do for using local declarations in IOperation? VariableDeclarationKind - Is Default the right kind? Should we use Other instead? - Documentation on Default isn't great because everything is also a declaration - Should we add other kinds for foreach, pattern, using statement - Action: Add new parent node to represent IUsingDeclarationOperation to parent the IVariableDeclarationGroupOperation, remove VariableDeclarationKind Simplifier.AddImportsAnnotation - Should we use `Using` or `Imports`? - We have existing precedent for using C# where in conflict, but the existing stuff around using also uses Imports. We'll stick with the name Are we holding these meetings too late? - Probably. We should look at holding these before ask mode ends in the future, rather than monthy.
## API Review Notes for September 30th, 2019 ### Changes reviewed Starting commit: `38c90f8401f9e3ee5fb7c82aac36f6b85fdda979` Ending Commit: `b8a5611e3db4f7ac3b5e1404b129304b5baf843e` ### Notes IVariableDeclarationOperation: - What does scripting do for using local declarations in IOperation? VariableDeclarationKind - Is Default the right kind? Should we use Other instead? - Documentation on Default isn't great because everything is also a declaration - Should we add other kinds for foreach, pattern, using statement - Action: Add new parent node to represent IUsingDeclarationOperation to parent the IVariableDeclarationGroupOperation, remove VariableDeclarationKind Simplifier.AddImportsAnnotation - Should we use `Using` or `Imports`? - We have existing precedent for using C# where in conflict, but the existing stuff around using also uses Imports. We'll stick with the name Are we holding these meetings too late? - Probably. We should look at holding these before ask mode ends in the future, rather than monthy.
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindowPackage.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; using System.ComponentModel.Design; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages; using Task = System.Threading.Tasks.Task; namespace Roslyn.VisualStudio.DiagnosticsWindow { // The option page configuration is duplicated in PackageRegistration.pkgdef. // These attributes specify the menu structure to be used in Tools | Options. These are not // localized because they are for internal use only. [ProvideOptionPage(typeof(InternalFeaturesOnOffPage), @"Roslyn\FeatureManager", @"Features", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(InternalComponentsOnOffPage), @"Roslyn\FeatureManager", @"Components", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(PerformanceFunctionIdPage), @"Roslyn\Performance", @"FunctionId", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(PerformanceLoggersPage), @"Roslyn\Performance", @"Loggers", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(InternalDiagnosticsPage), @"Roslyn\Diagnostics", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(InternalSolutionCrawlerPage), @"Roslyn\SolutionCrawler", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [Guid(GuidList.guidVisualStudioDiagnosticsWindowPkgString)] [Description("Roslyn Diagnostics Window")] public sealed class VisualStudioDiagnosticsWindowPackage : AsyncPackage { private IThreadingContext _threadingContext; /// <summary> /// This function is called when the user clicks the menu item that shows the /// tool window. See the Initialize method to see how the menu item is associated to /// this function using the OleMenuCommandService service and the MenuCommand class. /// </summary> private void ShowToolWindow(object sender, EventArgs e) { _threadingContext.ThrowIfNotOnUIThread(); JoinableTaskFactory.RunAsync(async () => { await ShowToolWindowAsync(typeof(DiagnosticsWindow), id: 0, create: true, this.DisposalToken).ConfigureAwait(true); }); } ///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); var menuCommandService = (IMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true); cancellationToken.ThrowIfCancellationRequested(); Assumes.Present(componentModel); Assumes.Present(menuCommandService); _threadingContext = componentModel.GetService<IThreadingContext>(); var workspace = componentModel.GetService<VisualStudioWorkspace>(); _ = new ForceLowMemoryMode(workspace.Services.GetService<IOptionService>()); // Add our command handlers for menu (commands must exist in the .vsct file) if (menuCommandService is OleMenuCommandService mcs) { // Create the command for the tool window var toolwndCommandID = new CommandID(GuidList.guidVisualStudioDiagnosticsWindowCmdSet, (int)PkgCmdIDList.CmdIDRoslynDiagnosticWindow); var menuToolWin = new MenuCommand(ShowToolWindow, toolwndCommandID); mcs.AddCommand(menuToolWin); } // set logger at start up var optionService = componentModel.GetService<IGlobalOptionService>(); var remoteClientProvider = workspace.Services.GetService<IRemoteHostClientProvider>(); PerformanceLoggersPage.SetLoggers(optionService, _threadingContext, remoteClientProvider); } #endregion public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType) { // Return this for everything, as all our windows are now async return this; } protected override string GetToolWindowTitle(Type toolWindowType, int id) { if (toolWindowType == typeof(DiagnosticsWindow)) { return Resources.ToolWindowTitle; } return null; } protected override Task<object> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) { return Task.FromResult(new object()); } } }
// 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; using System.ComponentModel.Design; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages; using Task = System.Threading.Tasks.Task; namespace Roslyn.VisualStudio.DiagnosticsWindow { // The option page configuration is duplicated in PackageRegistration.pkgdef. // These attributes specify the menu structure to be used in Tools | Options. These are not // localized because they are for internal use only. [ProvideOptionPage(typeof(InternalFeaturesOnOffPage), @"Roslyn\FeatureManager", @"Features", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(InternalComponentsOnOffPage), @"Roslyn\FeatureManager", @"Components", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(PerformanceFunctionIdPage), @"Roslyn\Performance", @"FunctionId", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(PerformanceLoggersPage), @"Roslyn\Performance", @"Loggers", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(InternalDiagnosticsPage), @"Roslyn\Diagnostics", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [ProvideOptionPage(typeof(InternalSolutionCrawlerPage), @"Roslyn\SolutionCrawler", @"Internal", categoryResourceID: 0, pageNameResourceID: 0, supportsAutomation: true, SupportsProfiles = false)] [Guid(GuidList.guidVisualStudioDiagnosticsWindowPkgString)] [Description("Roslyn Diagnostics Window")] public sealed class VisualStudioDiagnosticsWindowPackage : AsyncPackage { private IThreadingContext _threadingContext; /// <summary> /// This function is called when the user clicks the menu item that shows the /// tool window. See the Initialize method to see how the menu item is associated to /// this function using the OleMenuCommandService service and the MenuCommand class. /// </summary> private void ShowToolWindow(object sender, EventArgs e) { _threadingContext.ThrowIfNotOnUIThread(); JoinableTaskFactory.RunAsync(async () => { await ShowToolWindowAsync(typeof(DiagnosticsWindow), id: 0, create: true, this.DisposalToken).ConfigureAwait(true); }); } ///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); var menuCommandService = (IMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true); cancellationToken.ThrowIfCancellationRequested(); Assumes.Present(componentModel); Assumes.Present(menuCommandService); _threadingContext = componentModel.GetService<IThreadingContext>(); var workspace = componentModel.GetService<VisualStudioWorkspace>(); _ = new ForceLowMemoryMode(workspace.Services.GetService<IOptionService>()); // Add our command handlers for menu (commands must exist in the .vsct file) if (menuCommandService is OleMenuCommandService mcs) { // Create the command for the tool window var toolwndCommandID = new CommandID(GuidList.guidVisualStudioDiagnosticsWindowCmdSet, (int)PkgCmdIDList.CmdIDRoslynDiagnosticWindow); var menuToolWin = new MenuCommand(ShowToolWindow, toolwndCommandID); mcs.AddCommand(menuToolWin); } // set logger at start up var optionService = componentModel.GetService<IGlobalOptionService>(); var remoteClientProvider = workspace.Services.GetService<IRemoteHostClientProvider>(); PerformanceLoggersPage.SetLoggers(optionService, _threadingContext, remoteClientProvider); } #endregion public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType) { // Return this for everything, as all our windows are now async return this; } protected override string GetToolWindowTitle(Type toolWindowType, int id) { if (toolWindowType == typeof(DiagnosticsWindow)) { return Resources.ToolWindowTitle; } return null; } protected override Task<object> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) { return Task.FromResult(new object()); } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/EditorFeatures/Test/Extensions/SetExtensionTests.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.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class SetExtensionTests { [Fact] public void TestAddAll() { var set = new HashSet<string>() { "a", "b", "c" }; Assert.False(set.AddAll(new[] { "b", "c" })); Assert.True(set.AddAll(new[] { "c", "d" })); Assert.True(set.AddAll(new[] { "e", "f" })); } } }
// 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.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class SetExtensionTests { [Fact] public void TestAddAll() { var set = new HashSet<string>() { "a", "b", "c" }; Assert.False(set.AddAll(new[] { "b", "c" })); Assert.True(set.AddAll(new[] { "c", "d" })); Assert.True(set.AddAll(new[] { "e", "f" })); } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/CSharp/Portable/BoundTree/BoundNullCoalescingOperatorResultKind.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.CSharp { /// <summary> /// Represents the operand type used for the result of a null-coalescing /// operator. Used when determining nullability. /// </summary> internal enum BoundNullCoalescingOperatorResultKind { /// <summary> /// No valid type for operator. /// </summary> NoCommonType, /// <summary> /// Type of left operand is used. /// </summary> LeftType, /// <summary> /// Nullable underlying type of left operand is used. /// </summary> LeftUnwrappedType, /// <summary> /// Type of right operand is used. /// </summary> RightType, /// <summary> /// Type of right operand is used and nullable left operand is converted /// to underlying type before converting to right operand type. /// </summary> LeftUnwrappedRightType, /// <summary> /// Type of right operand is dynamic and is used. /// </summary> RightDynamicType, } }
// 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.CSharp { /// <summary> /// Represents the operand type used for the result of a null-coalescing /// operator. Used when determining nullability. /// </summary> internal enum BoundNullCoalescingOperatorResultKind { /// <summary> /// No valid type for operator. /// </summary> NoCommonType, /// <summary> /// Type of left operand is used. /// </summary> LeftType, /// <summary> /// Nullable underlying type of left operand is used. /// </summary> LeftUnwrappedType, /// <summary> /// Type of right operand is used. /// </summary> RightType, /// <summary> /// Type of right operand is used and nullable left operand is converted /// to underlying type before converting to right operand type. /// </summary> LeftUnwrappedRightType, /// <summary> /// Type of right operand is dynamic and is used. /// </summary> RightDynamicType, } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Interactive/Host/xlf/InteractiveHostResources.es.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="es" original="../InteractiveHostResources.resx"> <body> <trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying"> <source>Attempt to connect to process #{0} failed, retrying ...</source> <target state="translated">Error al intentar conectar con el proceso #{0}, reintentando...</target> <note /> </trans-unit> <trans-unit id="Cannot_resolve_reference_0"> <source>Cannot resolve reference '{0}'.</source> <target state="translated">No se puede resolver la referencia '{0}'.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution"> <source>Failed to create a remote process for interactive code execution: '{0}'</source> <target state="translated">No se pudo crear un proceso remoto para la ejecución de código interactivo: "{0}"</target> <note /> </trans-unit> <trans-unit id="Failed_to_initialize_remote_interactive_process"> <source>Failed to initialize remote interactive process.</source> <target state="translated">Error al inicializar el proceso remoto interactivo.</target> <note /> </trans-unit> <trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon"> <source>Failed to launch '{0}' process (exit code: {1}) with output: </source> <target state="translated">Error al iniciar el proceso '{0}' (código de salida: {1}) con la salida: </target> <note /> </trans-unit> <trans-unit id="Hosting_process_exited_with_exit_code_0"> <source>Hosting process exited with exit code {0}.</source> <target state="translated">El proceso de hospedaje terminó con el código de salida {0}.</target> <note /> </trans-unit> <trans-unit id="Interactive_Host_not_initialized"> <source>Interactive Host not initialized.</source> <target state="translated">Host interactivo no inicializado.</target> <note /> </trans-unit> <trans-unit id="Loading_context_from_0"> <source>Loading context from '{0}'.</source> <target state="translated">Cargando contexto de '{0}'.</target> <note /> </trans-unit> <trans-unit id="Searched_in_directories_colon"> <source>Searched in directories:</source> <target state="translated">Buscado en directorios:</target> <note /> </trans-unit> <trans-unit id="Searched_in_directory_colon"> <source>Searched in directory:</source> <target state="translated">Buscado en directorio:</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found"> <source>Specified file not found.</source> <target state="translated">Archivo especificado no encontrado.</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found_colon_0"> <source>Specified file not found: {0}</source> <target state="translated">Archivo especificado no encontrado: {0}</target> <note /> </trans-unit> <trans-unit id="Type_Sharphelp_for_more_information"> <source>Type "#help" for more information.</source> <target state="translated">Escriba "#help" para más información.</target> <note /> </trans-unit> <trans-unit id="Unable_to_create_hosting_process"> <source>Unable to create hosting process.</source> <target state="translated">No se puede crear el proceso de hospedaje.</target> <note /> </trans-unit> <trans-unit id="plus_additional_0_1"> <source> + additional {0} {1}</source> <target state="translated"> + adicional {0} {1}</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="es" original="../InteractiveHostResources.resx"> <body> <trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying"> <source>Attempt to connect to process #{0} failed, retrying ...</source> <target state="translated">Error al intentar conectar con el proceso #{0}, reintentando...</target> <note /> </trans-unit> <trans-unit id="Cannot_resolve_reference_0"> <source>Cannot resolve reference '{0}'.</source> <target state="translated">No se puede resolver la referencia '{0}'.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution"> <source>Failed to create a remote process for interactive code execution: '{0}'</source> <target state="translated">No se pudo crear un proceso remoto para la ejecución de código interactivo: "{0}"</target> <note /> </trans-unit> <trans-unit id="Failed_to_initialize_remote_interactive_process"> <source>Failed to initialize remote interactive process.</source> <target state="translated">Error al inicializar el proceso remoto interactivo.</target> <note /> </trans-unit> <trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon"> <source>Failed to launch '{0}' process (exit code: {1}) with output: </source> <target state="translated">Error al iniciar el proceso '{0}' (código de salida: {1}) con la salida: </target> <note /> </trans-unit> <trans-unit id="Hosting_process_exited_with_exit_code_0"> <source>Hosting process exited with exit code {0}.</source> <target state="translated">El proceso de hospedaje terminó con el código de salida {0}.</target> <note /> </trans-unit> <trans-unit id="Interactive_Host_not_initialized"> <source>Interactive Host not initialized.</source> <target state="translated">Host interactivo no inicializado.</target> <note /> </trans-unit> <trans-unit id="Loading_context_from_0"> <source>Loading context from '{0}'.</source> <target state="translated">Cargando contexto de '{0}'.</target> <note /> </trans-unit> <trans-unit id="Searched_in_directories_colon"> <source>Searched in directories:</source> <target state="translated">Buscado en directorios:</target> <note /> </trans-unit> <trans-unit id="Searched_in_directory_colon"> <source>Searched in directory:</source> <target state="translated">Buscado en directorio:</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found"> <source>Specified file not found.</source> <target state="translated">Archivo especificado no encontrado.</target> <note /> </trans-unit> <trans-unit id="Specified_file_not_found_colon_0"> <source>Specified file not found: {0}</source> <target state="translated">Archivo especificado no encontrado: {0}</target> <note /> </trans-unit> <trans-unit id="Type_Sharphelp_for_more_information"> <source>Type "#help" for more information.</source> <target state="translated">Escriba "#help" para más información.</target> <note /> </trans-unit> <trans-unit id="Unable_to_create_hosting_process"> <source>Unable to create hosting process.</source> <target state="translated">No se puede crear el proceso de hospedaje.</target> <note /> </trans-unit> <trans-unit id="plus_additional_0_1"> <source> + additional {0} {1}</source> <target state="translated"> + adicional {0} {1}</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/Test/Utilities/VisualBasic/TestOptions.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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Roslyn.Test.Utilities Public Class TestOptions Public Shared ReadOnly Script As New VisualBasicParseOptions(kind:=SourceCodeKind.Script) Public Shared ReadOnly Regular As New VisualBasicParseOptions(kind:=SourceCodeKind.Regular) Public Shared ReadOnly Regular15_5 As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_5) Public Shared ReadOnly Regular16 As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.VisualBasic16) Public Shared ReadOnly Regular16_9 As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.VisualBasic16_9) Public Shared ReadOnly RegularLatest As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.Latest) Public Shared ReadOnly RegularWithLegacyStrongName As VisualBasicParseOptions = Regular.WithFeature("UseLegacyStrongNameProvider") Public Shared ReadOnly ReleaseDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly ReleaseExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly ReleaseDebugDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Release). WithDebugPlusMode(True).WithParseOptions(Regular) Public Shared ReadOnly ReleaseDebugExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Release). WithDebugPlusMode(True).WithParseOptions(Regular) Public Shared ReadOnly DebugDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular) Public Shared ReadOnly DebugExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular) Public Shared ReadOnly ReleaseModule As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.NetModule, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly ReleaseWinMD As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly DebugWinMD As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular) Public Shared ReadOnly SigningReleaseDll As VisualBasicCompilationOptions = ReleaseDll.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningReleaseExe As VisualBasicCompilationOptions = ReleaseExe.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningDebugDll As VisualBasicCompilationOptions = DebugDll.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningDebugExe As VisualBasicCompilationOptions = DebugExe.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningReleaseModule As VisualBasicCompilationOptions = ReleaseModule.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) End Class Friend Module TestOptionExtensions <Extension()> Public Function WithStrictFeature(options As VisualBasicParseOptions) As VisualBasicParseOptions Return WithFeature(options, "Strict") End Function <Extension()> Public Function WithFeature(options As VisualBasicParseOptions, feature As String, Optional value As String = "True") As VisualBasicParseOptions Return options.WithFeatures(options.Features.Concat(New KeyValuePair(Of String, String)() {New KeyValuePair(Of String, String)(feature, value)})) End Function <Extension()> Friend Function WithExperimental(options As VisualBasicParseOptions, ParamArray features As Feature()) As VisualBasicParseOptions If features.Length = 0 Then Throw New InvalidOperationException("Need at least one feature to enable") End If Dim list As New List(Of KeyValuePair(Of String, String)) For Each feature In features Dim flagName = feature.GetFeatureFlag() If flagName Is Nothing Then Throw New InvalidOperationException($"{feature} is not an experimental feature") End If list.Add(New KeyValuePair(Of String, String)(flagName, "True")) Next Return options.WithFeatures(options.Features.Concat(list)) End Function End Module
' 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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Roslyn.Test.Utilities Public Class TestOptions Public Shared ReadOnly Script As New VisualBasicParseOptions(kind:=SourceCodeKind.Script) Public Shared ReadOnly Regular As New VisualBasicParseOptions(kind:=SourceCodeKind.Regular) Public Shared ReadOnly Regular15_5 As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_5) Public Shared ReadOnly Regular16 As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.VisualBasic16) Public Shared ReadOnly Regular16_9 As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.VisualBasic16_9) Public Shared ReadOnly RegularLatest As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.Latest) Public Shared ReadOnly RegularWithLegacyStrongName As VisualBasicParseOptions = Regular.WithFeature("UseLegacyStrongNameProvider") Public Shared ReadOnly ReleaseDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly ReleaseExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly ReleaseDebugDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Release). WithDebugPlusMode(True).WithParseOptions(Regular) Public Shared ReadOnly ReleaseDebugExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Release). WithDebugPlusMode(True).WithParseOptions(Regular) Public Shared ReadOnly DebugDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular) Public Shared ReadOnly DebugExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular) Public Shared ReadOnly ReleaseModule As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.NetModule, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly ReleaseWinMD As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular) Public Shared ReadOnly DebugWinMD As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular) Public Shared ReadOnly SigningReleaseDll As VisualBasicCompilationOptions = ReleaseDll.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningReleaseExe As VisualBasicCompilationOptions = ReleaseExe.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningDebugDll As VisualBasicCompilationOptions = DebugDll.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningDebugExe As VisualBasicCompilationOptions = DebugExe.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) Public Shared ReadOnly SigningReleaseModule As VisualBasicCompilationOptions = ReleaseModule.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider) End Class Friend Module TestOptionExtensions <Extension()> Public Function WithStrictFeature(options As VisualBasicParseOptions) As VisualBasicParseOptions Return WithFeature(options, "Strict") End Function <Extension()> Public Function WithFeature(options As VisualBasicParseOptions, feature As String, Optional value As String = "True") As VisualBasicParseOptions Return options.WithFeatures(options.Features.Concat(New KeyValuePair(Of String, String)() {New KeyValuePair(Of String, String)(feature, value)})) End Function <Extension()> Friend Function WithExperimental(options As VisualBasicParseOptions, ParamArray features As Feature()) As VisualBasicParseOptions If features.Length = 0 Then Throw New InvalidOperationException("Need at least one feature to enable") End If Dim list As New List(Of KeyValuePair(Of String, String)) For Each feature In features Dim flagName = feature.GetFeatureFlag() If flagName Is Nothing Then Throw New InvalidOperationException($"{feature} is not an experimental feature") End If list.Add(New KeyValuePair(Of String, String)(flagName, "True")) Next Return options.WithFeatures(options.Features.Concat(list)) End Function End Module
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedGlobalMethodBase.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 Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' This class represents a base class for compiler generated synthesized method symbols ''' that must be emitted in the compiler generated PrivateImplementationDetails class. ''' SynthesizedGlobalMethodBase symbols don't have a ContainingType, there are global to ''' the containing source module and are Public Shared methods. ''' </summary> Friend MustInherit Class SynthesizedGlobalMethodBase Inherits MethodSymbol Protected ReadOnly m_privateImplType As PrivateImplementationDetails Protected ReadOnly m_containingModule As SourceModuleSymbol Protected ReadOnly m_name As String Protected Sub New(containingModule As SourceModuleSymbol, name As String, privateImplType As PrivateImplementationDetails) Debug.Assert(containingModule IsNot Nothing) m_containingModule = containingModule m_name = name m_privateImplType = privateImplType End Sub Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property ''' <summary> ''' Gets the symbol name. Returns the empty string if unnamed. ''' </summary> Public NotOverridable Overrides ReadOnly Property Name As String Get Return m_name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function ''' <summary> ''' Gets a value indicating whether this instance is abstract or not. ''' </summary> ''' <value> ''' <c>true</c> if this instance is abstract; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is not overridable. ''' </summary> ''' <value> ''' <c>true</c> if this instance is not overridable; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is overloads. ''' </summary> ''' <value> ''' <c>true</c> if this instance is overloads; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is overridable. ''' </summary> ''' <value> ''' <c>true</c> if this instance is overridable; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is overrides. ''' </summary> ''' <value> ''' <c>true</c> if this instance is overrides; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is shared. ''' </summary> ''' <value> ''' <c>true</c> if this instance is shared; otherwise, <c>false</c>. ''' </value> Public NotOverridable Overrides ReadOnly Property IsShared As Boolean Get Return True End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey Return LexicalSortKey.NotInSource End Function ''' <summary> ''' A potentially empty collection of locations that correspond to this instance. ''' </summary> Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property ''' <summary> ''' Gets what kind of method this is. There are several different kinds of things in the ''' VB language that are represented as methods. This property allow distinguishing those things ''' without having to decode the name of the method. ''' </summary> Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property ''' <summary> ''' The parameters forming part of this signature. ''' </summary> Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return ImmutableArray(Of ParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Friend End Get End Property Friend NotOverridable Overrides ReadOnly Property Syntax As SyntaxNode Get Return VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot() End Get End Property Public NotOverridable Overrides ReadOnly Property Arity As Integer Get Return 0 End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return If(IsShared, Microsoft.Cci.CallingConvention.Default, Microsoft.Cci.CallingConvention.HasThis) End Get End Property Public ReadOnly Property ContainingPrivateImplementationDetailsType As PrivateImplementationDetails Get Return m_privateImplType End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return m_containingModule End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return m_containingModule.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return Nothing End Get End Property Public NotOverridable Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public NotOverridable Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend NotOverridable Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Public NotOverridable Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return ImmutableArray(Of VisualBasicAttributeData).Empty End Function Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable 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 Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' This class represents a base class for compiler generated synthesized method symbols ''' that must be emitted in the compiler generated PrivateImplementationDetails class. ''' SynthesizedGlobalMethodBase symbols don't have a ContainingType, there are global to ''' the containing source module and are Public Shared methods. ''' </summary> Friend MustInherit Class SynthesizedGlobalMethodBase Inherits MethodSymbol Protected ReadOnly m_privateImplType As PrivateImplementationDetails Protected ReadOnly m_containingModule As SourceModuleSymbol Protected ReadOnly m_name As String Protected Sub New(containingModule As SourceModuleSymbol, name As String, privateImplType As PrivateImplementationDetails) Debug.Assert(containingModule IsNot Nothing) m_containingModule = containingModule m_name = name m_privateImplType = privateImplType End Sub Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property ''' <summary> ''' Gets the symbol name. Returns the empty string if unnamed. ''' </summary> Public NotOverridable Overrides ReadOnly Property Name As String Get Return m_name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function ''' <summary> ''' Gets a value indicating whether this instance is abstract or not. ''' </summary> ''' <value> ''' <c>true</c> if this instance is abstract; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is not overridable. ''' </summary> ''' <value> ''' <c>true</c> if this instance is not overridable; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is overloads. ''' </summary> ''' <value> ''' <c>true</c> if this instance is overloads; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is overridable. ''' </summary> ''' <value> ''' <c>true</c> if this instance is overridable; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is overrides. ''' </summary> ''' <value> ''' <c>true</c> if this instance is overrides; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is shared. ''' </summary> ''' <value> ''' <c>true</c> if this instance is shared; otherwise, <c>false</c>. ''' </value> Public NotOverridable Overrides ReadOnly Property IsShared As Boolean Get Return True End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey Return LexicalSortKey.NotInSource End Function ''' <summary> ''' A potentially empty collection of locations that correspond to this instance. ''' </summary> Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property ''' <summary> ''' Gets what kind of method this is. There are several different kinds of things in the ''' VB language that are represented as methods. This property allow distinguishing those things ''' without having to decode the name of the method. ''' </summary> Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property ''' <summary> ''' The parameters forming part of this signature. ''' </summary> Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return ImmutableArray(Of ParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Friend End Get End Property Friend NotOverridable Overrides ReadOnly Property Syntax As SyntaxNode Get Return VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot() End Get End Property Public NotOverridable Overrides ReadOnly Property Arity As Integer Get Return 0 End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return If(IsShared, Microsoft.Cci.CallingConvention.Default, Microsoft.Cci.CallingConvention.HasThis) End Get End Property Public ReadOnly Property ContainingPrivateImplementationDetailsType As PrivateImplementationDetails Get Return m_privateImplType End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return m_containingModule End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return m_containingModule.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return Nothing End Get End Property Public NotOverridable Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public NotOverridable Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend NotOverridable Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Public NotOverridable Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return ImmutableArray(Of VisualBasicAttributeData).Empty End Function Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Features/Core/Portable/Completion/Providers/Scripting/AbstractDirectivePathCompletionProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using System.Diagnostics; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractDirectivePathCompletionProvider : CompletionProvider { protected static bool IsDirectorySeparator(char ch) => ch == '/' || (ch == '\\' && !PathUtilities.IsUnixLikePlatform); protected abstract bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken); /// <summary> /// <code>r</code> for metadata reference directive, <code>load</code> for source file directive. /// </summary> protected abstract string DirectiveName { get; } public sealed override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (!TryGetStringLiteralToken(tree, position, out var stringLiteral, cancellationToken)) { return; } var literalValue = stringLiteral.ToString(); context.CompletionListSpan = GetTextChangeSpan( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); var pathThroughLastSlash = GetPathThroughLastSlash( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); await ProvideCompletionsAsync(context, pathThroughLastSlash).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } public sealed override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { var lineStart = text.Lines.GetLineFromPosition(caretPosition).Start; // check if the line starts with {whitespace}#{whitespace}{DirectiveName}{whitespace}" var poundIndex = text.IndexOfNonWhiteSpace(lineStart, caretPosition - lineStart); if (poundIndex == -1 || text[poundIndex] != '#') { return false; } var directiveNameStartIndex = text.IndexOfNonWhiteSpace(poundIndex + 1, caretPosition - poundIndex - 1); if (directiveNameStartIndex == -1 || !text.ContentEquals(directiveNameStartIndex, DirectiveName)) { return false; } var directiveNameEndIndex = directiveNameStartIndex + DirectiveName.Length; var quoteIndex = text.IndexOfNonWhiteSpace(directiveNameEndIndex, caretPosition - directiveNameEndIndex); if (quoteIndex == -1 || text[quoteIndex] != '"') { return false; } return true; } private static string GetPathThroughLastSlash(string quotedPath, int quotedPathStart, int position) { Contract.ThrowIfTrue(quotedPath[0] != '"'); const int QuoteLength = 1; var positionInQuotedPath = position - quotedPathStart; var path = quotedPath[QuoteLength..positionInQuotedPath].Trim(); var afterLastSlashIndex = AfterLastSlashIndex(path, path.Length); // We want the portion up to, and including the last slash if there is one. That way if // the user pops up completion in the middle of a path (i.e. "C:\Win") then we'll // consider the path to be "C:\" and we will show appropriate completions. return afterLastSlashIndex >= 0 ? path.Substring(0, afterLastSlashIndex) : path; } private static TextSpan GetTextChangeSpan(string quotedPath, int quotedPathStart, int position) { // We want the text change to be from after the last slash to the end of the quoted // path. If there is no last slash, then we want it from right after the start quote // character. var positionInQuotedPath = position - quotedPathStart; // Where we want to start tracking is right after the slash (if we have one), or else // right after the string starts. var afterLastSlashIndex = AfterLastSlashIndex(quotedPath, positionInQuotedPath); var afterFirstQuote = 1; var startIndex = Math.Max(afterLastSlashIndex, afterFirstQuote); var endIndex = quotedPath.Length; // If the string ends with a quote, the we do not want to consume that. if (EndsWithQuote(quotedPath)) { endIndex--; } return TextSpan.FromBounds(startIndex + quotedPathStart, endIndex + quotedPathStart); } private static bool EndsWithQuote(string quotedPath) => quotedPath.Length >= 2 && quotedPath[quotedPath.Length - 1] == '"'; /// <summary> /// Returns the index right after the last slash that precedes 'position'. If there is no /// slash in the string, -1 is returned. /// </summary> private static int AfterLastSlashIndex(string text, int position) { // Position might be out of bounds of the string (if the string is unterminated. Make // sure it's within bounds. position = Math.Min(position, text.Length - 1); int index; if ((index = text.LastIndexOf('/', position)) >= 0 || !PathUtilities.IsUnixLikePlatform && (index = text.LastIndexOf('\\', position)) >= 0) { return index + 1; } return -1; } protected abstract Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash); protected static FileSystemCompletionHelper GetFileSystemCompletionHelper( Document document, Glyph itemGlyph, ImmutableArray<string> extensions, CompletionItemRules completionRules) { ImmutableArray<string> referenceSearchPaths; string? baseDirectory; if (document.Project.CompilationOptions?.MetadataReferenceResolver is RuntimeMetadataReferenceResolver resolver) { referenceSearchPaths = resolver.PathResolver.SearchPaths; baseDirectory = resolver.PathResolver.BaseDirectory; } else { referenceSearchPaths = ImmutableArray<string>.Empty; baseDirectory = null; } return new FileSystemCompletionHelper( Glyph.OpenFolder, itemGlyph, referenceSearchPaths, GetBaseDirectory(document, baseDirectory), extensions, completionRules); } private static string? GetBaseDirectory(Document document, string? baseDirectory) { var result = PathUtilities.GetDirectoryName(document.FilePath); if (!PathUtilities.IsAbsolute(result)) { result = baseDirectory; Debug.Assert(result == null || PathUtilities.IsAbsolute(result)); } return result; } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using System.Diagnostics; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractDirectivePathCompletionProvider : CompletionProvider { protected static bool IsDirectorySeparator(char ch) => ch == '/' || (ch == '\\' && !PathUtilities.IsUnixLikePlatform); protected abstract bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken); /// <summary> /// <code>r</code> for metadata reference directive, <code>load</code> for source file directive. /// </summary> protected abstract string DirectiveName { get; } public sealed override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (!TryGetStringLiteralToken(tree, position, out var stringLiteral, cancellationToken)) { return; } var literalValue = stringLiteral.ToString(); context.CompletionListSpan = GetTextChangeSpan( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); var pathThroughLastSlash = GetPathThroughLastSlash( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); await ProvideCompletionsAsync(context, pathThroughLastSlash).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } public sealed override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { var lineStart = text.Lines.GetLineFromPosition(caretPosition).Start; // check if the line starts with {whitespace}#{whitespace}{DirectiveName}{whitespace}" var poundIndex = text.IndexOfNonWhiteSpace(lineStart, caretPosition - lineStart); if (poundIndex == -1 || text[poundIndex] != '#') { return false; } var directiveNameStartIndex = text.IndexOfNonWhiteSpace(poundIndex + 1, caretPosition - poundIndex - 1); if (directiveNameStartIndex == -1 || !text.ContentEquals(directiveNameStartIndex, DirectiveName)) { return false; } var directiveNameEndIndex = directiveNameStartIndex + DirectiveName.Length; var quoteIndex = text.IndexOfNonWhiteSpace(directiveNameEndIndex, caretPosition - directiveNameEndIndex); if (quoteIndex == -1 || text[quoteIndex] != '"') { return false; } return true; } private static string GetPathThroughLastSlash(string quotedPath, int quotedPathStart, int position) { Contract.ThrowIfTrue(quotedPath[0] != '"'); const int QuoteLength = 1; var positionInQuotedPath = position - quotedPathStart; var path = quotedPath[QuoteLength..positionInQuotedPath].Trim(); var afterLastSlashIndex = AfterLastSlashIndex(path, path.Length); // We want the portion up to, and including the last slash if there is one. That way if // the user pops up completion in the middle of a path (i.e. "C:\Win") then we'll // consider the path to be "C:\" and we will show appropriate completions. return afterLastSlashIndex >= 0 ? path.Substring(0, afterLastSlashIndex) : path; } private static TextSpan GetTextChangeSpan(string quotedPath, int quotedPathStart, int position) { // We want the text change to be from after the last slash to the end of the quoted // path. If there is no last slash, then we want it from right after the start quote // character. var positionInQuotedPath = position - quotedPathStart; // Where we want to start tracking is right after the slash (if we have one), or else // right after the string starts. var afterLastSlashIndex = AfterLastSlashIndex(quotedPath, positionInQuotedPath); var afterFirstQuote = 1; var startIndex = Math.Max(afterLastSlashIndex, afterFirstQuote); var endIndex = quotedPath.Length; // If the string ends with a quote, the we do not want to consume that. if (EndsWithQuote(quotedPath)) { endIndex--; } return TextSpan.FromBounds(startIndex + quotedPathStart, endIndex + quotedPathStart); } private static bool EndsWithQuote(string quotedPath) => quotedPath.Length >= 2 && quotedPath[quotedPath.Length - 1] == '"'; /// <summary> /// Returns the index right after the last slash that precedes 'position'. If there is no /// slash in the string, -1 is returned. /// </summary> private static int AfterLastSlashIndex(string text, int position) { // Position might be out of bounds of the string (if the string is unterminated. Make // sure it's within bounds. position = Math.Min(position, text.Length - 1); int index; if ((index = text.LastIndexOf('/', position)) >= 0 || !PathUtilities.IsUnixLikePlatform && (index = text.LastIndexOf('\\', position)) >= 0) { return index + 1; } return -1; } protected abstract Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash); protected static FileSystemCompletionHelper GetFileSystemCompletionHelper( Document document, Glyph itemGlyph, ImmutableArray<string> extensions, CompletionItemRules completionRules) { ImmutableArray<string> referenceSearchPaths; string? baseDirectory; if (document.Project.CompilationOptions?.MetadataReferenceResolver is RuntimeMetadataReferenceResolver resolver) { referenceSearchPaths = resolver.PathResolver.SearchPaths; baseDirectory = resolver.PathResolver.BaseDirectory; } else { referenceSearchPaths = ImmutableArray<string>.Empty; baseDirectory = null; } return new FileSystemCompletionHelper( Glyph.OpenFolder, itemGlyph, referenceSearchPaths, GetBaseDirectory(document, baseDirectory), extensions, completionRules); } private static string? GetBaseDirectory(Document document, string? baseDirectory) { var result = PathUtilities.GetDirectoryName(document.FilePath); if (!PathUtilities.IsAbsolute(result)) { result = baseDirectory; Debug.Assert(result == null || PathUtilities.IsAbsolute(result)); } return result; } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider.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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { internal partial class UseExpressionBodyForLambdaCodeStyleProvider : AbstractCodeStyleProvider<ExpressionBodyPreference, UseExpressionBodyForLambdaCodeStyleProvider> { private static readonly LocalizableString UseExpressionBodyTitle = new LocalizableResourceString(nameof(FeaturesResources.Use_expression_body_for_lambda_expressions), FeaturesResources.ResourceManager, typeof(FeaturesResources)); private static readonly LocalizableString UseBlockBodyTitle = new LocalizableResourceString(nameof(FeaturesResources.Use_block_body_for_lambda_expressions), FeaturesResources.ResourceManager, typeof(FeaturesResources)); public UseExpressionBodyForLambdaCodeStyleProvider() : base(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, LanguageNames.CSharp, IDEDiagnosticIds.UseExpressionBodyForLambdaExpressionsDiagnosticId, EnforceOnBuildValues.UseExpressionBodyForLambdaExpressions, UseExpressionBodyTitle, UseExpressionBodyTitle) { } // Shared code needed by all parts of the style provider for this feature. private static ExpressionSyntax GetBodyAsExpression(LambdaExpressionSyntax declaration) => declaration.Body as ExpressionSyntax; private static bool CanOfferUseExpressionBody( ExpressionBodyPreference preference, LambdaExpressionSyntax declaration) { var userPrefersExpressionBodies = preference != ExpressionBodyPreference.Never; if (!userPrefersExpressionBodies) { // If the user doesn't even want expression bodies, then certainly do not offer. return false; } var expressionBody = GetBodyAsExpression(declaration); if (expressionBody != null) { // they already have an expression body. so nothing to do here. return false; } // They don't have an expression body. See if we could convert the block they // have into one. var options = declaration.SyntaxTree.Options; return TryConvertToExpressionBody(declaration, options, preference, out _, out _); } private static bool TryConvertToExpressionBody( LambdaExpressionSyntax declaration, ParseOptions options, ExpressionBodyPreference conversionPreference, out ExpressionSyntax expression, out SyntaxToken semicolon) { var body = declaration.Body as BlockSyntax; return body.TryConvertToExpressionBody( options, conversionPreference, out expression, out semicolon); } private static bool CanOfferUseBlockBody( SemanticModel semanticModel, ExpressionBodyPreference preference, LambdaExpressionSyntax declaration, CancellationToken cancellationToken) { var userPrefersBlockBodies = preference == ExpressionBodyPreference.Never; if (!userPrefersBlockBodies) { // If the user doesn't even want block bodies, then certainly do not offer. return false; } var expressionBodyOpt = GetBodyAsExpression(declaration); if (expressionBodyOpt == null) { // they already have a block body. return false; } // We need to know what sort of lambda this is (void returning or not) in order to be // able to create the right sort of block body (i.e. with a return-statement or // expr-statement). So, if we can't figure out what lambda type this is, we should not // proceed. if (semanticModel.GetTypeInfo(declaration, cancellationToken).ConvertedType is not INamedTypeSymbol lambdaType || lambdaType.DelegateInvokeMethod == null) { return false; } var canOffer = expressionBodyOpt.TryConvertToStatement( semicolonTokenOpt: null, createReturnStatementForExpression: false, out _); if (!canOffer) { // Couldn't even convert the expression into statement form. return false; } var languageVersion = ((CSharpParseOptions)declaration.SyntaxTree.Options).LanguageVersion; if (expressionBodyOpt.IsKind(SyntaxKind.ThrowExpression) && languageVersion < LanguageVersion.CSharp7) { // Can't convert this prior to C# 7 because ```a => throw ...``` isn't allowed. return false; } return true; } private static LambdaExpressionSyntax Update(SemanticModel semanticModel, LambdaExpressionSyntax originalDeclaration, LambdaExpressionSyntax currentDeclaration) => UpdateWorker(semanticModel, originalDeclaration, currentDeclaration).WithAdditionalAnnotations(Formatter.Annotation); private static LambdaExpressionSyntax UpdateWorker( SemanticModel semanticModel, LambdaExpressionSyntax originalDeclaration, LambdaExpressionSyntax currentDeclaration) { var expressionBody = GetBodyAsExpression(currentDeclaration); return expressionBody == null ? WithExpressionBody(currentDeclaration) : WithBlockBody(semanticModel, originalDeclaration, currentDeclaration); } private static LambdaExpressionSyntax WithExpressionBody(LambdaExpressionSyntax declaration) { if (!TryConvertToExpressionBody( declaration, declaration.SyntaxTree.Options, ExpressionBodyPreference.WhenPossible, out var expressionBody, out _)) { return declaration; } var updatedDecl = declaration.WithBody(expressionBody); // If there will only be whitespace between the arrow and the body, then replace that // with a single space so that the lambda doesn't have superfluous newlines in it. if (declaration.ArrowToken.TrailingTrivia.All(t => t.IsWhitespaceOrEndOfLine()) && expressionBody.GetLeadingTrivia().All(t => t.IsWhitespaceOrEndOfLine())) { updatedDecl = updatedDecl.WithArrowToken(updatedDecl.ArrowToken.WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } return updatedDecl; } private static LambdaExpressionSyntax WithBlockBody( SemanticModel semanticModel, LambdaExpressionSyntax originalDeclaration, LambdaExpressionSyntax currentDeclaration) { var expressionBody = GetBodyAsExpression(currentDeclaration); var createReturnStatementForExpression = CreateReturnStatementForExpression( semanticModel, originalDeclaration); if (!expressionBody.TryConvertToStatement( semicolonTokenOpt: null, createReturnStatementForExpression, out var statement)) { return currentDeclaration; } // If the user is converting to a block, it's likely they intend to add multiple // statements to it. So make a multi-line block so that things are formatted properly // for them to do so. return currentDeclaration.WithBody(SyntaxFactory.Block( SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed), SyntaxFactory.SingletonList(statement), SyntaxFactory.Token(SyntaxKind.CloseBraceToken))); } private static bool CreateReturnStatementForExpression( SemanticModel semanticModel, LambdaExpressionSyntax declaration) { var lambdaType = (INamedTypeSymbol)semanticModel.GetTypeInfo(declaration).ConvertedType; if (lambdaType.DelegateInvokeMethod.ReturnsVoid) { return false; } // 'async Task' is effectively a void-returning lambda. we do not want to create // 'return statements' when converting. if (declaration.AsyncKeyword != default) { var returnType = lambdaType.DelegateInvokeMethod.ReturnType; if (returnType.IsErrorType()) { // "async Goo" where 'Goo' failed to bind. If 'Goo' is 'Task' then it's // reasonable to assume this is just a missing 'using' and that this is a true // "async Task" lambda. If the name isn't 'Task', then this looks like a // real return type, and we should use return statements. return returnType.Name != nameof(Task); } var taskType = semanticModel.Compilation.GetTypeByMetadataName(typeof(Task).FullName); if (returnType.Equals(taskType)) { // 'async Task'. definitely do not create a 'return' statement; return false; } } return true; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } // Stub classes needed only for exporting purposes. [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExpressionBodyForLambda), Shared] internal sealed class UseExpressionBodyForLambdaCodeFixProvider : UseExpressionBodyForLambdaCodeStyleProvider.CodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExpressionBodyForLambdaCodeFixProvider() { } } [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseExpressionBodyForLambda), Shared] internal sealed class UseExpressionBodyForLambdaCodeRefactoringProvider : UseExpressionBodyForLambdaCodeStyleProvider.CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExpressionBodyForLambdaCodeRefactoringProvider() { } } [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class UseExpressionBodyForLambdaDiagnosticAnalyzer : UseExpressionBodyForLambdaCodeStyleProvider.DiagnosticAnalyzer { } }
// 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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { internal partial class UseExpressionBodyForLambdaCodeStyleProvider : AbstractCodeStyleProvider<ExpressionBodyPreference, UseExpressionBodyForLambdaCodeStyleProvider> { private static readonly LocalizableString UseExpressionBodyTitle = new LocalizableResourceString(nameof(FeaturesResources.Use_expression_body_for_lambda_expressions), FeaturesResources.ResourceManager, typeof(FeaturesResources)); private static readonly LocalizableString UseBlockBodyTitle = new LocalizableResourceString(nameof(FeaturesResources.Use_block_body_for_lambda_expressions), FeaturesResources.ResourceManager, typeof(FeaturesResources)); public UseExpressionBodyForLambdaCodeStyleProvider() : base(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, LanguageNames.CSharp, IDEDiagnosticIds.UseExpressionBodyForLambdaExpressionsDiagnosticId, EnforceOnBuildValues.UseExpressionBodyForLambdaExpressions, UseExpressionBodyTitle, UseExpressionBodyTitle) { } // Shared code needed by all parts of the style provider for this feature. private static ExpressionSyntax GetBodyAsExpression(LambdaExpressionSyntax declaration) => declaration.Body as ExpressionSyntax; private static bool CanOfferUseExpressionBody( ExpressionBodyPreference preference, LambdaExpressionSyntax declaration) { var userPrefersExpressionBodies = preference != ExpressionBodyPreference.Never; if (!userPrefersExpressionBodies) { // If the user doesn't even want expression bodies, then certainly do not offer. return false; } var expressionBody = GetBodyAsExpression(declaration); if (expressionBody != null) { // they already have an expression body. so nothing to do here. return false; } // They don't have an expression body. See if we could convert the block they // have into one. var options = declaration.SyntaxTree.Options; return TryConvertToExpressionBody(declaration, options, preference, out _, out _); } private static bool TryConvertToExpressionBody( LambdaExpressionSyntax declaration, ParseOptions options, ExpressionBodyPreference conversionPreference, out ExpressionSyntax expression, out SyntaxToken semicolon) { var body = declaration.Body as BlockSyntax; return body.TryConvertToExpressionBody( options, conversionPreference, out expression, out semicolon); } private static bool CanOfferUseBlockBody( SemanticModel semanticModel, ExpressionBodyPreference preference, LambdaExpressionSyntax declaration, CancellationToken cancellationToken) { var userPrefersBlockBodies = preference == ExpressionBodyPreference.Never; if (!userPrefersBlockBodies) { // If the user doesn't even want block bodies, then certainly do not offer. return false; } var expressionBodyOpt = GetBodyAsExpression(declaration); if (expressionBodyOpt == null) { // they already have a block body. return false; } // We need to know what sort of lambda this is (void returning or not) in order to be // able to create the right sort of block body (i.e. with a return-statement or // expr-statement). So, if we can't figure out what lambda type this is, we should not // proceed. if (semanticModel.GetTypeInfo(declaration, cancellationToken).ConvertedType is not INamedTypeSymbol lambdaType || lambdaType.DelegateInvokeMethod == null) { return false; } var canOffer = expressionBodyOpt.TryConvertToStatement( semicolonTokenOpt: null, createReturnStatementForExpression: false, out _); if (!canOffer) { // Couldn't even convert the expression into statement form. return false; } var languageVersion = ((CSharpParseOptions)declaration.SyntaxTree.Options).LanguageVersion; if (expressionBodyOpt.IsKind(SyntaxKind.ThrowExpression) && languageVersion < LanguageVersion.CSharp7) { // Can't convert this prior to C# 7 because ```a => throw ...``` isn't allowed. return false; } return true; } private static LambdaExpressionSyntax Update(SemanticModel semanticModel, LambdaExpressionSyntax originalDeclaration, LambdaExpressionSyntax currentDeclaration) => UpdateWorker(semanticModel, originalDeclaration, currentDeclaration).WithAdditionalAnnotations(Formatter.Annotation); private static LambdaExpressionSyntax UpdateWorker( SemanticModel semanticModel, LambdaExpressionSyntax originalDeclaration, LambdaExpressionSyntax currentDeclaration) { var expressionBody = GetBodyAsExpression(currentDeclaration); return expressionBody == null ? WithExpressionBody(currentDeclaration) : WithBlockBody(semanticModel, originalDeclaration, currentDeclaration); } private static LambdaExpressionSyntax WithExpressionBody(LambdaExpressionSyntax declaration) { if (!TryConvertToExpressionBody( declaration, declaration.SyntaxTree.Options, ExpressionBodyPreference.WhenPossible, out var expressionBody, out _)) { return declaration; } var updatedDecl = declaration.WithBody(expressionBody); // If there will only be whitespace between the arrow and the body, then replace that // with a single space so that the lambda doesn't have superfluous newlines in it. if (declaration.ArrowToken.TrailingTrivia.All(t => t.IsWhitespaceOrEndOfLine()) && expressionBody.GetLeadingTrivia().All(t => t.IsWhitespaceOrEndOfLine())) { updatedDecl = updatedDecl.WithArrowToken(updatedDecl.ArrowToken.WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } return updatedDecl; } private static LambdaExpressionSyntax WithBlockBody( SemanticModel semanticModel, LambdaExpressionSyntax originalDeclaration, LambdaExpressionSyntax currentDeclaration) { var expressionBody = GetBodyAsExpression(currentDeclaration); var createReturnStatementForExpression = CreateReturnStatementForExpression( semanticModel, originalDeclaration); if (!expressionBody.TryConvertToStatement( semicolonTokenOpt: null, createReturnStatementForExpression, out var statement)) { return currentDeclaration; } // If the user is converting to a block, it's likely they intend to add multiple // statements to it. So make a multi-line block so that things are formatted properly // for them to do so. return currentDeclaration.WithBody(SyntaxFactory.Block( SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed), SyntaxFactory.SingletonList(statement), SyntaxFactory.Token(SyntaxKind.CloseBraceToken))); } private static bool CreateReturnStatementForExpression( SemanticModel semanticModel, LambdaExpressionSyntax declaration) { var lambdaType = (INamedTypeSymbol)semanticModel.GetTypeInfo(declaration).ConvertedType; if (lambdaType.DelegateInvokeMethod.ReturnsVoid) { return false; } // 'async Task' is effectively a void-returning lambda. we do not want to create // 'return statements' when converting. if (declaration.AsyncKeyword != default) { var returnType = lambdaType.DelegateInvokeMethod.ReturnType; if (returnType.IsErrorType()) { // "async Goo" where 'Goo' failed to bind. If 'Goo' is 'Task' then it's // reasonable to assume this is just a missing 'using' and that this is a true // "async Task" lambda. If the name isn't 'Task', then this looks like a // real return type, and we should use return statements. return returnType.Name != nameof(Task); } var taskType = semanticModel.Compilation.GetTypeByMetadataName(typeof(Task).FullName); if (returnType.Equals(taskType)) { // 'async Task'. definitely do not create a 'return' statement; return false; } } return true; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } // Stub classes needed only for exporting purposes. [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExpressionBodyForLambda), Shared] internal sealed class UseExpressionBodyForLambdaCodeFixProvider : UseExpressionBodyForLambdaCodeStyleProvider.CodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExpressionBodyForLambdaCodeFixProvider() { } } [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseExpressionBodyForLambda), Shared] internal sealed class UseExpressionBodyForLambdaCodeRefactoringProvider : UseExpressionBodyForLambdaCodeStyleProvider.CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExpressionBodyForLambdaCodeRefactoringProvider() { } } [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class UseExpressionBodyForLambdaDiagnosticAnalyzer : UseExpressionBodyForLambdaCodeStyleProvider.DiagnosticAnalyzer { } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Workspaces/Core/Portable/EmbeddedLanguages/LanguageServices/FallbackSyntaxClassifier.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.Threading; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices { internal class FallbackSyntaxClassifier : AbstractSyntaxClassifier { private readonly EmbeddedLanguageInfo _info; public override ImmutableArray<int> SyntaxTokenKinds { get; } public FallbackSyntaxClassifier(EmbeddedLanguageInfo info) { _info = info; SyntaxTokenKinds = ImmutableArray.Create( info.CharLiteralTokenKind, info.StringLiteralTokenKind, info.InterpolatedTextTokenKind); } public override void AddClassifications( Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (_info.CharLiteralTokenKind != token.RawKind && _info.StringLiteralTokenKind != token.RawKind && _info.InterpolatedTextTokenKind != token.RawKind) { return; } var virtualChars = _info.VirtualCharService.TryConvertToVirtualChars(token); if (virtualChars.IsDefaultOrEmpty) { return; } foreach (var vc in virtualChars) { if (vc.Span.Length > 1) { result.Add(new ClassifiedSpan(ClassificationTypeNames.StringEscapeCharacter, vc.Span)); } } } } }
// 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.Threading; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices { internal class FallbackSyntaxClassifier : AbstractSyntaxClassifier { private readonly EmbeddedLanguageInfo _info; public override ImmutableArray<int> SyntaxTokenKinds { get; } public FallbackSyntaxClassifier(EmbeddedLanguageInfo info) { _info = info; SyntaxTokenKinds = ImmutableArray.Create( info.CharLiteralTokenKind, info.StringLiteralTokenKind, info.InterpolatedTextTokenKind); } public override void AddClassifications( Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (_info.CharLiteralTokenKind != token.RawKind && _info.StringLiteralTokenKind != token.RawKind && _info.InterpolatedTextTokenKind != token.RawKind) { return; } var virtualChars = _info.VirtualCharService.TryConvertToVirtualChars(token); if (virtualChars.IsDefaultOrEmpty) { return; } foreach (var vc in virtualChars) { if (vc.Span.Length > 1) { result.Add(new ClassifiedSpan(ClassificationTypeNames.StringEscapeCharacter, vc.Span)); } } } } }
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Compilers/VisualBasic/Portable/Scanner/QuickTokenAccumulator.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. '----------------------------------------------------------------------------- ' Contains quick token accumulator. '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax '' The QuickTokenAccumulator is a small mini-tokenizer that may fail. It consumes characters and '' eventually either decides that either it found a complete token (including the trivia on either '' side), or it gives up and says that the full scanner should take an attempt. It also accumulates the '' token into a character buffer and computes a hash code. The entire tokenization is done by a single '' routine without any memory allocations to keep it very fast. '' '' Currently it only handles two cases: '' optional-whitespace keyword-or-identifier optional-whitespace '' optional-whitespace single-char-punctuation optional-whitespace '' '' where the whitespace does not include newlines. ' '' The VB tokenization rules are complex, and care needs to be taken in constructing the quick '' tokenization. For example "REM" begins a comment, so it can't be tokenized as a keyword or identifier. '' Similar problems arise with multi-character punctuation tokens, which can have embedded spaces. Partial Friend Class Scanner ''' <summary> ''' The possible states that the mini scanning can be in. ''' </summary> Private Enum AccumulatorState Initial InitialAllowLeadingMultilineTrivia Ident TypeChar FollowingWhite Punctuation CompoundPunctStart CR Done Bad End Enum ' Flags used to classify characters. <Flags()> Private Enum CharFlags As UShort White = 1 << 0 ' simple whitespace (space/tab) Letter = 1 << 1 ' letter, except for "R" (because of REM) and "_" IdentOnly = 1 << 2 ' allowed only in identifiers (cannot start one) - letter "R" (because of REM), "_" TypeChar = 1 << 3 ' legal type character (except !, which is contextually dictionary lookup Punct = 1 << 4 ' some simple punctuation (parens, braces, dot, comma, equals, question) CompoundPunctStart = 1 << 5 ' may be a part of compound punctuation. will be used only if followed by (not white) && (not punct) CR = 1 << 6 ' CR LF = 1 << 7 ' LF Digit = 1 << 8 ' digit 0-9 Complex = 1 << 9 ' complex - causes scanning to abort End Enum 'TODO: why : and ; are complex? (8th row, 3 and 4) ' The following table classifies the first &H180 Unicode characters. ' R and r are marked as COMPLEX so that quick-scanning doesn't stop after "REM". ' # is marked complex as it may start directives. ' < = > are complex because they might start a merge conflict marker. ' PERF: Use UShort instead of CharFlags so the compiler can use array literal initialization. ' The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. Private Shared ReadOnly s_charProperties As UShort() = { CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.White, CharFlags.LF, CharFlags.Complex, CharFlags.Complex, CharFlags.CR, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, _ _ CharFlags.White, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.TypeChar, CharFlags.TypeChar, CharFlags.TypeChar, CharFlags.Complex, CharFlags.Punct, CharFlags.Punct, CharFlags.CompoundPunctStart, CharFlags.CompoundPunctStart, CharFlags.Punct, CharFlags.CompoundPunctStart, CharFlags.Punct, CharFlags.CompoundPunctStart, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Punct, _ _ CharFlags.TypeChar, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.IdentOnly, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Complex, CharFlags.CompoundPunctStart, CharFlags.Complex, CharFlags.CompoundPunctStart, CharFlags.IdentOnly, _ _ CharFlags.Complex, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.IdentOnly, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Punct, CharFlags.Complex, CharFlags.Punct, CharFlags.Complex, CharFlags.Complex, _ CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, _ _ CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Letter, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Letter, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Letter, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Complex, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Complex, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter} ' Size of the above table. Private Const s_CHARPROP_LENGTH = &H180 ' Maximum length of a token to scan Friend Const MAX_CACHED_TOKENSIZE = 42 Shared Sub New() Debug.Assert(s_charProperties.Length = s_CHARPROP_LENGTH) End Sub Public Structure QuickScanResult Public Sub New(start As Integer, length As Integer, chars As Char(), hashCode As Integer, terminatorLength As Byte) Me.Start = start Me.Length = length Me.Chars = chars Me.HashCode = hashCode Me.TerminatorLength = terminatorLength End Sub Public ReadOnly Chars As Char() Public ReadOnly Start As Integer Public ReadOnly Length As Integer Public ReadOnly HashCode As Integer Public ReadOnly TerminatorLength As Byte Public ReadOnly Property Succeeded As Boolean Get Return Me.Length > 0 End Get End Property End Structure ' Attempt to scan a single token. ' If it succeeds, return True, and the characters, length, and hashcode of the token ' can be retrieved by other functions. ' If it fails (the token is too complex), return False. Public Function QuickScanToken(allowLeadingMultilineTrivia As Boolean) As QuickScanResult Dim state As AccumulatorState = If(allowLeadingMultilineTrivia, AccumulatorState.InitialAllowLeadingMultilineTrivia, AccumulatorState.Initial) Dim offset = _lineBufferOffset Dim page = _curPage If page Is Nothing OrElse page._pageStart <> (offset And s_NOT_PAGE_MASK) Then page = GetPage(offset) End If Dim pageArr As Char() = page._arr Dim qtChars = pageArr Dim index = _lineBufferOffset And s_PAGE_MASK Dim qtStart = index Dim limit = index + Math.Min(MAX_CACHED_TOKENSIZE, _bufferLen - offset) limit = Math.Min(limit, pageArr.Length) Dim hashCode As Integer = Hash.FnvOffsetBias Dim terminatorLength As Byte = 0 Dim unicodeValue As Integer = 0 While index < limit ' Get current character. Dim c = pageArr(index) ' Get the flags for that character. unicodeValue = AscW(c) If unicodeValue >= s_CHARPROP_LENGTH Then Exit While End If Dim flags = s_charProperties(unicodeValue) ' Advance the scanner state. Select Case state Case AccumulatorState.InitialAllowLeadingMultilineTrivia If flags = CharFlags.Letter Then state = AccumulatorState.Ident ElseIf flags = CharFlags.Punct Then state = AccumulatorState.Punctuation ElseIf flags = CharFlags.CompoundPunctStart Then state = AccumulatorState.CompoundPunctStart ElseIf (flags And (CharFlags.White Or CharFlags.CR Or CharFlags.LF)) <> 0 Then ' stay in AccumulatorState.InitialNewStatement Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.Initial If flags = CharFlags.Letter Then state = AccumulatorState.Ident ElseIf flags = CharFlags.Punct Then state = AccumulatorState.Punctuation ElseIf flags = CharFlags.CompoundPunctStart Then state = AccumulatorState.CompoundPunctStart ElseIf flags = CharFlags.White Then ' stay in AccumulatorState.Initial Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.Ident If (flags And (CharFlags.Letter Or CharFlags.IdentOnly Or CharFlags.Digit)) <> 0 Then ' stay in Ident ElseIf flags = CharFlags.White Then state = AccumulatorState.FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf flags = CharFlags.TypeChar Then state = AccumulatorState.TypeChar ElseIf flags = CharFlags.Punct Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.TypeChar If flags = CharFlags.White Then state = AccumulatorState.FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf (flags And (CharFlags.Punct Or CharFlags.Digit Or CharFlags.TypeChar)) <> 0 Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.FollowingWhite If flags = CharFlags.White Then ' stay in FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf (flags And (CharFlags.Complex Or CharFlags.IdentOnly)) <> 0 Then state = AccumulatorState.Bad Exit While Else state = AccumulatorState.Done Exit While End If Case AccumulatorState.Punctuation If flags = CharFlags.White Then state = AccumulatorState.FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf (flags And (CharFlags.Letter Or CharFlags.Punct)) <> 0 Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.CompoundPunctStart If flags = CharFlags.White Then ' stay in CompoundPunctStart ElseIf (flags And (CharFlags.Letter Or CharFlags.Digit)) <> 0 Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.CR If flags = CharFlags.LF Then terminatorLength = 2 state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad End If Exit While Case Else Debug.Assert(False, "should not get here") End Select index += 1 'FNV-like hash should work here 'since these strings are short and mostly ASCII hashCode = (hashCode Xor unicodeValue) * Hash.FnvPrime End While If state = AccumulatorState.Done AndAlso (terminatorLength = 0 OrElse Not Me._IsScanningXmlDoc) Then If terminatorLength <> 0 Then index += 1 hashCode = (hashCode Xor unicodeValue) * Hash.FnvPrime End If Return New QuickScanResult(qtStart, index - qtStart, qtChars, hashCode, terminatorLength) Else Return Nothing End If 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. '----------------------------------------------------------------------------- ' Contains quick token accumulator. '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax '' The QuickTokenAccumulator is a small mini-tokenizer that may fail. It consumes characters and '' eventually either decides that either it found a complete token (including the trivia on either '' side), or it gives up and says that the full scanner should take an attempt. It also accumulates the '' token into a character buffer and computes a hash code. The entire tokenization is done by a single '' routine without any memory allocations to keep it very fast. '' '' Currently it only handles two cases: '' optional-whitespace keyword-or-identifier optional-whitespace '' optional-whitespace single-char-punctuation optional-whitespace '' '' where the whitespace does not include newlines. ' '' The VB tokenization rules are complex, and care needs to be taken in constructing the quick '' tokenization. For example "REM" begins a comment, so it can't be tokenized as a keyword or identifier. '' Similar problems arise with multi-character punctuation tokens, which can have embedded spaces. Partial Friend Class Scanner ''' <summary> ''' The possible states that the mini scanning can be in. ''' </summary> Private Enum AccumulatorState Initial InitialAllowLeadingMultilineTrivia Ident TypeChar FollowingWhite Punctuation CompoundPunctStart CR Done Bad End Enum ' Flags used to classify characters. <Flags()> Private Enum CharFlags As UShort White = 1 << 0 ' simple whitespace (space/tab) Letter = 1 << 1 ' letter, except for "R" (because of REM) and "_" IdentOnly = 1 << 2 ' allowed only in identifiers (cannot start one) - letter "R" (because of REM), "_" TypeChar = 1 << 3 ' legal type character (except !, which is contextually dictionary lookup Punct = 1 << 4 ' some simple punctuation (parens, braces, dot, comma, equals, question) CompoundPunctStart = 1 << 5 ' may be a part of compound punctuation. will be used only if followed by (not white) && (not punct) CR = 1 << 6 ' CR LF = 1 << 7 ' LF Digit = 1 << 8 ' digit 0-9 Complex = 1 << 9 ' complex - causes scanning to abort End Enum 'TODO: why : and ; are complex? (8th row, 3 and 4) ' The following table classifies the first &H180 Unicode characters. ' R and r are marked as COMPLEX so that quick-scanning doesn't stop after "REM". ' # is marked complex as it may start directives. ' < = > are complex because they might start a merge conflict marker. ' PERF: Use UShort instead of CharFlags so the compiler can use array literal initialization. ' The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. Private Shared ReadOnly s_charProperties As UShort() = { CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.White, CharFlags.LF, CharFlags.Complex, CharFlags.Complex, CharFlags.CR, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, _ _ CharFlags.White, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.TypeChar, CharFlags.TypeChar, CharFlags.TypeChar, CharFlags.Complex, CharFlags.Punct, CharFlags.Punct, CharFlags.CompoundPunctStart, CharFlags.CompoundPunctStart, CharFlags.Punct, CharFlags.CompoundPunctStart, CharFlags.Punct, CharFlags.CompoundPunctStart, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Digit, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Punct, _ _ CharFlags.TypeChar, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.IdentOnly, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Complex, CharFlags.CompoundPunctStart, CharFlags.Complex, CharFlags.CompoundPunctStart, CharFlags.IdentOnly, _ _ CharFlags.Complex, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.IdentOnly, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Punct, CharFlags.Complex, CharFlags.Punct, CharFlags.Complex, CharFlags.Complex, _ CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, _ _ CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Letter, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Letter, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Letter, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, CharFlags.Complex, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Complex, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Complex, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, _ _ CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter, CharFlags.Letter} ' Size of the above table. Private Const s_CHARPROP_LENGTH = &H180 ' Maximum length of a token to scan Friend Const MAX_CACHED_TOKENSIZE = 42 Shared Sub New() Debug.Assert(s_charProperties.Length = s_CHARPROP_LENGTH) End Sub Public Structure QuickScanResult Public Sub New(start As Integer, length As Integer, chars As Char(), hashCode As Integer, terminatorLength As Byte) Me.Start = start Me.Length = length Me.Chars = chars Me.HashCode = hashCode Me.TerminatorLength = terminatorLength End Sub Public ReadOnly Chars As Char() Public ReadOnly Start As Integer Public ReadOnly Length As Integer Public ReadOnly HashCode As Integer Public ReadOnly TerminatorLength As Byte Public ReadOnly Property Succeeded As Boolean Get Return Me.Length > 0 End Get End Property End Structure ' Attempt to scan a single token. ' If it succeeds, return True, and the characters, length, and hashcode of the token ' can be retrieved by other functions. ' If it fails (the token is too complex), return False. Public Function QuickScanToken(allowLeadingMultilineTrivia As Boolean) As QuickScanResult Dim state As AccumulatorState = If(allowLeadingMultilineTrivia, AccumulatorState.InitialAllowLeadingMultilineTrivia, AccumulatorState.Initial) Dim offset = _lineBufferOffset Dim page = _curPage If page Is Nothing OrElse page._pageStart <> (offset And s_NOT_PAGE_MASK) Then page = GetPage(offset) End If Dim pageArr As Char() = page._arr Dim qtChars = pageArr Dim index = _lineBufferOffset And s_PAGE_MASK Dim qtStart = index Dim limit = index + Math.Min(MAX_CACHED_TOKENSIZE, _bufferLen - offset) limit = Math.Min(limit, pageArr.Length) Dim hashCode As Integer = Hash.FnvOffsetBias Dim terminatorLength As Byte = 0 Dim unicodeValue As Integer = 0 While index < limit ' Get current character. Dim c = pageArr(index) ' Get the flags for that character. unicodeValue = AscW(c) If unicodeValue >= s_CHARPROP_LENGTH Then Exit While End If Dim flags = s_charProperties(unicodeValue) ' Advance the scanner state. Select Case state Case AccumulatorState.InitialAllowLeadingMultilineTrivia If flags = CharFlags.Letter Then state = AccumulatorState.Ident ElseIf flags = CharFlags.Punct Then state = AccumulatorState.Punctuation ElseIf flags = CharFlags.CompoundPunctStart Then state = AccumulatorState.CompoundPunctStart ElseIf (flags And (CharFlags.White Or CharFlags.CR Or CharFlags.LF)) <> 0 Then ' stay in AccumulatorState.InitialNewStatement Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.Initial If flags = CharFlags.Letter Then state = AccumulatorState.Ident ElseIf flags = CharFlags.Punct Then state = AccumulatorState.Punctuation ElseIf flags = CharFlags.CompoundPunctStart Then state = AccumulatorState.CompoundPunctStart ElseIf flags = CharFlags.White Then ' stay in AccumulatorState.Initial Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.Ident If (flags And (CharFlags.Letter Or CharFlags.IdentOnly Or CharFlags.Digit)) <> 0 Then ' stay in Ident ElseIf flags = CharFlags.White Then state = AccumulatorState.FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf flags = CharFlags.TypeChar Then state = AccumulatorState.TypeChar ElseIf flags = CharFlags.Punct Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.TypeChar If flags = CharFlags.White Then state = AccumulatorState.FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf (flags And (CharFlags.Punct Or CharFlags.Digit Or CharFlags.TypeChar)) <> 0 Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.FollowingWhite If flags = CharFlags.White Then ' stay in FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf (flags And (CharFlags.Complex Or CharFlags.IdentOnly)) <> 0 Then state = AccumulatorState.Bad Exit While Else state = AccumulatorState.Done Exit While End If Case AccumulatorState.Punctuation If flags = CharFlags.White Then state = AccumulatorState.FollowingWhite ElseIf flags = CharFlags.CR Then state = AccumulatorState.CR ElseIf flags = CharFlags.LF Then terminatorLength = 1 state = AccumulatorState.Done Exit While ElseIf (flags And (CharFlags.Letter Or CharFlags.Punct)) <> 0 Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.CompoundPunctStart If flags = CharFlags.White Then ' stay in CompoundPunctStart ElseIf (flags And (CharFlags.Letter Or CharFlags.Digit)) <> 0 Then state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad Exit While End If Case AccumulatorState.CR If flags = CharFlags.LF Then terminatorLength = 2 state = AccumulatorState.Done Exit While Else state = AccumulatorState.Bad End If Exit While Case Else Debug.Assert(False, "should not get here") End Select index += 1 'FNV-like hash should work here 'since these strings are short and mostly ASCII hashCode = (hashCode Xor unicodeValue) * Hash.FnvPrime End While If state = AccumulatorState.Done AndAlso (terminatorLength = 0 OrElse Not Me._IsScanningXmlDoc) Then If terminatorLength <> 0 Then index += 1 hashCode = (hashCode Xor unicodeValue) * Hash.FnvPrime End If Return New QuickScanResult(qtStart, index - qtStart, qtChars, hashCode, terminatorLength) Else Return Nothing End If End Function End Class End Namespace
-1
dotnet/roslyn
56,310
Move semantic classification caching down to Editor layer
CyrusNajmabadi
"2021-09-09T23:15:16Z"
"2021-09-10T19:26:25Z"
6e123012d868c56aba8acabfe1ccad1bf8f20b04
7af13b6e3867198cd59c566a905b332888ea1dec
Move semantic classification caching down to Editor layer.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/CastExpressionSyntaxExtensions.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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module CastExpressionSyntaxExtensions <Extension> Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function <Extension> Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax Dim resultNode = innerNode.WithTriviaFrom(castNode) resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode) Return resultNode 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 System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module CastExpressionSyntaxExtensions <Extension> Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function <Extension> Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax Dim resultNode = innerNode.WithTriviaFrom(castNode) resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode) Return resultNode End Function End Module End Namespace
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/FlowAnalysis/LocalDataFlowPass.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; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Does a data flow analysis for state attached to local variables and fields of struct locals. /// </summary> internal abstract partial class LocalDataFlowPass<TLocalState, TLocalFunctionState> : AbstractFlowPass<TLocalState, TLocalFunctionState> where TLocalState : LocalDataFlowPass<TLocalState, TLocalFunctionState>.ILocalDataFlowState where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState { internal interface ILocalDataFlowState : ILocalState { /// <summary> /// True if new variables introduced in <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}" /> should be set /// to the bottom state. False if they should be set to the top state. /// </summary> bool NormalizeToBottom { get; } } /// <summary> /// A cache for remember which structs are empty. /// </summary> protected readonly EmptyStructTypeCache _emptyStructTypeCache; protected LocalDataFlowPass( CSharpCompilation compilation, Symbol? member, BoundNode node, EmptyStructTypeCache emptyStructs, bool trackUnassignments) : base(compilation, member, node, nonMonotonicTransferFunction: trackUnassignments) { Debug.Assert(emptyStructs != null); _emptyStructTypeCache = emptyStructs; } protected LocalDataFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, EmptyStructTypeCache emptyStructs, BoundNode firstInRegion, BoundNode lastInRegion, bool trackRegions, bool trackUnassignments) : base(compilation, member, node, firstInRegion, lastInRegion, trackRegions: trackRegions, nonMonotonicTransferFunction: trackUnassignments) { _emptyStructTypeCache = emptyStructs; } protected abstract bool TryGetVariable(VariableIdentifier identifier, out int slot); protected abstract int AddVariable(VariableIdentifier identifier); /// <summary> /// Locals are given slots when their declarations are encountered. We only need give slots /// to local variables, out parameters, and the "this" variable of a struct constructs. /// Other variables are not given slots, and are therefore not tracked by the analysis. This /// returns -1 for a variable that is not tracked, for fields of structs that have the same /// assigned status as the container, and for structs that (recursively) contain no data members. /// We do not need to track references to /// variables that occur before the variable is declared, as those are reported in an /// earlier phase as "use before declaration". That allows us to avoid giving slots to local /// variables before processing their declarations. /// </summary> protected int VariableSlot(Symbol symbol, int containingSlot = 0) { containingSlot = DescendThroughTupleRestFields(ref symbol, containingSlot, forceContainingSlotsToExist: false); int slot; return TryGetVariable(new VariableIdentifier(symbol, containingSlot), out slot) ? slot : -1; } protected virtual bool IsEmptyStructType(TypeSymbol type) { return _emptyStructTypeCache.IsEmptyStructType(type); } /// <summary> /// Force a variable to have a slot. Returns -1 if the variable has an empty struct type. /// </summary> protected virtual int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { Debug.Assert(containingSlot >= 0); Debug.Assert(symbol != null); if (symbol.Kind == SymbolKind.RangeVariable) return -1; containingSlot = DescendThroughTupleRestFields(ref symbol, containingSlot, forceContainingSlotsToExist: true); if (containingSlot < 0) { // Error case. Diagnostics should already have been produced. return -1; } VariableIdentifier identifier = new VariableIdentifier(symbol, containingSlot); int slot; // Since analysis may proceed in multiple passes, it is possible the slot is already assigned. if (!TryGetVariable(identifier, out slot)) { if (!createIfMissing) { return -1; } var variableType = symbol.GetTypeOrReturnType().Type; if (!forceSlotEvenIfEmpty && IsEmptyStructType(variableType)) { return -1; } slot = AddVariable(identifier); } if (IsConditionalState) { Normalize(ref this.StateWhenTrue); Normalize(ref this.StateWhenFalse); } else { Normalize(ref this.State); } return slot; } /// <summary> /// Sets the starting state for any newly declared variables in the LocalDataFlowPass. /// </summary> protected abstract void Normalize(ref TLocalState state); /// <summary> /// Descends through Rest fields of a tuple if "symbol" is an extended field /// As a result the "symbol" will be adjusted to be the field of the innermost tuple /// and a corresponding containingSlot is returned. /// Return value -1 indicates a failure which could happen for the following reasons /// a) Rest field does not exist, which could happen in rare error scenarios involving broken ValueTuple types /// b) Rest is not tracked already and forceSlotsToExist is false (otherwise we create slots on demand) /// </summary> private int DescendThroughTupleRestFields(ref Symbol symbol, int containingSlot, bool forceContainingSlotsToExist) { if (symbol is TupleElementFieldSymbol fieldSymbol) { TypeSymbol containingType = symbol.ContainingType; // for tuple fields the variable identifier represents the underlying field symbol = fieldSymbol.TupleUnderlyingField; // descend through Rest fields // force corresponding slots if do not exist while (!TypeSymbol.Equals(containingType, symbol.ContainingType, TypeCompareKind.ConsiderEverything)) { var restField = containingType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() as FieldSymbol; if (restField is null) { return -1; } if (forceContainingSlotsToExist) { containingSlot = GetOrCreateSlot(restField, containingSlot); } else { if (!TryGetVariable(new VariableIdentifier(restField, containingSlot), out containingSlot)) { return -1; } } containingType = restField.Type; } } return containingSlot; } protected abstract bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member); /// <summary> /// Return the slot for a variable, or -1 if it is not tracked (because, for example, it is an empty struct). /// </summary> /// <param name="node"></param> /// <returns></returns> protected virtual int MakeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: return (object)MethodThisParameter != null ? GetOrCreateSlot(MethodThisParameter) : -1; case BoundKind.Local: return GetOrCreateSlot(((BoundLocal)node).LocalSymbol); case BoundKind.Parameter: return GetOrCreateSlot(((BoundParameter)node).ParameterSymbol); case BoundKind.RangeVariable: return MakeSlot(((BoundRangeVariable)node).Value); case BoundKind.FieldAccess: case BoundKind.EventAccess: case BoundKind.PropertyAccess: if (TryGetReceiverAndMember(node, out BoundExpression? receiver, out Symbol? member)) { Debug.Assert((receiver is null) != member.RequiresInstanceReceiver()); return MakeMemberSlot(receiver, member); } break; case BoundKind.AssignmentOperator: return MakeSlot(((BoundAssignmentOperator)node).Left); } return -1; } protected int MakeMemberSlot(BoundExpression? receiverOpt, Symbol member) { int containingSlot; if (member.RequiresInstanceReceiver()) { if (receiverOpt is null) { return -1; } containingSlot = MakeSlot(receiverOpt); if (containingSlot < 0) { return -1; } } else { containingSlot = 0; } return GetOrCreateSlot(member, containingSlot); } protected static bool HasInitializer(Symbol field) => field switch { SourceMemberFieldSymbol f => f.HasInitializer, SynthesizedBackingFieldSymbol f => f.HasInitializer, SourceFieldLikeEventSymbol e => e.AssociatedEventField?.HasInitializer == true, _ => 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Does a data flow analysis for state attached to local variables and fields of struct locals. /// </summary> internal abstract partial class LocalDataFlowPass<TLocalState, TLocalFunctionState> : AbstractFlowPass<TLocalState, TLocalFunctionState> where TLocalState : LocalDataFlowPass<TLocalState, TLocalFunctionState>.ILocalDataFlowState where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState { internal interface ILocalDataFlowState : ILocalState { /// <summary> /// True if new variables introduced in <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}" /> should be set /// to the bottom state. False if they should be set to the top state. /// </summary> bool NormalizeToBottom { get; } } /// <summary> /// A cache for remember which structs are empty. /// </summary> protected readonly EmptyStructTypeCache _emptyStructTypeCache; protected LocalDataFlowPass( CSharpCompilation compilation, Symbol? member, BoundNode node, EmptyStructTypeCache emptyStructs, bool trackUnassignments) : base(compilation, member, node, nonMonotonicTransferFunction: trackUnassignments) { Debug.Assert(emptyStructs != null); _emptyStructTypeCache = emptyStructs; } protected LocalDataFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, EmptyStructTypeCache emptyStructs, BoundNode firstInRegion, BoundNode lastInRegion, bool trackRegions, bool trackUnassignments) : base(compilation, member, node, firstInRegion, lastInRegion, trackRegions: trackRegions, nonMonotonicTransferFunction: trackUnassignments) { _emptyStructTypeCache = emptyStructs; } protected abstract bool TryGetVariable(VariableIdentifier identifier, out int slot); protected abstract int AddVariable(VariableIdentifier identifier); /// <summary> /// Locals are given slots when their declarations are encountered. We only need give slots /// to local variables, out parameters, and the "this" variable of a struct constructs. /// Other variables are not given slots, and are therefore not tracked by the analysis. This /// returns -1 for a variable that is not tracked, for fields of structs that have the same /// assigned status as the container, and for structs that (recursively) contain no data members. /// We do not need to track references to /// variables that occur before the variable is declared, as those are reported in an /// earlier phase as "use before declaration". That allows us to avoid giving slots to local /// variables before processing their declarations. /// </summary> protected int VariableSlot(Symbol symbol, int containingSlot = 0) { containingSlot = DescendThroughTupleRestFields(ref symbol, containingSlot, forceContainingSlotsToExist: false); int slot; return TryGetVariable(new VariableIdentifier(symbol, containingSlot), out slot) ? slot : -1; } protected virtual bool IsEmptyStructType(TypeSymbol type) { return _emptyStructTypeCache.IsEmptyStructType(type); } /// <summary> /// Force a variable to have a slot. Returns -1 if the variable has an empty struct type. /// </summary> protected virtual int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { Debug.Assert(containingSlot >= 0); Debug.Assert(symbol != null); if (symbol.Kind == SymbolKind.RangeVariable) return -1; containingSlot = DescendThroughTupleRestFields(ref symbol, containingSlot, forceContainingSlotsToExist: true); if (containingSlot < 0) { // Error case. Diagnostics should already have been produced. return -1; } VariableIdentifier identifier = new VariableIdentifier(symbol, containingSlot); int slot; // Since analysis may proceed in multiple passes, it is possible the slot is already assigned. if (!TryGetVariable(identifier, out slot)) { if (!createIfMissing) { return -1; } var variableType = symbol.GetTypeOrReturnType().Type; if (!forceSlotEvenIfEmpty && IsEmptyStructType(variableType)) { return -1; } slot = AddVariable(identifier); } if (IsConditionalState) { Normalize(ref this.StateWhenTrue); Normalize(ref this.StateWhenFalse); } else { Normalize(ref this.State); } return slot; } /// <summary> /// Sets the starting state for any newly declared variables in the LocalDataFlowPass. /// </summary> protected abstract void Normalize(ref TLocalState state); /// <summary> /// Descends through Rest fields of a tuple if "symbol" is an extended field /// As a result the "symbol" will be adjusted to be the field of the innermost tuple /// and a corresponding containingSlot is returned. /// Return value -1 indicates a failure which could happen for the following reasons /// a) Rest field does not exist, which could happen in rare error scenarios involving broken ValueTuple types /// b) Rest is not tracked already and forceSlotsToExist is false (otherwise we create slots on demand) /// </summary> private int DescendThroughTupleRestFields(ref Symbol symbol, int containingSlot, bool forceContainingSlotsToExist) { if (symbol is TupleElementFieldSymbol fieldSymbol) { TypeSymbol containingType = symbol.ContainingType; // for tuple fields the variable identifier represents the underlying field symbol = fieldSymbol.TupleUnderlyingField; // descend through Rest fields // force corresponding slots if do not exist while (!TypeSymbol.Equals(containingType, symbol.ContainingType, TypeCompareKind.ConsiderEverything)) { var restField = containingType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault(s => s is not TupleVirtualElementFieldSymbol) as FieldSymbol; if (restField is null) { return -1; } if (forceContainingSlotsToExist) { containingSlot = GetOrCreateSlot(restField, containingSlot); } else { if (!TryGetVariable(new VariableIdentifier(restField, containingSlot), out containingSlot)) { return -1; } } containingType = restField.Type; } } return containingSlot; } protected abstract bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member); /// <summary> /// Return the slot for a variable, or -1 if it is not tracked (because, for example, it is an empty struct). /// </summary> /// <param name="node"></param> /// <returns></returns> protected virtual int MakeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: return (object)MethodThisParameter != null ? GetOrCreateSlot(MethodThisParameter) : -1; case BoundKind.Local: return GetOrCreateSlot(((BoundLocal)node).LocalSymbol); case BoundKind.Parameter: return GetOrCreateSlot(((BoundParameter)node).ParameterSymbol); case BoundKind.RangeVariable: return MakeSlot(((BoundRangeVariable)node).Value); case BoundKind.FieldAccess: case BoundKind.EventAccess: case BoundKind.PropertyAccess: if (TryGetReceiverAndMember(node, out BoundExpression? receiver, out Symbol? member)) { Debug.Assert((receiver is null) != member.RequiresInstanceReceiver()); return MakeMemberSlot(receiver, member); } break; case BoundKind.AssignmentOperator: return MakeSlot(((BoundAssignmentOperator)node).Left); } return -1; } protected int MakeMemberSlot(BoundExpression? receiverOpt, Symbol member) { int containingSlot; if (member.RequiresInstanceReceiver()) { if (receiverOpt is null) { return -1; } containingSlot = MakeSlot(receiverOpt); if (containingSlot < 0) { return -1; } } else { containingSlot = 0; } return GetOrCreateSlot(member, containingSlot); } protected static bool HasInitializer(Symbol field) => field switch { SourceMemberFieldSymbol f => f.HasInitializer, SynthesizedBackingFieldSymbol f => f.HasInitializer, SourceFieldLikeEventSymbol e => e.AssociatedEventField?.HasInitializer == true, _ => false }; } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// An ErrorSymbol is used when the compiler cannot determine a symbol object to return because /// of an error. For example, if a field is declared "Goo x;", and the type "Goo" cannot be /// found, an ErrorSymbol is returned when asking the field "x" what it's type is. /// </summary> internal abstract partial class ErrorTypeSymbol : NamedTypeSymbol { internal static readonly ErrorTypeSymbol UnknownResultType = new UnsupportedMetadataTypeSymbol(); private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; /// <summary> /// The underlying error. /// </summary> internal abstract DiagnosticInfo? ErrorInfo { get; } /// <summary> /// Summary of the reason why the type is bad. /// </summary> internal virtual LookupResultKind ResultKind { get { return LookupResultKind.Empty; } } /// <summary> /// Called by <see cref="AbstractTypeMap.SubstituteType(TypeSymbol)"/> to perform substitution /// on types with TypeKind ErrorType. The general pattern is to use the type map /// to perform substitution on the wrapped type, if any, and then construct a new /// error type symbol from the result (if there was a change). /// </summary> internal TypeWithAnnotations Substitute(AbstractTypeMap typeMap) { return TypeWithAnnotations.Create(typeMap.SubstituteNamedType(this)); } /// <summary> /// When constructing this ErrorTypeSymbol, there may have been symbols that seemed to /// be what the user intended, but were unsuitable. For example, a type might have been /// inaccessible, or ambiguous. This property returns the possible symbols that the user /// might have intended. It will return no symbols if no possible symbols were found. /// See the CandidateReason property to understand why the symbols were unsuitable. /// </summary> public virtual ImmutableArray<Symbol> CandidateSymbols { get { return ImmutableArray<Symbol>.Empty; } } ///<summary> /// If CandidateSymbols returns one or more symbols, returns the reason that those /// symbols were not chosen. Otherwise, returns None. /// </summary> public CandidateReason CandidateReason { get { if (!CandidateSymbols.IsEmpty) { Debug.Assert(ResultKind != LookupResultKind.Viable, "Shouldn't have viable result kind on error symbol"); return ResultKind.ToCandidateReason(); } else { return CandidateReason.None; } } } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return new UseSiteInfo<AssemblySymbol>(this.ErrorInfo); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public override bool IsReferenceType { // TODO: Consider returning False. get { return true; } } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public sealed override bool IsValueType { get { return false; } } public sealed override bool IsRefLikeType { get { return false; } } public sealed override bool IsReadOnly { get { return false; } } /// <summary> /// Collection of names of members declared within this type. /// </summary> public override IEnumerable<string> MemberNames { get { return SpecializedCollections.EmptyEnumerable<string>(); } } /// <summary> /// Get all the members of this symbol. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns Null.</returns> public override ImmutableArray<Symbol> GetMembers() { if (IsTupleType) { var result = AddOrWrapTupleMembers(ImmutableArray<Symbol>.Empty); RoslynDebug.Assert(result is object); return result.ToImmutableAndFree(); } return ImmutableArray<Symbol>.Empty; } /// <summary> /// Get all the members of this symbol that have a particular name. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are /// no members with this name, returns an empty ImmutableArray. Never returns Null.</returns> public override ImmutableArray<Symbol> GetMembers(string name) { return GetMembers().WhereAsArray((m, name) => m.Name == name, name); } internal sealed override IEnumerable<FieldSymbol> GetFieldsToEmit() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return this.GetMembersUnordered(); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { return this.GetMembers(name); } /// <summary> /// Get all the members of this symbol that are types. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// Get all the members of this symbol that are types that have a particular name, of any arity. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. /// If this symbol has no type members with this name, /// returns an empty ImmutableArray. Never returns null.</returns> public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// Get all the members of this symbol that are types that have a particular name and arity /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity. /// If this symbol has no type members with this name and arity, /// returns an empty ImmutableArray. Never returns null.</returns> public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.ErrorType; } } /// <summary> /// Gets the kind of this type. /// </summary> public sealed override TypeKind TypeKind { get { return TypeKind.Error; } } internal sealed override bool IsInterface { get { return false; } } /// <summary> /// Get the symbol that logically contains this symbol. /// </summary> public override Symbol? ContainingSymbol { get { return null; } } /// <summary> /// Gets the locations where this symbol was originally defined, either in source or /// metadata. Some symbols (for example, partial classes) may be defined in more than one /// location. /// </summary> public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> public override int Arity { get { return 0; } } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public override string Name { get { return string.Empty; } } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a give type parameters, /// then the type parameter itself is consider the type argument. /// </summary> internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { if (_lazyTypeParameters.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, GetTypeParameters(), default(ImmutableArray<TypeParameterSymbol>)); } return _lazyTypeParameters; } } private ImmutableArray<TypeParameterSymbol> GetTypeParameters() { int arity = this.Arity; if (arity == 0) { return ImmutableArray<TypeParameterSymbol>.Empty; } else { var @params = new TypeParameterSymbol[arity]; for (int i = 0; i < arity; i++) { @params[i] = new ErrorTypeParameterSymbol(this, string.Empty, i); } return @params.AsImmutableOrNull(); } } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> public override NamedTypeSymbol ConstructedFrom { get { return this; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitErrorType(this, argument); } // Only the compiler should create error symbols. internal ErrorTypeSymbol(TupleExtraData? tupleData = null) : base(tupleData) { } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public sealed override bool IsStatic { get { return false; } } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the "abstract" modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for /// types that do not allow a derived class (declared with "sealed" or "static" or "struct" /// or "enum" or "delegate"). /// </summary> public sealed override bool IsSealed { get { return false; } } internal sealed override bool HasSpecialName { get { return false; } } public sealed override bool MightContainExtensionMethods { get { return false; } } internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal override bool IsInterpolatedStringHandlerType => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol? GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) { return null; } internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) { return ImmutableArray<NamedTypeSymbol>.Empty; } protected override NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { return new ConstructedErrorTypeSymbol(this, typeArguments); } internal override NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol?.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedNestedErrorTypeSymbol(newOwner, this); } internal sealed override bool ShouldAddWinRTMembers { get { return false; } } internal sealed override bool IsWindowsRuntimeImport { get { return false; } } internal sealed override TypeLayout Layout { get { return default(TypeLayout); } } internal override CharSet MarshallingCharSet { get { return DefaultMarshallingCharSet; } } public sealed override bool IsSerializable { get { return false; } } internal sealed override bool HasDeclarativeSecurity { get { return false; } } internal sealed override bool IsComImport { get { return false; } } internal sealed override ObsoleteAttributeData? ObsoleteAttributeData { get { return null; } } internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override AttributeUsageInfo GetAttributeUsageInfo() { return AttributeUsageInfo.Null; } internal virtual bool Unreported { get { return false; } } public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } internal override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal override NamedTypeSymbol? NativeIntegerUnderlyingType => null; protected sealed override ISymbol CreateISymbol() { return new PublicModel.ErrorTypeSymbol(this, DefaultNullableAnnotation); } protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.ErrorTypeSymbol(this, nullableAnnotation); } internal sealed override bool IsRecord => false; internal override bool IsRecordStruct => false; internal sealed override bool HasPossibleWellKnownCloneMethod() => false; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } internal abstract class SubstitutedErrorTypeSymbol : ErrorTypeSymbol { private readonly ErrorTypeSymbol _originalDefinition; private int _hashCode; protected SubstitutedErrorTypeSymbol(ErrorTypeSymbol originalDefinition, TupleExtraData? tupleData = null) : base(tupleData) { _originalDefinition = originalDefinition; } public override NamedTypeSymbol OriginalDefinition { get { return _originalDefinition; } } internal override bool MangleName { get { return _originalDefinition.MangleName; } } internal override DiagnosticInfo? ErrorInfo { get { return _originalDefinition.ErrorInfo; } } public override int Arity { get { return _originalDefinition.Arity; } } public override string Name { get { return _originalDefinition.Name; } } public override ImmutableArray<Location> Locations { get { return _originalDefinition.Locations; } } public override ImmutableArray<Symbol> CandidateSymbols { get { return _originalDefinition.CandidateSymbols; } } internal override LookupResultKind ResultKind { get { return _originalDefinition.ResultKind; } } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return _originalDefinition.GetUseSiteInfo(); } public override int GetHashCode() { if (_hashCode == 0) { _hashCode = this.ComputeHashCode(); } return _hashCode; } } internal sealed class ConstructedErrorTypeSymbol : SubstitutedErrorTypeSymbol { private readonly ErrorTypeSymbol _constructedFrom; private readonly ImmutableArray<TypeWithAnnotations> _typeArgumentsWithAnnotations; private readonly TypeMap _map; public ConstructedErrorTypeSymbol(ErrorTypeSymbol constructedFrom, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, TupleExtraData? tupleData = null) : base((ErrorTypeSymbol)constructedFrom.OriginalDefinition, tupleData) { _constructedFrom = constructedFrom; _typeArgumentsWithAnnotations = typeArgumentsWithAnnotations; _map = new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new ConstructedErrorTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, tupleData: newData); } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _constructedFrom.TypeParameters; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return _typeArgumentsWithAnnotations; } } public override NamedTypeSymbol ConstructedFrom { get { return _constructedFrom; } } public override Symbol? ContainingSymbol { get { return _constructedFrom.ContainingSymbol; } } internal override TypeMap TypeSubstitution { get { return _map; } } } internal sealed class SubstitutedNestedErrorTypeSymbol : SubstitutedErrorTypeSymbol { private readonly NamedTypeSymbol _containingSymbol; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly TypeMap _map; public SubstitutedNestedErrorTypeSymbol(NamedTypeSymbol containingSymbol, ErrorTypeSymbol originalDefinition) : base(originalDefinition) { _containingSymbol = containingSymbol; _map = containingSymbol.TypeSubstitution.WithAlphaRename(originalDefinition, this, out _typeParameters); } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } public override NamedTypeSymbol ConstructedFrom { get { return this; } } public override Symbol ContainingSymbol { get { return _containingSymbol; } } internal override TypeMap TypeSubstitution { get { return _map; } } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; } }
// 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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// An ErrorSymbol is used when the compiler cannot determine a symbol object to return because /// of an error. For example, if a field is declared "Goo x;", and the type "Goo" cannot be /// found, an ErrorSymbol is returned when asking the field "x" what it's type is. /// </summary> internal abstract partial class ErrorTypeSymbol : NamedTypeSymbol { internal static readonly ErrorTypeSymbol UnknownResultType = new UnsupportedMetadataTypeSymbol(); private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; /// <summary> /// The underlying error. /// </summary> internal abstract DiagnosticInfo? ErrorInfo { get; } /// <summary> /// Summary of the reason why the type is bad. /// </summary> internal virtual LookupResultKind ResultKind { get { return LookupResultKind.Empty; } } /// <summary> /// Called by <see cref="AbstractTypeMap.SubstituteType(TypeSymbol)"/> to perform substitution /// on types with TypeKind ErrorType. The general pattern is to use the type map /// to perform substitution on the wrapped type, if any, and then construct a new /// error type symbol from the result (if there was a change). /// </summary> internal TypeWithAnnotations Substitute(AbstractTypeMap typeMap) { return TypeWithAnnotations.Create(typeMap.SubstituteNamedType(this)); } /// <summary> /// When constructing this ErrorTypeSymbol, there may have been symbols that seemed to /// be what the user intended, but were unsuitable. For example, a type might have been /// inaccessible, or ambiguous. This property returns the possible symbols that the user /// might have intended. It will return no symbols if no possible symbols were found. /// See the CandidateReason property to understand why the symbols were unsuitable. /// </summary> public virtual ImmutableArray<Symbol> CandidateSymbols { get { return ImmutableArray<Symbol>.Empty; } } ///<summary> /// If CandidateSymbols returns one or more symbols, returns the reason that those /// symbols were not chosen. Otherwise, returns None. /// </summary> public CandidateReason CandidateReason { get { if (!CandidateSymbols.IsEmpty) { Debug.Assert(ResultKind != LookupResultKind.Viable, "Shouldn't have viable result kind on error symbol"); return ResultKind.ToCandidateReason(); } else { return CandidateReason.None; } } } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return new UseSiteInfo<AssemblySymbol>(this.ErrorInfo); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public override bool IsReferenceType { // TODO: Consider returning False. get { return true; } } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public sealed override bool IsValueType { get { return false; } } public sealed override bool IsRefLikeType { get { return false; } } public sealed override bool IsReadOnly { get { return false; } } /// <summary> /// Collection of names of members declared within this type. /// </summary> public override IEnumerable<string> MemberNames { get { return SpecializedCollections.EmptyEnumerable<string>(); } } /// <summary> /// Get all the members of this symbol. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, /// returns an empty ImmutableArray. Never returns Null.</returns> public override ImmutableArray<Symbol> GetMembers() { if (IsTupleType) { var result = MakeSynthesizedTupleMembers(ImmutableArray<Symbol>.Empty); RoslynDebug.Assert(result is object); return result.ToImmutableAndFree(); } return ImmutableArray<Symbol>.Empty; } /// <summary> /// Get all the members of this symbol that have a particular name. /// </summary> /// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are /// no members with this name, returns an empty ImmutableArray. Never returns Null.</returns> public override ImmutableArray<Symbol> GetMembers(string name) { return GetMembers().WhereAsArray((m, name) => m.Name == name, name); } internal sealed override IEnumerable<FieldSymbol> GetFieldsToEmit() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return this.GetMembersUnordered(); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { return this.GetMembers(name); } /// <summary> /// Get all the members of this symbol that are types. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, /// returns an empty ImmutableArray. Never returns null.</returns> public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// Get all the members of this symbol that are types that have a particular name, of any arity. /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. /// If this symbol has no type members with this name, /// returns an empty ImmutableArray. Never returns null.</returns> public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// Get all the members of this symbol that are types that have a particular name and arity /// </summary> /// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity. /// If this symbol has no type members with this name and arity, /// returns an empty ImmutableArray. Never returns null.</returns> public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return ImmutableArray<NamedTypeSymbol>.Empty; } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.ErrorType; } } /// <summary> /// Gets the kind of this type. /// </summary> public sealed override TypeKind TypeKind { get { return TypeKind.Error; } } internal sealed override bool IsInterface { get { return false; } } /// <summary> /// Get the symbol that logically contains this symbol. /// </summary> public override Symbol? ContainingSymbol { get { return null; } } /// <summary> /// Gets the locations where this symbol was originally defined, either in source or /// metadata. Some symbols (for example, partial classes) may be defined in more than one /// location. /// </summary> public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> public override int Arity { get { return 0; } } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public override string Name { get { return string.Empty; } } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a give type parameters, /// then the type parameter itself is consider the type argument. /// </summary> internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { if (_lazyTypeParameters.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, GetTypeParameters(), default(ImmutableArray<TypeParameterSymbol>)); } return _lazyTypeParameters; } } private ImmutableArray<TypeParameterSymbol> GetTypeParameters() { int arity = this.Arity; if (arity == 0) { return ImmutableArray<TypeParameterSymbol>.Empty; } else { var @params = new TypeParameterSymbol[arity]; for (int i = 0; i < arity; i++) { @params[i] = new ErrorTypeParameterSymbol(this, string.Empty, i); } return @params.AsImmutableOrNull(); } } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> public override NamedTypeSymbol ConstructedFrom { get { return this; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitErrorType(this, argument); } // Only the compiler should create error symbols. internal ErrorTypeSymbol(TupleExtraData? tupleData = null) : base(tupleData) { } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public sealed override bool IsStatic { get { return false; } } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the "abstract" modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for /// types that do not allow a derived class (declared with "sealed" or "static" or "struct" /// or "enum" or "delegate"). /// </summary> public sealed override bool IsSealed { get { return false; } } internal sealed override bool HasSpecialName { get { return false; } } public sealed override bool MightContainExtensionMethods { get { return false; } } internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal override bool IsInterpolatedStringHandlerType => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol? GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) { return null; } internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) { return ImmutableArray<NamedTypeSymbol>.Empty; } protected override NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { return new ConstructedErrorTypeSymbol(this, typeArguments); } internal override NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol?.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedNestedErrorTypeSymbol(newOwner, this); } internal sealed override bool ShouldAddWinRTMembers { get { return false; } } internal sealed override bool IsWindowsRuntimeImport { get { return false; } } internal sealed override TypeLayout Layout { get { return default(TypeLayout); } } internal override CharSet MarshallingCharSet { get { return DefaultMarshallingCharSet; } } public sealed override bool IsSerializable { get { return false; } } internal sealed override bool HasDeclarativeSecurity { get { return false; } } internal sealed override bool IsComImport { get { return false; } } internal sealed override ObsoleteAttributeData? ObsoleteAttributeData { get { return null; } } internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override AttributeUsageInfo GetAttributeUsageInfo() { return AttributeUsageInfo.Null; } internal virtual bool Unreported { get { return false; } } public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } internal override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal override NamedTypeSymbol? NativeIntegerUnderlyingType => null; protected sealed override ISymbol CreateISymbol() { return new PublicModel.ErrorTypeSymbol(this, DefaultNullableAnnotation); } protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.ErrorTypeSymbol(this, nullableAnnotation); } internal sealed override bool IsRecord => false; internal override bool IsRecordStruct => false; internal sealed override bool HasPossibleWellKnownCloneMethod() => false; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } internal abstract class SubstitutedErrorTypeSymbol : ErrorTypeSymbol { private readonly ErrorTypeSymbol _originalDefinition; private int _hashCode; protected SubstitutedErrorTypeSymbol(ErrorTypeSymbol originalDefinition, TupleExtraData? tupleData = null) : base(tupleData) { _originalDefinition = originalDefinition; } public override NamedTypeSymbol OriginalDefinition { get { return _originalDefinition; } } internal override bool MangleName { get { return _originalDefinition.MangleName; } } internal override DiagnosticInfo? ErrorInfo { get { return _originalDefinition.ErrorInfo; } } public override int Arity { get { return _originalDefinition.Arity; } } public override string Name { get { return _originalDefinition.Name; } } public override ImmutableArray<Location> Locations { get { return _originalDefinition.Locations; } } public override ImmutableArray<Symbol> CandidateSymbols { get { return _originalDefinition.CandidateSymbols; } } internal override LookupResultKind ResultKind { get { return _originalDefinition.ResultKind; } } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return _originalDefinition.GetUseSiteInfo(); } public override int GetHashCode() { if (_hashCode == 0) { _hashCode = this.ComputeHashCode(); } return _hashCode; } } internal sealed class ConstructedErrorTypeSymbol : SubstitutedErrorTypeSymbol { private readonly ErrorTypeSymbol _constructedFrom; private readonly ImmutableArray<TypeWithAnnotations> _typeArgumentsWithAnnotations; private readonly TypeMap _map; public ConstructedErrorTypeSymbol(ErrorTypeSymbol constructedFrom, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, TupleExtraData? tupleData = null) : base((ErrorTypeSymbol)constructedFrom.OriginalDefinition, tupleData) { _constructedFrom = constructedFrom; _typeArgumentsWithAnnotations = typeArgumentsWithAnnotations; _map = new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new ConstructedErrorTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, tupleData: newData); } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _constructedFrom.TypeParameters; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return _typeArgumentsWithAnnotations; } } public override NamedTypeSymbol ConstructedFrom { get { return _constructedFrom; } } public override Symbol? ContainingSymbol { get { return _constructedFrom.ContainingSymbol; } } internal override TypeMap TypeSubstitution { get { return _map; } } } internal sealed class SubstitutedNestedErrorTypeSymbol : SubstitutedErrorTypeSymbol { private readonly NamedTypeSymbol _containingSymbol; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly TypeMap _map; public SubstitutedNestedErrorTypeSymbol(NamedTypeSymbol containingSymbol, ErrorTypeSymbol originalDefinition) : base(originalDefinition) { _containingSymbol = containingSymbol; _map = containingSymbol.TypeSubstitution.WithAlphaRename(originalDefinition, this, out _typeParameters); } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } public override NamedTypeSymbol ConstructedFrom { get { return this; } } public override Symbol ContainingSymbol { get { return _containingSymbol; } } internal override TypeMap TypeSubstitution { get { return _map; } } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamedTypeSymbol.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.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The class to represent all types imported from a PE/module. /// </summary> internal abstract class PENamedTypeSymbol : NamedTypeSymbol { private static readonly Dictionary<string, ImmutableArray<PENamedTypeSymbol>> s_emptyNestedTypes = new Dictionary<string, ImmutableArray<PENamedTypeSymbol>>(EmptyComparer.Instance); private readonly NamespaceOrTypeSymbol _container; private readonly TypeDefinitionHandle _handle; private readonly string _name; private readonly TypeAttributes _flags; private readonly SpecialType _corTypeId; /// <summary> /// A set of all the names of the members in this type. /// We can get names without getting members (which is a more expensive operation) /// </summary> private ICollection<string> _lazyMemberNames; /// <summary> /// We used to sort symbols on demand and relied on row ids to figure out the order between symbols of the same kind. /// However, that was fragile because, when map tables are used in metadata, row ids in the map table define the order /// and we don't have them. /// Members are grouped by kind. First we store fields, then methods, then properties, then events and finally nested types. /// Within groups, members are sorted based on declaration order. /// </summary> private ImmutableArray<Symbol> _lazyMembersInDeclarationOrder; /// <summary> /// A map of members immediately contained within this type /// grouped by their name (case-sensitively). /// </summary> private Dictionary<string, ImmutableArray<Symbol>> _lazyMembersByName; /// <summary> /// A map of types immediately contained within this type /// grouped by their name (case-sensitively). /// </summary> private Dictionary<string, ImmutableArray<PENamedTypeSymbol>> _lazyNestedTypes; /// <summary> /// Lazily initialized by TypeKind property. /// </summary> private TypeKind _lazyKind; private NullableContextKind _lazyNullableContextValue; private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType; private ImmutableArray<NamedTypeSymbol> _lazyInterfaces = default(ImmutableArray<NamedTypeSymbol>); private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType; private ImmutableArray<NamedTypeSymbol> _lazyDeclaredInterfaces = default(ImmutableArray<NamedTypeSymbol>); private Tuple<CultureInfo, string> _lazyDocComment; private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized; // There is a bunch of type properties relevant only for enums or types with custom attributes. // It is fairly easy to check whether a type s is not "uncommon". So we store uncommon properties in // a separate class with a noUncommonProperties singleton used for cases when type is "common". // this is done purely to save memory with expectation that "uncommon" cases are indeed uncommon. #region "Uncommon properties" private static readonly UncommonProperties s_noUncommonProperties = new UncommonProperties(); private UncommonProperties _lazyUncommonProperties; private UncommonProperties GetUncommonProperties() { var result = _lazyUncommonProperties; if (result != null) { #if DEBUG Debug.Assert(result != s_noUncommonProperties || result.IsDefaultValue(), "default value was modified"); #endif return result; } if (this.IsUncommon()) { result = new UncommonProperties(); return Interlocked.CompareExchange(ref _lazyUncommonProperties, result, null) ?? result; } _lazyUncommonProperties = result = s_noUncommonProperties; return result; } // enums and types with custom attributes are considered uncommon private bool IsUncommon() { if (this.ContainingPEModule.HasAnyCustomAttributes(_handle)) { return true; } if (this.TypeKind == TypeKind.Enum) { return true; } return false; } private class UncommonProperties { /// <summary> /// Need to import them for an enum from a linked assembly, when we are embedding it. These symbols are not included into lazyMembersInDeclarationOrder. /// </summary> internal ImmutableArray<PEFieldSymbol> lazyInstanceEnumFields; internal NamedTypeSymbol lazyEnumUnderlyingType; // CONSIDER: Should we use a CustomAttributeBag for PE symbols? internal ImmutableArray<CSharpAttributeData> lazyCustomAttributes; internal ImmutableArray<string> lazyConditionalAttributeSymbols; internal ObsoleteAttributeData lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; internal AttributeUsageInfo lazyAttributeUsageInfo = AttributeUsageInfo.Null; internal ThreeState lazyContainsExtensionMethods; internal ThreeState lazyIsByRefLike; internal ThreeState lazyIsReadOnly; internal string lazyDefaultMemberName; internal NamedTypeSymbol lazyComImportCoClassType = ErrorTypeSymbol.UnknownResultType; internal ThreeState lazyHasEmbeddedAttribute = ThreeState.Unknown; internal ThreeState lazyHasInterpolatedStringHandlerAttribute = ThreeState.Unknown; #if DEBUG internal bool IsDefaultValue() { return lazyInstanceEnumFields.IsDefault && (object)lazyEnumUnderlyingType == null && lazyCustomAttributes.IsDefault && lazyConditionalAttributeSymbols.IsDefault && lazyObsoleteAttributeData == ObsoleteAttributeData.Uninitialized && lazyAttributeUsageInfo.IsNull && !lazyContainsExtensionMethods.HasValue() && lazyDefaultMemberName == null && (object)lazyComImportCoClassType == (object)ErrorTypeSymbol.UnknownResultType && !lazyHasEmbeddedAttribute.HasValue() && !lazyHasInterpolatedStringHandlerAttribute.HasValue(); } #endif } #endregion // Uncommon properties internal static PENamedTypeSymbol Create( PEModuleSymbol moduleSymbol, PENamespaceSymbol containingNamespace, TypeDefinitionHandle handle, string emittedNamespaceName) { GenericParameterHandleCollection genericParameterHandles; ushort arity; BadImageFormatException mrEx = null; GetGenericInfo(moduleSymbol, handle, out genericParameterHandles, out arity, out mrEx); bool mangleName; PENamedTypeSymbol result; if (arity == 0) { result = new PENamedTypeSymbolNonGeneric(moduleSymbol, containingNamespace, handle, emittedNamespaceName, out mangleName); } else { result = new PENamedTypeSymbolGeneric( moduleSymbol, containingNamespace, handle, emittedNamespaceName, genericParameterHandles, arity, out mangleName); } if (mrEx != null) { result._lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, result)); } return result; } private static void GetGenericInfo(PEModuleSymbol moduleSymbol, TypeDefinitionHandle handle, out GenericParameterHandleCollection genericParameterHandles, out ushort arity, out BadImageFormatException mrEx) { try { genericParameterHandles = moduleSymbol.Module.GetTypeDefGenericParamsOrThrow(handle); arity = (ushort)genericParameterHandles.Count; mrEx = null; } catch (BadImageFormatException e) { arity = 0; genericParameterHandles = default(GenericParameterHandleCollection); mrEx = e; } } internal static PENamedTypeSymbol Create( PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, TypeDefinitionHandle handle) { GenericParameterHandleCollection genericParameterHandles; ushort metadataArity; BadImageFormatException mrEx = null; GetGenericInfo(moduleSymbol, handle, out genericParameterHandles, out metadataArity, out mrEx); ushort arity = 0; var containerMetadataArity = containingType.MetadataArity; if (metadataArity > containerMetadataArity) { arity = (ushort)(metadataArity - containerMetadataArity); } bool mangleName; PENamedTypeSymbol result; if (metadataArity == 0) { result = new PENamedTypeSymbolNonGeneric(moduleSymbol, containingType, handle, null, out mangleName); } else { result = new PENamedTypeSymbolGeneric( moduleSymbol, containingType, handle, null, genericParameterHandles, arity, out mangleName); } if (mrEx != null || metadataArity < containerMetadataArity) { result._lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, result)); } return result; } private PENamedTypeSymbol( PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, ushort arity, out bool mangleName) { Debug.Assert(!handle.IsNil); Debug.Assert((object)container != null); Debug.Assert(arity == 0 || this is PENamedTypeSymbolGeneric); string metadataName; bool makeBad = false; try { metadataName = moduleSymbol.Module.GetTypeDefNameOrThrow(handle); } catch (BadImageFormatException) { metadataName = string.Empty; makeBad = true; } _handle = handle; _container = container; try { _flags = moduleSymbol.Module.GetTypeDefFlagsOrThrow(handle); } catch (BadImageFormatException) { makeBad = true; } if (arity == 0) { _name = metadataName; mangleName = false; } else { // Unmangle name for a generic type. _name = MetadataHelpers.UnmangleMetadataNameForArity(metadataName, arity); Debug.Assert(ReferenceEquals(_name, metadataName) == (_name == metadataName)); mangleName = !ReferenceEquals(_name, metadataName); } // check if this is one of the COR library types if (emittedNamespaceName != null && moduleSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes && this.DeclaredAccessibility == Accessibility.Public) // NB: this.flags was set above. { _corTypeId = SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(emittedNamespaceName, metadataName)); } else { _corTypeId = SpecialType.None; } if (makeBad) { _lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this)); } } public override SpecialType SpecialType { get { return _corTypeId; } } internal PEModuleSymbol ContainingPEModule { get { Symbol s = _container; while (s.Kind != SymbolKind.Namespace) { s = s.ContainingSymbol; } return ((PENamespaceSymbol)s).ContainingPEModule; } } internal override ModuleSymbol ContainingModule { get { return ContainingPEModule; } } public abstract override int Arity { get; } internal abstract override bool MangleName { get; } internal abstract int MetadataArity { get; } internal TypeDefinitionHandle Handle { get { return _handle; } } internal sealed override bool IsInterpolatedStringHandlerType { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyHasInterpolatedStringHandlerAttribute.HasValue()) { uncommon.lazyHasInterpolatedStringHandlerAttribute = ContainingPEModule.Module.HasInterpolatedStringHandlerAttribute(_handle).ToThreeState(); } return uncommon.lazyHasInterpolatedStringHandlerAttribute.Value(); } } internal override bool HasCodeAnalysisEmbeddedAttribute { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyHasEmbeddedAttribute.HasValue()) { uncommon.lazyHasEmbeddedAttribute = ContainingPEModule.Module.HasCodeAnalysisEmbeddedAttribute(_handle).ToThreeState(); } return uncommon.lazyHasEmbeddedAttribute.Value(); } } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get { if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType)) { Interlocked.CompareExchange(ref _lazyBaseType, MakeAcyclicBaseType(), ErrorTypeSymbol.UnknownResultType); } return _lazyBaseType; } } internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null) { if (_lazyInterfaces.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, MakeAcyclicInterfaces(), default(ImmutableArray<NamedTypeSymbol>)); } return _lazyInterfaces; } internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { return InterfacesNoUseSiteDiagnostics(); } internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) { return GetDeclaredBaseType(skipTransformsIfNecessary: false); } private NamedTypeSymbol GetDeclaredBaseType(bool skipTransformsIfNecessary) { if (ReferenceEquals(_lazyDeclaredBaseType, ErrorTypeSymbol.UnknownResultType)) { var baseType = MakeDeclaredBaseType(); if (baseType is object) { if (skipTransformsIfNecessary) { // If the transforms are not necessary, return early without updating the // base type field. This avoids cycles decoding nullability in particular. return baseType; } var moduleSymbol = ContainingPEModule; TypeSymbol decodedType = DynamicTypeDecoder.TransformType(baseType, 0, _handle, moduleSymbol); decodedType = NativeIntegerTypeDecoder.TransformType(decodedType, _handle, moduleSymbol); decodedType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(decodedType, _handle, moduleSymbol); baseType = (NamedTypeSymbol)NullableTypeDecoder.TransformType(TypeWithAnnotations.Create(decodedType), _handle, moduleSymbol, accessSymbol: this, nullableContext: this).Type; } Interlocked.CompareExchange(ref _lazyDeclaredBaseType, baseType, ErrorTypeSymbol.UnknownResultType); } return _lazyDeclaredBaseType; } internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) { if (_lazyDeclaredInterfaces.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, MakeDeclaredInterfaces(), default(ImmutableArray<NamedTypeSymbol>)); } return _lazyDeclaredInterfaces; } private NamedTypeSymbol MakeDeclaredBaseType() { if (!_flags.IsInterface()) { try { var moduleSymbol = ContainingPEModule; EntityHandle token = moduleSymbol.Module.GetBaseTypeOfTypeOrThrow(_handle); if (!token.IsNil) { return (NamedTypeSymbol)new MetadataDecoder(moduleSymbol, this).GetTypeOfToken(token); } } catch (BadImageFormatException mrEx) { return new UnsupportedMetadataTypeSymbol(mrEx); } } return null; } private ImmutableArray<NamedTypeSymbol> MakeDeclaredInterfaces() { try { var moduleSymbol = ContainingPEModule; var interfaceImpls = moduleSymbol.Module.GetInterfaceImplementationsOrThrow(_handle); if (interfaceImpls.Count > 0) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(interfaceImpls.Count); var tokenDecoder = new MetadataDecoder(moduleSymbol, this); foreach (var interfaceImpl in interfaceImpls) { EntityHandle interfaceHandle = moduleSymbol.Module.MetadataReader.GetInterfaceImplementation(interfaceImpl).Interface; TypeSymbol typeSymbol = tokenDecoder.GetTypeOfToken(interfaceHandle); typeSymbol = NativeIntegerTypeDecoder.TransformType(typeSymbol, interfaceImpl, moduleSymbol); typeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeSymbol, interfaceImpl, moduleSymbol); typeSymbol = NullableTypeDecoder.TransformType(TypeWithAnnotations.Create(typeSymbol), interfaceImpl, moduleSymbol, accessSymbol: this, nullableContext: this).Type; var namedTypeSymbol = typeSymbol as NamedTypeSymbol ?? new UnsupportedMetadataTypeSymbol(); // interface list contains a bad type symbols.Add(namedTypeSymbol); } return symbols.ToImmutableAndFree(); } return ImmutableArray<NamedTypeSymbol>.Empty; } catch (BadImageFormatException mrEx) { return ImmutableArray.Create<NamedTypeSymbol>(new UnsupportedMetadataTypeSymbol(mrEx)); } } public override NamedTypeSymbol ConstructedFrom { get { return this; } } public override Symbol ContainingSymbol { get { return _container; } } public override NamedTypeSymbol ContainingType { get { return _container as NamedTypeSymbol; } } internal override bool IsRecord { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return SynthesizedRecordClone.FindValidCloneMethod(this, ref discardedUseSiteInfo) != null; } } // Record structs get erased when emitted to metadata internal override bool IsRecordStruct => false; public override Accessibility DeclaredAccessibility { get { Accessibility access = Accessibility.Private; switch (_flags & TypeAttributes.VisibilityMask) { case TypeAttributes.NestedAssembly: access = Accessibility.Internal; break; case TypeAttributes.NestedFamORAssem: access = Accessibility.ProtectedOrInternal; break; case TypeAttributes.NestedFamANDAssem: access = Accessibility.ProtectedAndInternal; break; case TypeAttributes.NestedPrivate: access = Accessibility.Private; break; case TypeAttributes.Public: case TypeAttributes.NestedPublic: access = Accessibility.Public; break; case TypeAttributes.NestedFamily: access = Accessibility.Protected; break; case TypeAttributes.NotPublic: access = Accessibility.Internal; break; default: throw ExceptionUtilities.UnexpectedValue(_flags & TypeAttributes.VisibilityMask); } return access; } } public override NamedTypeSymbol EnumUnderlyingType { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return null; } this.EnsureEnumUnderlyingTypeIsLoaded(uncommon); return uncommon.lazyEnumUnderlyingType; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ImmutableArray<CSharpAttributeData>.Empty; } if (uncommon.lazyCustomAttributes.IsDefault) { var loadedCustomAttributes = ContainingPEModule.GetCustomAttributesForToken( Handle, out _, // Filter out [Extension] MightContainExtensionMethods ? AttributeDescription.CaseSensitiveExtensionAttribute : default, out _, // Filter out [Obsolete], unless it was user defined (IsRefLikeType && ObsoleteAttributeData is null) ? AttributeDescription.ObsoleteAttribute : default, out _, // Filter out [IsReadOnly] IsReadOnly ? AttributeDescription.IsReadOnlyAttribute : default, out _, // Filter out [IsByRefLike] IsRefLikeType ? AttributeDescription.IsByRefLikeAttribute : default); ImmutableInterlocked.InterlockedInitialize(ref uncommon.lazyCustomAttributes, loadedCustomAttributes); } return uncommon.lazyCustomAttributes; } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return GetAttributes(); } internal override byte? GetNullableContextValue() { byte? value; if (!_lazyNullableContextValue.TryGetByte(out value)) { value = ContainingPEModule.Module.HasNullableContextAttribute(_handle, out byte arg) ? arg : _container.GetNullableContextValue(); _lazyNullableContextValue = value.ToNullableContextFlags(); } return value; } internal override byte? GetLocalNullableContextValue() { throw ExceptionUtilities.Unreachable; } public override IEnumerable<string> MemberNames { get { EnsureNonTypeMemberNamesAreLoaded(); return _lazyMemberNames; } } private void EnsureNonTypeMemberNamesAreLoaded() { if (_lazyMemberNames == null) { var moduleSymbol = ContainingPEModule; var module = moduleSymbol.Module; var names = new HashSet<string>(); try { foreach (var methodDef in module.GetMethodsOfTypeOrThrow(_handle)) { try { names.Add(module.GetMethodDefNameOrThrow(methodDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } try { foreach (var propertyDef in module.GetPropertiesOfTypeOrThrow(_handle)) { try { names.Add(module.GetPropertyDefNameOrThrow(propertyDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } try { foreach (var eventDef in module.GetEventsOfTypeOrThrow(_handle)) { try { names.Add(module.GetEventDefNameOrThrow(eventDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { try { names.Add(module.GetFieldDefNameOrThrow(fieldDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } // From C#'s perspective, structs always have a public constructor // (even if it's not in metadata). Add it unconditionally and let // the hash set de-dup. if (this.IsValueType) { names.Add(WellKnownMemberNames.InstanceConstructorName); } Interlocked.CompareExchange(ref _lazyMemberNames, CreateReadOnlyMemberNames(names), null); } } private static ICollection<string> CreateReadOnlyMemberNames(HashSet<string> names) { switch (names.Count) { case 0: return SpecializedCollections.EmptySet<string>(); case 1: return SpecializedCollections.SingletonCollection(names.First()); case 2: case 3: case 4: case 5: case 6: // PERF: Small collections can be implemented as ImmutableArray. // While lookup is O(n), when n is small, the memory savings are more valuable. // Size 6 was chosen because that represented 50% of the names generated in the Picasso end to end. // This causes boxing, but that's still superior to a wrapped HashSet return ImmutableArray.CreateRange(names); default: return SpecializedCollections.ReadOnlySet(names); } } public override ImmutableArray<Symbol> GetMembers() { EnsureAllMembersAreLoaded(); return _lazyMembersInDeclarationOrder; } private IEnumerable<FieldSymbol> GetEnumFieldsToEmit() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { yield break; } var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; // Non-static fields of enum types are not imported by default because they are not bindable, // but we need them for NoPia. var fieldDefs = ArrayBuilder<FieldDefinitionHandle>.GetInstance(); try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { fieldDefs.Add(fieldDef); } } catch (BadImageFormatException) { } if (uncommon.lazyInstanceEnumFields.IsDefault) { var builder = ArrayBuilder<PEFieldSymbol>.GetInstance(); foreach (var fieldDef in fieldDefs) { try { FieldAttributes fieldFlags = module.GetFieldDefFlagsOrThrow(fieldDef); if ((fieldFlags & FieldAttributes.Static) == 0 && ModuleExtensions.ShouldImportField(fieldFlags, moduleSymbol.ImportOptions)) { builder.Add(new PEFieldSymbol(moduleSymbol, this, fieldDef)); } } catch (BadImageFormatException) { } } ImmutableInterlocked.InterlockedInitialize(ref uncommon.lazyInstanceEnumFields, builder.ToImmutableAndFree()); } int staticIndex = 0; ImmutableArray<Symbol> staticFields = GetMembers(); int instanceIndex = 0; foreach (var fieldDef in fieldDefs) { if (instanceIndex < uncommon.lazyInstanceEnumFields.Length && uncommon.lazyInstanceEnumFields[instanceIndex].Handle == fieldDef) { yield return uncommon.lazyInstanceEnumFields[instanceIndex]; instanceIndex++; continue; } if (staticIndex < staticFields.Length && staticFields[staticIndex].Kind == SymbolKind.Field) { var field = (PEFieldSymbol)staticFields[staticIndex]; if (field.Handle == fieldDef) { yield return field; staticIndex++; continue; } } } fieldDefs.Free(); Debug.Assert(instanceIndex == uncommon.lazyInstanceEnumFields.Length); Debug.Assert(staticIndex == staticFields.Length || staticFields[staticIndex].Kind != SymbolKind.Field); } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { return GetEnumFieldsToEmit(); } else { // If there are any non-event fields, they are at the very beginning. IEnumerable<FieldSymbol> nonEventFields = GetMembers<FieldSymbol>(this.GetMembers().WhereAsArray(m => !(m is TupleErrorFieldSymbol)), SymbolKind.Field, offset: 0); // Event backing fields are not part of the set returned by GetMembers. Let's add them manually. ArrayBuilder<FieldSymbol> eventFields = null; foreach (var eventSymbol in GetEventsToEmit()) { FieldSymbol associatedField = eventSymbol.AssociatedField; if ((object)associatedField != null) { Debug.Assert((object)associatedField.AssociatedSymbol != null); Debug.Assert(!nonEventFields.Contains(associatedField)); if (eventFields == null) { eventFields = ArrayBuilder<FieldSymbol>.GetInstance(); } eventFields.Add(associatedField); } } if (eventFields == null) { // Simple case return nonEventFields; } // We need to merge non-event fields with event fields while preserving their relative declaration order var handleToFieldMap = new SmallDictionary<FieldDefinitionHandle, FieldSymbol>(); int count = 0; foreach (PEFieldSymbol field in nonEventFields) { handleToFieldMap.Add(field.Handle, field); count++; } foreach (PEFieldSymbol field in eventFields) { handleToFieldMap.Add(field.Handle, field); } count += eventFields.Count; eventFields.Free(); var result = ArrayBuilder<FieldSymbol>.GetInstance(count); try { foreach (var handle in this.ContainingPEModule.Module.GetFieldsOfTypeOrThrow(_handle)) { FieldSymbol field; if (handleToFieldMap.TryGetValue(handle, out field)) { result.Add(field); } } } catch (BadImageFormatException) { } Debug.Assert(result.Count == count); return result.ToImmutableAndFree(); } } internal override IEnumerable<MethodSymbol> GetMethodsToEmit() { ImmutableArray<Symbol> members = GetMembers(); // Get to methods. int index = GetIndexOfFirstMember(members, SymbolKind.Method); if (!this.IsInterfaceType()) { for (; index < members.Length; index++) { if (members[index].Kind != SymbolKind.Method) { break; } var method = (MethodSymbol)members[index]; // Don't emit the default value type constructor - the runtime handles that. // For parameterless struct constructors from metadata, IsDefaultValueTypeConstructor() // ignores requireZeroInit and simply checks if the method is implicitly declared. if (!method.IsDefaultValueTypeConstructor(requireZeroInit: false)) { yield return method; } } } else { // We do not create symbols for v-table gap methods, let's figure out where the gaps go. if (index >= members.Length || members[index].Kind != SymbolKind.Method) { // We didn't import any methods, it is Ok to return an empty set. yield break; } var method = (PEMethodSymbol)members[index]; var module = this.ContainingPEModule.Module; var methodDefs = ArrayBuilder<MethodDefinitionHandle>.GetInstance(); try { foreach (var methodDef in module.GetMethodsOfTypeOrThrow(_handle)) { methodDefs.Add(methodDef); } } catch (BadImageFormatException) { } foreach (var methodDef in methodDefs) { if (method.Handle == methodDef) { yield return method; index++; if (index == members.Length || members[index].Kind != SymbolKind.Method) { // no need to return any gaps at the end. methodDefs.Free(); yield break; } method = (PEMethodSymbol)members[index]; } else { // Encountered a gap. int gapSize; try { gapSize = ModuleExtensions.GetVTableGapSize(module.GetMethodDefNameOrThrow(methodDef)); } catch (BadImageFormatException) { gapSize = 1; } // We don't have a symbol to return, so, even if the name doesn't represent a gap, we still have a gap. do { yield return null; gapSize--; } while (gapSize > 0); } } // Ensure we explicitly returned from inside loop. throw ExceptionUtilities.Unreachable; } } internal override IEnumerable<PropertySymbol> GetPropertiesToEmit() { return GetMembers<PropertySymbol>(this.GetMembers(), SymbolKind.Property); } internal override IEnumerable<EventSymbol> GetEventsToEmit() { return GetMembers<EventSymbol>(this.GetMembers(), SymbolKind.Event); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return this.GetMembersUnordered(); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { return this.GetMembers(name); } private class DeclarationOrderTypeSymbolComparer : IComparer<Symbol> { public static readonly DeclarationOrderTypeSymbolComparer Instance = new DeclarationOrderTypeSymbolComparer(); private DeclarationOrderTypeSymbolComparer() { } public int Compare(Symbol x, Symbol y) { return HandleComparer.Default.Compare(((PENamedTypeSymbol)x).Handle, ((PENamedTypeSymbol)y).Handle); } } private void EnsureEnumUnderlyingTypeIsLoaded(UncommonProperties uncommon) { if ((object)(uncommon.lazyEnumUnderlyingType) == null && this.TypeKind == TypeKind.Enum) { // From §8.5.2 // An enum is considerably more restricted than a true type, as // follows: // - It shall have exactly one instance field, and the type of that field defines the underlying type of // the enumeration. // - It shall not have any static fields unless they are literal. (see §8.6.1.2) // The underlying type shall be a built-in integer type. Enums shall derive from System.Enum, hence they are // value types. Like all value types, they shall be sealed (see §8.9.9). var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; var decoder = new MetadataDecoder(moduleSymbol, this); NamedTypeSymbol underlyingType = null; try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { FieldAttributes fieldFlags; try { fieldFlags = module.GetFieldDefFlagsOrThrow(fieldDef); } catch (BadImageFormatException) { continue; } if ((fieldFlags & FieldAttributes.Static) == 0) { // Instance field used to determine underlying type. ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers; TypeSymbol type = decoder.DecodeFieldSignature(fieldDef, out customModifiers); if (type.SpecialType.IsValidEnumUnderlyingType() && !customModifiers.AnyRequired()) { if ((object)underlyingType == null) { underlyingType = (NamedTypeSymbol)type; } else { underlyingType = new UnsupportedMetadataTypeSymbol(); // ambiguous underlying type } } } } if ((object)underlyingType == null) { underlyingType = new UnsupportedMetadataTypeSymbol(); // undefined underlying type } } catch (BadImageFormatException mrEx) { if ((object)underlyingType == null) { underlyingType = new UnsupportedMetadataTypeSymbol(mrEx); } } Interlocked.CompareExchange(ref uncommon.lazyEnumUnderlyingType, underlyingType, null); } } private void EnsureAllMembersAreLoaded() { if (_lazyMembersByName == null) { LoadMembers(); } } private void LoadMembers() { ArrayBuilder<Symbol> members = null; if (_lazyMembersInDeclarationOrder.IsDefault) { EnsureNestedTypesAreLoaded(); members = ArrayBuilder<Symbol>.GetInstance(); Debug.Assert(SymbolKind.Field.ToSortOrder() < SymbolKind.Method.ToSortOrder()); Debug.Assert(SymbolKind.Method.ToSortOrder() < SymbolKind.Property.ToSortOrder()); Debug.Assert(SymbolKind.Property.ToSortOrder() < SymbolKind.Event.ToSortOrder()); Debug.Assert(SymbolKind.Event.ToSortOrder() < SymbolKind.NamedType.ToSortOrder()); if (this.TypeKind == TypeKind.Enum) { EnsureEnumUnderlyingTypeIsLoaded(this.GetUncommonProperties()); var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { FieldAttributes fieldFlags; try { fieldFlags = module.GetFieldDefFlagsOrThrow(fieldDef); if ((fieldFlags & FieldAttributes.Static) == 0) { continue; } } catch (BadImageFormatException) { fieldFlags = 0; } if (ModuleExtensions.ShouldImportField(fieldFlags, moduleSymbol.ImportOptions)) { var field = new PEFieldSymbol(moduleSymbol, this, fieldDef); members.Add(field); } } } catch (BadImageFormatException) { } var syntheticCtor = new SynthesizedInstanceConstructor(this); members.Add(syntheticCtor); } else { ArrayBuilder<PEFieldSymbol> fieldMembers = ArrayBuilder<PEFieldSymbol>.GetInstance(); ArrayBuilder<Symbol> nonFieldMembers = ArrayBuilder<Symbol>.GetInstance(); MultiDictionary<string, PEFieldSymbol> privateFieldNameToSymbols = this.CreateFields(fieldMembers); // A method may be referenced as an accessor by one or more properties. And, // any of those properties may be "bogus" if one of the property accessors // does not match the property signature. If the method is referenced by at // least one non-bogus property, then the method is created as an accessor, // and (for purposes of error reporting if the method is referenced directly) the // associated property is set (arbitrarily) to the first non-bogus property found // in metadata. If the method is not referenced by any non-bogus properties, // then the method is created as a normal method rather than an accessor. // Create a dictionary of method symbols indexed by metadata handle // (to allow efficient lookup when matching property accessors). PooledDictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol = this.CreateMethods(nonFieldMembers); if (this.TypeKind == TypeKind.Struct) { bool haveParameterlessConstructor = false; foreach (MethodSymbol method in nonFieldMembers) { if (method.IsParameterlessConstructor()) { haveParameterlessConstructor = true; break; } } // Structs have an implicit parameterless constructor, even if it // does not appear in metadata (11.3.8) if (!haveParameterlessConstructor) { nonFieldMembers.Insert(0, new SynthesizedInstanceConstructor(this)); } } this.CreateProperties(methodHandleToSymbol, nonFieldMembers); this.CreateEvents(privateFieldNameToSymbols, methodHandleToSymbol, nonFieldMembers); foreach (PEFieldSymbol field in fieldMembers) { if ((object)field.AssociatedSymbol == null) { members.Add(field); } else { // As for source symbols, our public API presents the fiction that all // operations are performed on the event, rather than on the backing field. // The backing field is not accessible through the API. As an additional // bonus, lookup is easier when the names don't collide. Debug.Assert(field.AssociatedSymbol.Kind == SymbolKind.Event); } } members.AddRange(nonFieldMembers); nonFieldMembers.Free(); fieldMembers.Free(); methodHandleToSymbol.Free(); } // Now add types to the end. int membersCount = members.Count; foreach (var typeArray in _lazyNestedTypes.Values) { members.AddRange(typeArray); } // Sort the types based on row id. members.Sort(membersCount, DeclarationOrderTypeSymbolComparer.Instance); #if DEBUG Symbol previous = null; foreach (var s in members) { if (previous == null) { previous = s; } else { Symbol current = s; Debug.Assert(previous.Kind.ToSortOrder() <= current.Kind.ToSortOrder()); previous = current; } } #endif if (IsTupleType) { int originalCount = members.Count; members = AddOrWrapTupleMembers(members.ToImmutableAndFree()); membersCount += (members.Count - originalCount); // account for added tuple error fields Debug.Assert(members is object); } var membersInDeclarationOrder = members.ToImmutable(); if (!ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersInDeclarationOrder, membersInDeclarationOrder)) { members.Free(); members = null; } else { // remove the types members.Clip(membersCount); } } if (_lazyMembersByName == null) { if (members == null) { members = ArrayBuilder<Symbol>.GetInstance(); foreach (var member in _lazyMembersInDeclarationOrder) { if (member.Kind == SymbolKind.NamedType) { break; } members.Add(member); } } Dictionary<string, ImmutableArray<Symbol>> membersDict = GroupByName(members); var exchangeResult = Interlocked.CompareExchange(ref _lazyMembersByName, membersDict, null); if (exchangeResult == null) { // we successfully swapped in the members dictionary. // Now, use these as the canonical member names. This saves us memory by not having // two collections around at the same time with redundant data in them. // // NOTE(cyrusn): We must use an interlocked exchange here so that the full // construction of this object will be seen from 'MemberNames'. Also, doing a // straight InterlockedExchange here is the right thing to do. Consider the case // where one thread is calling in through "MemberNames" while we are in the middle // of this method. Either that thread will compute the member names and store it // first (in which case we overwrite it), or we will store first (in which case // their CompareExchange(..., ..., null) will fail. Either way, this will be certain // to become the canonical set of member names. // // NOTE(cyrusn): This means that it is possible (and by design) for people to get a // different object back when they call MemberNames multiple times. However, outside // of object identity, both collections should appear identical to the user. var memberNames = SpecializedCollections.ReadOnlyCollection(membersDict.Keys); Interlocked.Exchange(ref _lazyMemberNames, memberNames); } } if (members != null) { members.Free(); } } internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { EnsureAllMembersAreLoaded(); ImmutableArray<Symbol> m; if (!_lazyMembersByName.TryGetValue(name, out m)) { m = ImmutableArray<Symbol>.Empty; } return m; } public override ImmutableArray<Symbol> GetMembers(string name) { EnsureAllMembersAreLoaded(); ImmutableArray<Symbol> m; if (!_lazyMembersByName.TryGetValue(name, out m)) { m = ImmutableArray<Symbol>.Empty; } // nested types are not common, but we need to check just in case ImmutableArray<PENamedTypeSymbol> t; if (_lazyNestedTypes.TryGetValue(name, out t)) { m = m.Concat(StaticCast<Symbol>.From(t)); } return m; } internal sealed override bool HasPossibleWellKnownCloneMethod() => MemberNames.Contains(WellKnownMemberNames.CloneMethodName); internal override FieldSymbol FixedElementField { get { FieldSymbol result = null; var candidates = this.GetMembers(FixedFieldImplementationType.FixedElementFieldName); if (!candidates.IsDefault && candidates.Length == 1) { result = candidates[0] as FieldSymbol; } return result; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembers().ConditionallyDeOrder(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { EnsureNestedTypesAreLoaded(); return GetMemberTypesPrivate(); } private ImmutableArray<NamedTypeSymbol> GetMemberTypesPrivate() { var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); foreach (var typeArray in _lazyNestedTypes.Values) { builder.AddRange(typeArray); } return builder.ToImmutableAndFree(); } private void EnsureNestedTypesAreLoaded() { if (_lazyNestedTypes == null) { var types = ArrayBuilder<PENamedTypeSymbol>.GetInstance(); types.AddRange(this.CreateNestedTypes()); var typesDict = GroupByName(types); var exchangeResult = Interlocked.CompareExchange(ref _lazyNestedTypes, typesDict, null); if (exchangeResult == null) { // Build cache of TypeDef Tokens // Potentially this can be done in the background. var moduleSymbol = this.ContainingPEModule; moduleSymbol.OnNewTypeDeclarationsLoaded(typesDict); } types.Free(); } } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { EnsureNestedTypesAreLoaded(); ImmutableArray<PENamedTypeSymbol> t; if (_lazyNestedTypes.TryGetValue(name, out t)) { return StaticCast<NamedTypeSymbol>.From(t); } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((type, arity) => type.Arity == arity, arity); } public override ImmutableArray<Location> Locations { get { return ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override string Name { get { return _name; } } internal override bool HasSpecialName { get { return (_flags & TypeAttributes.SpecialName) != 0; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override bool IsStatic { get { return (_flags & TypeAttributes.Sealed) != 0 && (_flags & TypeAttributes.Abstract) != 0; } } public override bool IsAbstract { get { return (_flags & TypeAttributes.Abstract) != 0 && (_flags & TypeAttributes.Sealed) == 0; } } internal override bool IsMetadataAbstract { get { return (_flags & TypeAttributes.Abstract) != 0; } } public override bool IsSealed { get { return (_flags & TypeAttributes.Sealed) != 0 && (_flags & TypeAttributes.Abstract) == 0; } } internal override bool IsMetadataSealed { get { return (_flags & TypeAttributes.Sealed) != 0; } } internal TypeAttributes Flags { get { return _flags; } } public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } public override bool MightContainExtensionMethods { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyContainsExtensionMethods.HasValue()) { var contains = ThreeState.False; // Dev11 supports extension methods defined on non-static // classes, structs, delegates, and generic types. switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Delegate: var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; bool moduleHasExtension = module.HasExtensionAttribute(_handle, ignoreCase: false); var containingAssembly = this.ContainingAssembly as PEAssemblySymbol; if ((object)containingAssembly != null) { contains = (moduleHasExtension && containingAssembly.MightContainExtensionMethods).ToThreeState(); } else { contains = moduleHasExtension.ToThreeState(); } break; } uncommon.lazyContainsExtensionMethods = contains; } return uncommon.lazyContainsExtensionMethods.Value(); } } public override TypeKind TypeKind { get { TypeKind result = _lazyKind; if (result == TypeKind.Unknown) { if (_flags.IsInterface()) { result = TypeKind.Interface; } else { TypeSymbol @base = GetDeclaredBaseType(skipTransformsIfNecessary: true); result = TypeKind.Class; if ((object)@base != null) { SpecialType baseCorTypeId = @base.SpecialType; switch (baseCorTypeId) { case SpecialType.System_Enum: // Enum result = TypeKind.Enum; break; case SpecialType.System_MulticastDelegate: // Delegate result = TypeKind.Delegate; break; case SpecialType.System_ValueType: // System.Enum is the only class that derives from ValueType if (this.SpecialType != SpecialType.System_Enum) { // Struct result = TypeKind.Struct; } break; } } } _lazyKind = result; } return result; } } internal sealed override bool IsInterface { get { return _flags.IsInterface(); } } private static ExtendedErrorTypeSymbol CyclicInheritanceError(PENamedTypeSymbol type, TypeSymbol declaredBase) { var info = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase, type); return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, info, true); } private NamedTypeSymbol MakeAcyclicBaseType() { NamedTypeSymbol declaredBase = GetDeclaredBaseType(null); // implicit base is not interesting for metadata cycle detection if ((object)declaredBase == null) { return null; } if (BaseTypeAnalysis.TypeDependsOn(declaredBase, this)) { return CyclicInheritanceError(this, declaredBase); } this.SetKnownToHaveNoDeclaredBaseCycles(); return declaredBase; } private ImmutableArray<NamedTypeSymbol> MakeAcyclicInterfaces() { var declaredInterfaces = GetDeclaredInterfaces(null); if (!IsInterface) { // only interfaces needs to check for inheritance cycles via interfaces. return declaredInterfaces; } return declaredInterfaces .SelectAsArray(t => BaseTypeAnalysis.TypeDependsOn(t, this) ? CyclicInheritanceError(this, t) : t); } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return PEDocumentationCommentUtils.GetDocumentationComment(this, ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); } private IEnumerable<PENamedTypeSymbol> CreateNestedTypes() { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; ImmutableArray<TypeDefinitionHandle> nestedTypeDefs; try { nestedTypeDefs = module.GetNestedTypeDefsOrThrow(_handle); } catch (BadImageFormatException) { yield break; } foreach (var typeRid in nestedTypeDefs) { if (module.ShouldImportNestedType(typeRid)) { yield return PENamedTypeSymbol.Create(moduleSymbol, this, typeRid); } } } private MultiDictionary<string, PEFieldSymbol> CreateFields(ArrayBuilder<PEFieldSymbol> fieldMembers) { var privateFieldNameToSymbols = new MultiDictionary<string, PEFieldSymbol>(); var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; // for ordinary struct types we import private fields so that we can distinguish empty structs from non-empty structs var isOrdinaryStruct = false; // for ordinary embeddable struct types we import private members so that we can report appropriate errors if the structure is used var isOrdinaryEmbeddableStruct = false; if (this.TypeKind == TypeKind.Struct) { if (this.SpecialType == Microsoft.CodeAnalysis.SpecialType.None) { isOrdinaryStruct = true; isOrdinaryEmbeddableStruct = this.ContainingAssembly.IsLinked; } else { isOrdinaryStruct = (this.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Nullable_T); } } try { foreach (var fieldRid in module.GetFieldsOfTypeOrThrow(_handle)) { try { if (!(isOrdinaryEmbeddableStruct || (isOrdinaryStruct && (module.GetFieldDefFlagsOrThrow(fieldRid) & FieldAttributes.Static) == 0) || module.ShouldImportField(fieldRid, moduleSymbol.ImportOptions))) { continue; } } catch (BadImageFormatException) { } var symbol = new PEFieldSymbol(moduleSymbol, this, fieldRid); fieldMembers.Add(symbol); // Only private fields are potentially backing fields for field-like events. if (symbol.DeclaredAccessibility == Accessibility.Private) { var name = symbol.Name; if (name.Length > 0) { privateFieldNameToSymbols.Add(name, symbol); } } } } catch (BadImageFormatException) { } return privateFieldNameToSymbols; } private PooledDictionary<MethodDefinitionHandle, PEMethodSymbol> CreateMethods(ArrayBuilder<Symbol> members) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; var map = PooledDictionary<MethodDefinitionHandle, PEMethodSymbol>.GetInstance(); // for ordinary embeddable struct types we import private members so that we can report appropriate errors if the structure is used var isOrdinaryEmbeddableStruct = (this.TypeKind == TypeKind.Struct) && (this.SpecialType == Microsoft.CodeAnalysis.SpecialType.None) && this.ContainingAssembly.IsLinked; try { foreach (var methodHandle in module.GetMethodsOfTypeOrThrow(_handle)) { if (isOrdinaryEmbeddableStruct || module.ShouldImportMethod(_handle, methodHandle, moduleSymbol.ImportOptions)) { var method = new PEMethodSymbol(moduleSymbol, this, methodHandle); members.Add(method); map.Add(methodHandle, method); } } } catch (BadImageFormatException) { } return map; } private void CreateProperties(Dictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol, ArrayBuilder<Symbol> members) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; try { foreach (var propertyDef in module.GetPropertiesOfTypeOrThrow(_handle)) { try { var methods = module.GetPropertyMethodsOrThrow(propertyDef); PEMethodSymbol getMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Getter); PEMethodSymbol setMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Setter); if (((object)getMethod != null) || ((object)setMethod != null)) { members.Add(PEPropertySymbol.Create(moduleSymbol, this, propertyDef, getMethod, setMethod)); } } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } } private void CreateEvents( MultiDictionary<string, PEFieldSymbol> privateFieldNameToSymbols, Dictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol, ArrayBuilder<Symbol> members) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; try { foreach (var eventRid in module.GetEventsOfTypeOrThrow(_handle)) { try { var methods = module.GetEventMethodsOrThrow(eventRid); // NOTE: C# ignores all other accessors (most notably, raise/fire). PEMethodSymbol addMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Adder); PEMethodSymbol removeMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Remover); // NOTE: both accessors are required, but that will be reported separately. // Create the symbol unless both accessors are missing. if (((object)addMethod != null) || ((object)removeMethod != null)) { members.Add(new PEEventSymbol(moduleSymbol, this, eventRid, addMethod, removeMethod, privateFieldNameToSymbols)); } } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } } private PEMethodSymbol GetAccessorMethod(PEModule module, Dictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol, TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef) { if (methodDef.IsNil) { return null; } PEMethodSymbol method; bool found = methodHandleToSymbol.TryGetValue(methodDef, out method); Debug.Assert(found || !module.ShouldImportMethod(typeDef, methodDef, this.ContainingPEModule.ImportOptions)); return method; } private static Dictionary<string, ImmutableArray<Symbol>> GroupByName(ArrayBuilder<Symbol> symbols) { return symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); } private static Dictionary<string, ImmutableArray<PENamedTypeSymbol>> GroupByName(ArrayBuilder<PENamedTypeSymbol> symbols) { if (symbols.Count == 0) { return s_emptyNestedTypes; } return symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (!_lazyCachedUseSiteInfo.IsInitialized) { AssemblySymbol primaryDependency = PrimaryDependency; _lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo<AssemblySymbol>(primaryDependency).AdjustDiagnosticInfo(GetUseSiteDiagnosticImpl())); } return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency); } protected virtual DiagnosticInfo GetUseSiteDiagnosticImpl() { DiagnosticInfo diagnostic = null; if (!MergeUseSiteDiagnostics(ref diagnostic, CalculateUseSiteDiagnostic())) { // Check if this type is marked by RequiredAttribute attribute. // If so mark the type as bad, because it relies upon semantics that are not understood by the C# compiler. if (this.ContainingPEModule.Module.HasRequiredAttributeAttribute(_handle)) { diagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this); } else if (TypeKind == TypeKind.Class && SpecialType != SpecialType.System_Enum) { TypeSymbol @base = GetDeclaredBaseType(null); if (@base?.SpecialType == SpecialType.None && @base.ContainingAssembly?.IsMissing == true) { var missingType = @base as MissingMetadataTypeSymbol.TopLevel; if ((object)missingType != null && missingType.Arity == 0) { string emittedName = MetadataHelpers.BuildQualifiedName(missingType.NamespaceName, missingType.MetadataName); switch (SpecialTypes.GetTypeFromMetadataName(emittedName)) { case SpecialType.System_Enum: case SpecialType.System_MulticastDelegate: case SpecialType.System_ValueType: // This might be a structure, an enum, or a delegate diagnostic = missingType.GetUseSiteInfo().DiagnosticInfo; break; } } } } } return diagnostic; } internal string DefaultMemberName { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ""; } if (uncommon.lazyDefaultMemberName == null) { string defaultMemberName; this.ContainingPEModule.Module.HasDefaultMemberAttribute(_handle, out defaultMemberName); // NOTE: the default member name is frequently null (e.g. if there is not indexer in the type). // Make sure we set a non-null value so that we don't recompute it repeatedly. // CONSIDER: this makes it impossible to distinguish between not having the attribute and // having the attribute with a value of "". Interlocked.CompareExchange(ref uncommon.lazyDefaultMemberName, defaultMemberName ?? "", null); } return uncommon.lazyDefaultMemberName; } } internal override bool IsComImport { get { return (_flags & TypeAttributes.Import) != 0; } } internal override bool ShouldAddWinRTMembers { get { return IsWindowsRuntimeImport; } } internal override bool IsWindowsRuntimeImport { get { return (_flags & TypeAttributes.WindowsRuntime) != 0; } } internal override bool GetGuidString(out string guidString) { return ContainingPEModule.Module.HasGuidAttribute(_handle, out guidString); } internal override TypeLayout Layout { get { return this.ContainingPEModule.Module.GetTypeLayout(_handle); } } internal override CharSet MarshallingCharSet { get { CharSet result = _flags.ToCharSet(); if (result == 0) { // TODO(tomat): report error return CharSet.Ansi; } return result; } } public override bool IsSerializable { get { return (_flags & TypeAttributes.Serializable) != 0; } } public override bool IsRefLikeType { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyIsByRefLike.HasValue()) { var isByRefLike = ThreeState.False; if (this.TypeKind == TypeKind.Struct) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; isByRefLike = module.HasIsByRefLikeAttribute(_handle).ToThreeState(); } uncommon.lazyIsByRefLike = isByRefLike; } return uncommon.lazyIsByRefLike.Value(); } } public override bool IsReadOnly { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyIsReadOnly.HasValue()) { var isReadOnly = ThreeState.False; if (this.TypeKind == TypeKind.Struct) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; isReadOnly = module.HasIsReadOnlyAttribute(_handle).ToThreeState(); } uncommon.lazyIsReadOnly = isReadOnly; } return uncommon.lazyIsReadOnly.Value(); } } internal override bool HasDeclarativeSecurity { get { return (_flags & TypeAttributes.HasSecurity) != 0; } } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override NamedTypeSymbol ComImportCoClass { get { if (!this.IsInterfaceType()) { return null; } var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return null; } if (ReferenceEquals(uncommon.lazyComImportCoClassType, ErrorTypeSymbol.UnknownResultType)) { var type = this.ContainingPEModule.TryDecodeAttributeWithTypeArgument(this.Handle, AttributeDescription.CoClassAttribute); var coClassType = ((object)type != null && (type.TypeKind == TypeKind.Class || type.IsErrorType())) ? (NamedTypeSymbol)type : null; Interlocked.CompareExchange(ref uncommon.lazyComImportCoClassType, coClassType, ErrorTypeSymbol.UnknownResultType); } return uncommon.lazyComImportCoClassType; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ImmutableArray<string>.Empty; } if (uncommon.lazyConditionalAttributeSymbols.IsDefault) { ImmutableArray<string> conditionalSymbols = this.ContainingPEModule.Module.GetConditionalAttributeValues(_handle); Debug.Assert(!conditionalSymbols.IsDefault); ImmutableInterlocked.InterlockedCompareExchange(ref uncommon.lazyConditionalAttributeSymbols, conditionalSymbols, default(ImmutableArray<string>)); } return uncommon.lazyConditionalAttributeSymbols; } internal override ObsoleteAttributeData ObsoleteAttributeData { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return null; } bool ignoreByRefLikeMarker = this.IsRefLikeType; ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref uncommon.lazyObsoleteAttributeData, _handle, ContainingPEModule, ignoreByRefLikeMarker); return uncommon.lazyObsoleteAttributeData; } } internal override AttributeUsageInfo GetAttributeUsageInfo() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ((object)this.BaseTypeNoUseSiteDiagnostics != null) ? this.BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo() : AttributeUsageInfo.Default; } if (uncommon.lazyAttributeUsageInfo.IsNull) { uncommon.lazyAttributeUsageInfo = this.DecodeAttributeUsageInfo(); } return uncommon.lazyAttributeUsageInfo; } private AttributeUsageInfo DecodeAttributeUsageInfo() { var handle = this.ContainingPEModule.Module.GetAttributeUsageAttributeHandle(_handle); if (!handle.IsNil) { var decoder = new MetadataDecoder(ContainingPEModule); TypedConstant[] positionalArgs; KeyValuePair<string, TypedConstant>[] namedArgs; if (decoder.GetCustomAttribute(handle, out positionalArgs, out namedArgs)) { AttributeUsageInfo info = AttributeData.DecodeAttributeUsageAttribute(positionalArgs[0], namedArgs.AsImmutableOrNull()); return info.HasValidAttributeTargets ? info : AttributeUsageInfo.Default; } } return ((object)this.BaseTypeNoUseSiteDiagnostics != null) ? this.BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo() : AttributeUsageInfo.Default; } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } /// <summary> /// Returns the index of the first member of the specific kind. /// Returns the number of members if not found. /// </summary> private static int GetIndexOfFirstMember(ImmutableArray<Symbol> members, SymbolKind kind) { int n = members.Length; for (int i = 0; i < n; i++) { if (members[i].Kind == kind) { return i; } } return n; } /// <summary> /// Returns all members of the specific kind, starting at the optional offset. /// Members of the same kind are assumed to be contiguous. /// </summary> private static IEnumerable<TSymbol> GetMembers<TSymbol>(ImmutableArray<Symbol> members, SymbolKind kind, int offset = -1) where TSymbol : Symbol { if (offset < 0) { offset = GetIndexOfFirstMember(members, kind); } int n = members.Length; for (int i = offset; i < n; i++) { var member = members[i]; if (member.Kind != kind) { yield break; } yield return (TSymbol)member; } } internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } /// <summary> /// Specialized PENamedTypeSymbol for types with no type parameters in /// metadata (no type parameters on this type and all containing types). /// </summary> private sealed class PENamedTypeSymbolNonGeneric : PENamedTypeSymbol { internal PENamedTypeSymbolNonGeneric( PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, out bool mangleName) : base(moduleSymbol, container, handle, emittedNamespaceName, 0, out mangleName) { } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; public override int Arity { get { return 0; } } internal override bool MangleName { get { return false; } } internal override int MetadataArity { get { var containingType = _container as PENamedTypeSymbol; return (object)containingType == null ? 0 : containingType.MetadataArity; } } internal override NamedTypeSymbol AsNativeInteger() { Debug.Assert(this.SpecialType == SpecialType.System_IntPtr || this.SpecialType == SpecialType.System_UIntPtr); return ContainingAssembly.GetNativeIntegerType(this); } internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return t2 is NativeIntegerTypeSymbol nativeInteger ? nativeInteger.Equals(this, comparison) : base.Equals(t2, comparison); } } /// <summary> /// Specialized PENamedTypeSymbol for types with type parameters in metadata. /// NOTE: the type may have Arity == 0 if it has same metadata arity as the metadata arity of the containing type. /// </summary> private sealed class PENamedTypeSymbolGeneric : PENamedTypeSymbol { private readonly GenericParameterHandleCollection _genericParameterHandles; private readonly ushort _arity; private readonly bool _mangleName; private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; internal PENamedTypeSymbolGeneric( PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, GenericParameterHandleCollection genericParameterHandles, ushort arity, out bool mangleName ) : base(moduleSymbol, container, handle, emittedNamespaceName, arity, out mangleName) { Debug.Assert(genericParameterHandles.Count > 0); _arity = arity; _genericParameterHandles = genericParameterHandles; _mangleName = mangleName; } protected sealed override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; public override int Arity { get { return _arity; } } internal override bool MangleName { get { return _mangleName; } } internal override int MetadataArity { get { return _genericParameterHandles.Count; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { // This is always the instance type, so the type arguments are the same as the type parameters. return GetTypeParametersAsTypeArguments(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { EnsureTypeParametersAreLoaded(); return _lazyTypeParameters; } } internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; private void EnsureTypeParametersAreLoaded() { if (_lazyTypeParameters.IsDefault) { var moduleSymbol = ContainingPEModule; // If this is a nested type generic parameters in metadata include generic parameters of the outer types. int firstIndex = _genericParameterHandles.Count - _arity; TypeParameterSymbol[] ownedParams = new TypeParameterSymbol[_arity]; for (int i = 0; i < ownedParams.Length; i++) { ownedParams[i] = new PETypeParameterSymbol(moduleSymbol, this, (ushort)i, _genericParameterHandles[firstIndex + i]); } ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameters, ImmutableArray.Create<TypeParameterSymbol>(ownedParams)); } } protected override DiagnosticInfo GetUseSiteDiagnosticImpl() { DiagnosticInfo diagnostic = null; if (!MergeUseSiteDiagnostics(ref diagnostic, base.GetUseSiteDiagnosticImpl())) { // Verify type parameters for containing types // match those on the containing types. if (!MatchesContainingTypeParameters()) { diagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this); } } return diagnostic; } /// <summary> /// Return true if the type parameters specified on the nested type (this), /// that represent the corresponding type parameters on the containing /// types, in fact match the actual type parameters on the containing types. /// </summary> private bool MatchesContainingTypeParameters() { var container = this.ContainingType; if ((object)container == null) { return true; } var containingTypeParameters = container.GetAllTypeParameters(); int n = containingTypeParameters.Length; if (n == 0) { return true; } // Create an instance of PENamedTypeSymbol for the nested type, but // with all type parameters, from the nested type and all containing // types. The type parameters on this temporary type instance are used // for comparison with those on the actual containing types. The // containing symbol for the temporary type is the namespace directly. var nestedType = Create(this.ContainingPEModule, (PENamespaceSymbol)this.ContainingNamespace, _handle, null); var nestedTypeParameters = nestedType.TypeParameters; var containingTypeMap = new TypeMap(containingTypeParameters, IndexedTypeParameterSymbol.Take(n), allowAlpha: false); var nestedTypeMap = new TypeMap(nestedTypeParameters, IndexedTypeParameterSymbol.Take(nestedTypeParameters.Length), allowAlpha: false); for (int i = 0; i < n; i++) { var containingTypeParameter = containingTypeParameters[i]; var nestedTypeParameter = nestedTypeParameters[i]; if (!MemberSignatureComparer.HaveSameConstraints(containingTypeParameter, containingTypeMap, nestedTypeParameter, nestedTypeMap)) { return false; } } return 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The class to represent all types imported from a PE/module. /// </summary> internal abstract class PENamedTypeSymbol : NamedTypeSymbol { private static readonly Dictionary<string, ImmutableArray<PENamedTypeSymbol>> s_emptyNestedTypes = new Dictionary<string, ImmutableArray<PENamedTypeSymbol>>(EmptyComparer.Instance); private readonly NamespaceOrTypeSymbol _container; private readonly TypeDefinitionHandle _handle; private readonly string _name; private readonly TypeAttributes _flags; private readonly SpecialType _corTypeId; /// <summary> /// A set of all the names of the members in this type. /// We can get names without getting members (which is a more expensive operation) /// </summary> private ICollection<string> _lazyMemberNames; /// <summary> /// We used to sort symbols on demand and relied on row ids to figure out the order between symbols of the same kind. /// However, that was fragile because, when map tables are used in metadata, row ids in the map table define the order /// and we don't have them. /// Members are grouped by kind. First we store fields, then methods, then properties, then events and finally nested types. /// Within groups, members are sorted based on declaration order. /// </summary> private ImmutableArray<Symbol> _lazyMembersInDeclarationOrder; /// <summary> /// A map of members immediately contained within this type /// grouped by their name (case-sensitively). /// </summary> private Dictionary<string, ImmutableArray<Symbol>> _lazyMembersByName; /// <summary> /// A map of types immediately contained within this type /// grouped by their name (case-sensitively). /// </summary> private Dictionary<string, ImmutableArray<PENamedTypeSymbol>> _lazyNestedTypes; /// <summary> /// Lazily initialized by TypeKind property. /// </summary> private TypeKind _lazyKind; private NullableContextKind _lazyNullableContextValue; private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType; private ImmutableArray<NamedTypeSymbol> _lazyInterfaces = default(ImmutableArray<NamedTypeSymbol>); private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType; private ImmutableArray<NamedTypeSymbol> _lazyDeclaredInterfaces = default(ImmutableArray<NamedTypeSymbol>); private Tuple<CultureInfo, string> _lazyDocComment; private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized; // There is a bunch of type properties relevant only for enums or types with custom attributes. // It is fairly easy to check whether a type s is not "uncommon". So we store uncommon properties in // a separate class with a noUncommonProperties singleton used for cases when type is "common". // this is done purely to save memory with expectation that "uncommon" cases are indeed uncommon. #region "Uncommon properties" private static readonly UncommonProperties s_noUncommonProperties = new UncommonProperties(); private UncommonProperties _lazyUncommonProperties; private UncommonProperties GetUncommonProperties() { var result = _lazyUncommonProperties; if (result != null) { #if DEBUG Debug.Assert(result != s_noUncommonProperties || result.IsDefaultValue(), "default value was modified"); #endif return result; } if (this.IsUncommon()) { result = new UncommonProperties(); return Interlocked.CompareExchange(ref _lazyUncommonProperties, result, null) ?? result; } _lazyUncommonProperties = result = s_noUncommonProperties; return result; } // enums and types with custom attributes are considered uncommon private bool IsUncommon() { if (this.ContainingPEModule.HasAnyCustomAttributes(_handle)) { return true; } if (this.TypeKind == TypeKind.Enum) { return true; } return false; } private class UncommonProperties { /// <summary> /// Need to import them for an enum from a linked assembly, when we are embedding it. These symbols are not included into lazyMembersInDeclarationOrder. /// </summary> internal ImmutableArray<PEFieldSymbol> lazyInstanceEnumFields; internal NamedTypeSymbol lazyEnumUnderlyingType; // CONSIDER: Should we use a CustomAttributeBag for PE symbols? internal ImmutableArray<CSharpAttributeData> lazyCustomAttributes; internal ImmutableArray<string> lazyConditionalAttributeSymbols; internal ObsoleteAttributeData lazyObsoleteAttributeData = ObsoleteAttributeData.Uninitialized; internal AttributeUsageInfo lazyAttributeUsageInfo = AttributeUsageInfo.Null; internal ThreeState lazyContainsExtensionMethods; internal ThreeState lazyIsByRefLike; internal ThreeState lazyIsReadOnly; internal string lazyDefaultMemberName; internal NamedTypeSymbol lazyComImportCoClassType = ErrorTypeSymbol.UnknownResultType; internal ThreeState lazyHasEmbeddedAttribute = ThreeState.Unknown; internal ThreeState lazyHasInterpolatedStringHandlerAttribute = ThreeState.Unknown; #if DEBUG internal bool IsDefaultValue() { return lazyInstanceEnumFields.IsDefault && (object)lazyEnumUnderlyingType == null && lazyCustomAttributes.IsDefault && lazyConditionalAttributeSymbols.IsDefault && lazyObsoleteAttributeData == ObsoleteAttributeData.Uninitialized && lazyAttributeUsageInfo.IsNull && !lazyContainsExtensionMethods.HasValue() && lazyDefaultMemberName == null && (object)lazyComImportCoClassType == (object)ErrorTypeSymbol.UnknownResultType && !lazyHasEmbeddedAttribute.HasValue() && !lazyHasInterpolatedStringHandlerAttribute.HasValue(); } #endif } #endregion // Uncommon properties internal static PENamedTypeSymbol Create( PEModuleSymbol moduleSymbol, PENamespaceSymbol containingNamespace, TypeDefinitionHandle handle, string emittedNamespaceName) { GenericParameterHandleCollection genericParameterHandles; ushort arity; BadImageFormatException mrEx = null; GetGenericInfo(moduleSymbol, handle, out genericParameterHandles, out arity, out mrEx); bool mangleName; PENamedTypeSymbol result; if (arity == 0) { result = new PENamedTypeSymbolNonGeneric(moduleSymbol, containingNamespace, handle, emittedNamespaceName, out mangleName); } else { result = new PENamedTypeSymbolGeneric( moduleSymbol, containingNamespace, handle, emittedNamespaceName, genericParameterHandles, arity, out mangleName); } if (mrEx != null) { result._lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, result)); } return result; } private static void GetGenericInfo(PEModuleSymbol moduleSymbol, TypeDefinitionHandle handle, out GenericParameterHandleCollection genericParameterHandles, out ushort arity, out BadImageFormatException mrEx) { try { genericParameterHandles = moduleSymbol.Module.GetTypeDefGenericParamsOrThrow(handle); arity = (ushort)genericParameterHandles.Count; mrEx = null; } catch (BadImageFormatException e) { arity = 0; genericParameterHandles = default(GenericParameterHandleCollection); mrEx = e; } } internal static PENamedTypeSymbol Create( PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, TypeDefinitionHandle handle) { GenericParameterHandleCollection genericParameterHandles; ushort metadataArity; BadImageFormatException mrEx = null; GetGenericInfo(moduleSymbol, handle, out genericParameterHandles, out metadataArity, out mrEx); ushort arity = 0; var containerMetadataArity = containingType.MetadataArity; if (metadataArity > containerMetadataArity) { arity = (ushort)(metadataArity - containerMetadataArity); } bool mangleName; PENamedTypeSymbol result; if (metadataArity == 0) { result = new PENamedTypeSymbolNonGeneric(moduleSymbol, containingType, handle, null, out mangleName); } else { result = new PENamedTypeSymbolGeneric( moduleSymbol, containingType, handle, null, genericParameterHandles, arity, out mangleName); } if (mrEx != null || metadataArity < containerMetadataArity) { result._lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, result)); } return result; } private PENamedTypeSymbol( PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, ushort arity, out bool mangleName) { Debug.Assert(!handle.IsNil); Debug.Assert((object)container != null); Debug.Assert(arity == 0 || this is PENamedTypeSymbolGeneric); string metadataName; bool makeBad = false; try { metadataName = moduleSymbol.Module.GetTypeDefNameOrThrow(handle); } catch (BadImageFormatException) { metadataName = string.Empty; makeBad = true; } _handle = handle; _container = container; try { _flags = moduleSymbol.Module.GetTypeDefFlagsOrThrow(handle); } catch (BadImageFormatException) { makeBad = true; } if (arity == 0) { _name = metadataName; mangleName = false; } else { // Unmangle name for a generic type. _name = MetadataHelpers.UnmangleMetadataNameForArity(metadataName, arity); Debug.Assert(ReferenceEquals(_name, metadataName) == (_name == metadataName)); mangleName = !ReferenceEquals(_name, metadataName); } // check if this is one of the COR library types if (emittedNamespaceName != null && moduleSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes && this.DeclaredAccessibility == Accessibility.Public) // NB: this.flags was set above. { _corTypeId = SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(emittedNamespaceName, metadataName)); } else { _corTypeId = SpecialType.None; } if (makeBad) { _lazyCachedUseSiteInfo.Initialize(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this)); } } public override SpecialType SpecialType { get { return _corTypeId; } } internal PEModuleSymbol ContainingPEModule { get { Symbol s = _container; while (s.Kind != SymbolKind.Namespace) { s = s.ContainingSymbol; } return ((PENamespaceSymbol)s).ContainingPEModule; } } internal override ModuleSymbol ContainingModule { get { return ContainingPEModule; } } public abstract override int Arity { get; } internal abstract override bool MangleName { get; } internal abstract int MetadataArity { get; } internal TypeDefinitionHandle Handle { get { return _handle; } } internal sealed override bool IsInterpolatedStringHandlerType { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyHasInterpolatedStringHandlerAttribute.HasValue()) { uncommon.lazyHasInterpolatedStringHandlerAttribute = ContainingPEModule.Module.HasInterpolatedStringHandlerAttribute(_handle).ToThreeState(); } return uncommon.lazyHasInterpolatedStringHandlerAttribute.Value(); } } internal override bool HasCodeAnalysisEmbeddedAttribute { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyHasEmbeddedAttribute.HasValue()) { uncommon.lazyHasEmbeddedAttribute = ContainingPEModule.Module.HasCodeAnalysisEmbeddedAttribute(_handle).ToThreeState(); } return uncommon.lazyHasEmbeddedAttribute.Value(); } } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get { if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType)) { Interlocked.CompareExchange(ref _lazyBaseType, MakeAcyclicBaseType(), ErrorTypeSymbol.UnknownResultType); } return _lazyBaseType; } } internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null) { if (_lazyInterfaces.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, MakeAcyclicInterfaces(), default(ImmutableArray<NamedTypeSymbol>)); } return _lazyInterfaces; } internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { return InterfacesNoUseSiteDiagnostics(); } internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) { return GetDeclaredBaseType(skipTransformsIfNecessary: false); } private NamedTypeSymbol GetDeclaredBaseType(bool skipTransformsIfNecessary) { if (ReferenceEquals(_lazyDeclaredBaseType, ErrorTypeSymbol.UnknownResultType)) { var baseType = MakeDeclaredBaseType(); if (baseType is object) { if (skipTransformsIfNecessary) { // If the transforms are not necessary, return early without updating the // base type field. This avoids cycles decoding nullability in particular. return baseType; } var moduleSymbol = ContainingPEModule; TypeSymbol decodedType = DynamicTypeDecoder.TransformType(baseType, 0, _handle, moduleSymbol); decodedType = NativeIntegerTypeDecoder.TransformType(decodedType, _handle, moduleSymbol); decodedType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(decodedType, _handle, moduleSymbol); baseType = (NamedTypeSymbol)NullableTypeDecoder.TransformType(TypeWithAnnotations.Create(decodedType), _handle, moduleSymbol, accessSymbol: this, nullableContext: this).Type; } Interlocked.CompareExchange(ref _lazyDeclaredBaseType, baseType, ErrorTypeSymbol.UnknownResultType); } return _lazyDeclaredBaseType; } internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) { if (_lazyDeclaredInterfaces.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, MakeDeclaredInterfaces(), default(ImmutableArray<NamedTypeSymbol>)); } return _lazyDeclaredInterfaces; } private NamedTypeSymbol MakeDeclaredBaseType() { if (!_flags.IsInterface()) { try { var moduleSymbol = ContainingPEModule; EntityHandle token = moduleSymbol.Module.GetBaseTypeOfTypeOrThrow(_handle); if (!token.IsNil) { return (NamedTypeSymbol)new MetadataDecoder(moduleSymbol, this).GetTypeOfToken(token); } } catch (BadImageFormatException mrEx) { return new UnsupportedMetadataTypeSymbol(mrEx); } } return null; } private ImmutableArray<NamedTypeSymbol> MakeDeclaredInterfaces() { try { var moduleSymbol = ContainingPEModule; var interfaceImpls = moduleSymbol.Module.GetInterfaceImplementationsOrThrow(_handle); if (interfaceImpls.Count > 0) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(interfaceImpls.Count); var tokenDecoder = new MetadataDecoder(moduleSymbol, this); foreach (var interfaceImpl in interfaceImpls) { EntityHandle interfaceHandle = moduleSymbol.Module.MetadataReader.GetInterfaceImplementation(interfaceImpl).Interface; TypeSymbol typeSymbol = tokenDecoder.GetTypeOfToken(interfaceHandle); typeSymbol = NativeIntegerTypeDecoder.TransformType(typeSymbol, interfaceImpl, moduleSymbol); typeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeSymbol, interfaceImpl, moduleSymbol); typeSymbol = NullableTypeDecoder.TransformType(TypeWithAnnotations.Create(typeSymbol), interfaceImpl, moduleSymbol, accessSymbol: this, nullableContext: this).Type; var namedTypeSymbol = typeSymbol as NamedTypeSymbol ?? new UnsupportedMetadataTypeSymbol(); // interface list contains a bad type symbols.Add(namedTypeSymbol); } return symbols.ToImmutableAndFree(); } return ImmutableArray<NamedTypeSymbol>.Empty; } catch (BadImageFormatException mrEx) { return ImmutableArray.Create<NamedTypeSymbol>(new UnsupportedMetadataTypeSymbol(mrEx)); } } public override NamedTypeSymbol ConstructedFrom { get { return this; } } public override Symbol ContainingSymbol { get { return _container; } } public override NamedTypeSymbol ContainingType { get { return _container as NamedTypeSymbol; } } internal override bool IsRecord { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return SynthesizedRecordClone.FindValidCloneMethod(this, ref discardedUseSiteInfo) != null; } } // Record structs get erased when emitted to metadata internal override bool IsRecordStruct => false; public override Accessibility DeclaredAccessibility { get { Accessibility access = Accessibility.Private; switch (_flags & TypeAttributes.VisibilityMask) { case TypeAttributes.NestedAssembly: access = Accessibility.Internal; break; case TypeAttributes.NestedFamORAssem: access = Accessibility.ProtectedOrInternal; break; case TypeAttributes.NestedFamANDAssem: access = Accessibility.ProtectedAndInternal; break; case TypeAttributes.NestedPrivate: access = Accessibility.Private; break; case TypeAttributes.Public: case TypeAttributes.NestedPublic: access = Accessibility.Public; break; case TypeAttributes.NestedFamily: access = Accessibility.Protected; break; case TypeAttributes.NotPublic: access = Accessibility.Internal; break; default: throw ExceptionUtilities.UnexpectedValue(_flags & TypeAttributes.VisibilityMask); } return access; } } public override NamedTypeSymbol EnumUnderlyingType { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return null; } this.EnsureEnumUnderlyingTypeIsLoaded(uncommon); return uncommon.lazyEnumUnderlyingType; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ImmutableArray<CSharpAttributeData>.Empty; } if (uncommon.lazyCustomAttributes.IsDefault) { var loadedCustomAttributes = ContainingPEModule.GetCustomAttributesForToken( Handle, out _, // Filter out [Extension] MightContainExtensionMethods ? AttributeDescription.CaseSensitiveExtensionAttribute : default, out _, // Filter out [Obsolete], unless it was user defined (IsRefLikeType && ObsoleteAttributeData is null) ? AttributeDescription.ObsoleteAttribute : default, out _, // Filter out [IsReadOnly] IsReadOnly ? AttributeDescription.IsReadOnlyAttribute : default, out _, // Filter out [IsByRefLike] IsRefLikeType ? AttributeDescription.IsByRefLikeAttribute : default); ImmutableInterlocked.InterlockedInitialize(ref uncommon.lazyCustomAttributes, loadedCustomAttributes); } return uncommon.lazyCustomAttributes; } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return GetAttributes(); } internal override byte? GetNullableContextValue() { byte? value; if (!_lazyNullableContextValue.TryGetByte(out value)) { value = ContainingPEModule.Module.HasNullableContextAttribute(_handle, out byte arg) ? arg : _container.GetNullableContextValue(); _lazyNullableContextValue = value.ToNullableContextFlags(); } return value; } internal override byte? GetLocalNullableContextValue() { throw ExceptionUtilities.Unreachable; } public override IEnumerable<string> MemberNames { get { EnsureNonTypeMemberNamesAreLoaded(); return _lazyMemberNames; } } private void EnsureNonTypeMemberNamesAreLoaded() { if (_lazyMemberNames == null) { var moduleSymbol = ContainingPEModule; var module = moduleSymbol.Module; var names = new HashSet<string>(); try { foreach (var methodDef in module.GetMethodsOfTypeOrThrow(_handle)) { try { names.Add(module.GetMethodDefNameOrThrow(methodDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } try { foreach (var propertyDef in module.GetPropertiesOfTypeOrThrow(_handle)) { try { names.Add(module.GetPropertyDefNameOrThrow(propertyDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } try { foreach (var eventDef in module.GetEventsOfTypeOrThrow(_handle)) { try { names.Add(module.GetEventDefNameOrThrow(eventDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { try { names.Add(module.GetFieldDefNameOrThrow(fieldDef)); } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } // From C#'s perspective, structs always have a public constructor // (even if it's not in metadata). Add it unconditionally and let // the hash set de-dup. if (this.IsValueType) { names.Add(WellKnownMemberNames.InstanceConstructorName); } Interlocked.CompareExchange(ref _lazyMemberNames, CreateReadOnlyMemberNames(names), null); } } private static ICollection<string> CreateReadOnlyMemberNames(HashSet<string> names) { switch (names.Count) { case 0: return SpecializedCollections.EmptySet<string>(); case 1: return SpecializedCollections.SingletonCollection(names.First()); case 2: case 3: case 4: case 5: case 6: // PERF: Small collections can be implemented as ImmutableArray. // While lookup is O(n), when n is small, the memory savings are more valuable. // Size 6 was chosen because that represented 50% of the names generated in the Picasso end to end. // This causes boxing, but that's still superior to a wrapped HashSet return ImmutableArray.CreateRange(names); default: return SpecializedCollections.ReadOnlySet(names); } } public override ImmutableArray<Symbol> GetMembers() { EnsureAllMembersAreLoaded(); return _lazyMembersInDeclarationOrder; } private IEnumerable<FieldSymbol> GetEnumFieldsToEmit() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { yield break; } var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; // Non-static fields of enum types are not imported by default because they are not bindable, // but we need them for NoPia. var fieldDefs = ArrayBuilder<FieldDefinitionHandle>.GetInstance(); try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { fieldDefs.Add(fieldDef); } } catch (BadImageFormatException) { } if (uncommon.lazyInstanceEnumFields.IsDefault) { var builder = ArrayBuilder<PEFieldSymbol>.GetInstance(); foreach (var fieldDef in fieldDefs) { try { FieldAttributes fieldFlags = module.GetFieldDefFlagsOrThrow(fieldDef); if ((fieldFlags & FieldAttributes.Static) == 0 && ModuleExtensions.ShouldImportField(fieldFlags, moduleSymbol.ImportOptions)) { builder.Add(new PEFieldSymbol(moduleSymbol, this, fieldDef)); } } catch (BadImageFormatException) { } } ImmutableInterlocked.InterlockedInitialize(ref uncommon.lazyInstanceEnumFields, builder.ToImmutableAndFree()); } int staticIndex = 0; ImmutableArray<Symbol> staticFields = GetMembers(); int instanceIndex = 0; foreach (var fieldDef in fieldDefs) { if (instanceIndex < uncommon.lazyInstanceEnumFields.Length && uncommon.lazyInstanceEnumFields[instanceIndex].Handle == fieldDef) { yield return uncommon.lazyInstanceEnumFields[instanceIndex]; instanceIndex++; continue; } if (staticIndex < staticFields.Length && staticFields[staticIndex].Kind == SymbolKind.Field) { var field = (PEFieldSymbol)staticFields[staticIndex]; if (field.Handle == fieldDef) { yield return field; staticIndex++; continue; } } } fieldDefs.Free(); Debug.Assert(instanceIndex == uncommon.lazyInstanceEnumFields.Length); Debug.Assert(staticIndex == staticFields.Length || staticFields[staticIndex].Kind != SymbolKind.Field); } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { return GetEnumFieldsToEmit(); } else { // If there are any non-event fields, they are at the very beginning. IEnumerable<FieldSymbol> nonEventFields = GetMembers<FieldSymbol>(this.GetMembers().WhereAsArray(m => !(m is TupleErrorFieldSymbol)), SymbolKind.Field, offset: 0); // Event backing fields are not part of the set returned by GetMembers. Let's add them manually. ArrayBuilder<FieldSymbol> eventFields = null; foreach (var eventSymbol in GetEventsToEmit()) { FieldSymbol associatedField = eventSymbol.AssociatedField; if ((object)associatedField != null) { Debug.Assert((object)associatedField.AssociatedSymbol != null); Debug.Assert(!nonEventFields.Contains(associatedField)); if (eventFields == null) { eventFields = ArrayBuilder<FieldSymbol>.GetInstance(); } eventFields.Add(associatedField); } } if (eventFields == null) { // Simple case return nonEventFields; } // We need to merge non-event fields with event fields while preserving their relative declaration order var handleToFieldMap = new SmallDictionary<FieldDefinitionHandle, FieldSymbol>(); int count = 0; foreach (PEFieldSymbol field in nonEventFields) { handleToFieldMap.Add(field.Handle, field); count++; } foreach (PEFieldSymbol field in eventFields) { handleToFieldMap.Add(field.Handle, field); } count += eventFields.Count; eventFields.Free(); var result = ArrayBuilder<FieldSymbol>.GetInstance(count); try { foreach (var handle in this.ContainingPEModule.Module.GetFieldsOfTypeOrThrow(_handle)) { FieldSymbol field; if (handleToFieldMap.TryGetValue(handle, out field)) { result.Add(field); } } } catch (BadImageFormatException) { } Debug.Assert(result.Count == count); return result.ToImmutableAndFree(); } } internal override IEnumerable<MethodSymbol> GetMethodsToEmit() { ImmutableArray<Symbol> members = GetMembers(); // Get to methods. int index = GetIndexOfFirstMember(members, SymbolKind.Method); if (!this.IsInterfaceType()) { for (; index < members.Length; index++) { if (members[index].Kind != SymbolKind.Method) { break; } var method = (MethodSymbol)members[index]; // Don't emit the default value type constructor - the runtime handles that. // For parameterless struct constructors from metadata, IsDefaultValueTypeConstructor() // ignores requireZeroInit and simply checks if the method is implicitly declared. if (!method.IsDefaultValueTypeConstructor(requireZeroInit: false)) { yield return method; } } } else { // We do not create symbols for v-table gap methods, let's figure out where the gaps go. if (index >= members.Length || members[index].Kind != SymbolKind.Method) { // We didn't import any methods, it is Ok to return an empty set. yield break; } var method = (PEMethodSymbol)members[index]; var module = this.ContainingPEModule.Module; var methodDefs = ArrayBuilder<MethodDefinitionHandle>.GetInstance(); try { foreach (var methodDef in module.GetMethodsOfTypeOrThrow(_handle)) { methodDefs.Add(methodDef); } } catch (BadImageFormatException) { } foreach (var methodDef in methodDefs) { if (method.Handle == methodDef) { yield return method; index++; if (index == members.Length || members[index].Kind != SymbolKind.Method) { // no need to return any gaps at the end. methodDefs.Free(); yield break; } method = (PEMethodSymbol)members[index]; } else { // Encountered a gap. int gapSize; try { gapSize = ModuleExtensions.GetVTableGapSize(module.GetMethodDefNameOrThrow(methodDef)); } catch (BadImageFormatException) { gapSize = 1; } // We don't have a symbol to return, so, even if the name doesn't represent a gap, we still have a gap. do { yield return null; gapSize--; } while (gapSize > 0); } } // Ensure we explicitly returned from inside loop. throw ExceptionUtilities.Unreachable; } } internal override IEnumerable<PropertySymbol> GetPropertiesToEmit() { return GetMembers<PropertySymbol>(this.GetMembers(), SymbolKind.Property); } internal override IEnumerable<EventSymbol> GetEventsToEmit() { return GetMembers<EventSymbol>(this.GetMembers(), SymbolKind.Event); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return this.GetMembersUnordered(); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { return this.GetMembers(name); } private class DeclarationOrderTypeSymbolComparer : IComparer<Symbol> { public static readonly DeclarationOrderTypeSymbolComparer Instance = new DeclarationOrderTypeSymbolComparer(); private DeclarationOrderTypeSymbolComparer() { } public int Compare(Symbol x, Symbol y) { return HandleComparer.Default.Compare(((PENamedTypeSymbol)x).Handle, ((PENamedTypeSymbol)y).Handle); } } private void EnsureEnumUnderlyingTypeIsLoaded(UncommonProperties uncommon) { if ((object)(uncommon.lazyEnumUnderlyingType) == null && this.TypeKind == TypeKind.Enum) { // From §8.5.2 // An enum is considerably more restricted than a true type, as // follows: // - It shall have exactly one instance field, and the type of that field defines the underlying type of // the enumeration. // - It shall not have any static fields unless they are literal. (see §8.6.1.2) // The underlying type shall be a built-in integer type. Enums shall derive from System.Enum, hence they are // value types. Like all value types, they shall be sealed (see §8.9.9). var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; var decoder = new MetadataDecoder(moduleSymbol, this); NamedTypeSymbol underlyingType = null; try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { FieldAttributes fieldFlags; try { fieldFlags = module.GetFieldDefFlagsOrThrow(fieldDef); } catch (BadImageFormatException) { continue; } if ((fieldFlags & FieldAttributes.Static) == 0) { // Instance field used to determine underlying type. ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers; TypeSymbol type = decoder.DecodeFieldSignature(fieldDef, out customModifiers); if (type.SpecialType.IsValidEnumUnderlyingType() && !customModifiers.AnyRequired()) { if ((object)underlyingType == null) { underlyingType = (NamedTypeSymbol)type; } else { underlyingType = new UnsupportedMetadataTypeSymbol(); // ambiguous underlying type } } } } if ((object)underlyingType == null) { underlyingType = new UnsupportedMetadataTypeSymbol(); // undefined underlying type } } catch (BadImageFormatException mrEx) { if ((object)underlyingType == null) { underlyingType = new UnsupportedMetadataTypeSymbol(mrEx); } } Interlocked.CompareExchange(ref uncommon.lazyEnumUnderlyingType, underlyingType, null); } } private void EnsureAllMembersAreLoaded() { if (_lazyMembersByName == null) { LoadMembers(); } } private void LoadMembers() { ArrayBuilder<Symbol> members = null; if (_lazyMembersInDeclarationOrder.IsDefault) { EnsureNestedTypesAreLoaded(); members = ArrayBuilder<Symbol>.GetInstance(); Debug.Assert(SymbolKind.Field.ToSortOrder() < SymbolKind.Method.ToSortOrder()); Debug.Assert(SymbolKind.Method.ToSortOrder() < SymbolKind.Property.ToSortOrder()); Debug.Assert(SymbolKind.Property.ToSortOrder() < SymbolKind.Event.ToSortOrder()); Debug.Assert(SymbolKind.Event.ToSortOrder() < SymbolKind.NamedType.ToSortOrder()); if (this.TypeKind == TypeKind.Enum) { EnsureEnumUnderlyingTypeIsLoaded(this.GetUncommonProperties()); var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; try { foreach (var fieldDef in module.GetFieldsOfTypeOrThrow(_handle)) { FieldAttributes fieldFlags; try { fieldFlags = module.GetFieldDefFlagsOrThrow(fieldDef); if ((fieldFlags & FieldAttributes.Static) == 0) { continue; } } catch (BadImageFormatException) { fieldFlags = 0; } if (ModuleExtensions.ShouldImportField(fieldFlags, moduleSymbol.ImportOptions)) { var field = new PEFieldSymbol(moduleSymbol, this, fieldDef); members.Add(field); } } } catch (BadImageFormatException) { } var syntheticCtor = new SynthesizedInstanceConstructor(this); members.Add(syntheticCtor); } else { ArrayBuilder<PEFieldSymbol> fieldMembers = ArrayBuilder<PEFieldSymbol>.GetInstance(); ArrayBuilder<Symbol> nonFieldMembers = ArrayBuilder<Symbol>.GetInstance(); MultiDictionary<string, PEFieldSymbol> privateFieldNameToSymbols = this.CreateFields(fieldMembers); // A method may be referenced as an accessor by one or more properties. And, // any of those properties may be "bogus" if one of the property accessors // does not match the property signature. If the method is referenced by at // least one non-bogus property, then the method is created as an accessor, // and (for purposes of error reporting if the method is referenced directly) the // associated property is set (arbitrarily) to the first non-bogus property found // in metadata. If the method is not referenced by any non-bogus properties, // then the method is created as a normal method rather than an accessor. // Create a dictionary of method symbols indexed by metadata handle // (to allow efficient lookup when matching property accessors). PooledDictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol = this.CreateMethods(nonFieldMembers); if (this.TypeKind == TypeKind.Struct) { bool haveParameterlessConstructor = false; foreach (MethodSymbol method in nonFieldMembers) { if (method.IsParameterlessConstructor()) { haveParameterlessConstructor = true; break; } } // Structs have an implicit parameterless constructor, even if it // does not appear in metadata (11.3.8) if (!haveParameterlessConstructor) { nonFieldMembers.Insert(0, new SynthesizedInstanceConstructor(this)); } } this.CreateProperties(methodHandleToSymbol, nonFieldMembers); this.CreateEvents(privateFieldNameToSymbols, methodHandleToSymbol, nonFieldMembers); foreach (PEFieldSymbol field in fieldMembers) { if ((object)field.AssociatedSymbol == null) { members.Add(field); } else { // As for source symbols, our public API presents the fiction that all // operations are performed on the event, rather than on the backing field. // The backing field is not accessible through the API. As an additional // bonus, lookup is easier when the names don't collide. Debug.Assert(field.AssociatedSymbol.Kind == SymbolKind.Event); } } members.AddRange(nonFieldMembers); nonFieldMembers.Free(); fieldMembers.Free(); methodHandleToSymbol.Free(); } // Now add types to the end. int membersCount = members.Count; foreach (var typeArray in _lazyNestedTypes.Values) { members.AddRange(typeArray); } // Sort the types based on row id. members.Sort(membersCount, DeclarationOrderTypeSymbolComparer.Instance); #if DEBUG Symbol previous = null; foreach (var s in members) { if (previous == null) { previous = s; } else { Symbol current = s; Debug.Assert(previous.Kind.ToSortOrder() <= current.Kind.ToSortOrder()); previous = current; } } #endif if (IsTupleType) { int originalCount = members.Count; var peMembers = members.ToImmutableAndFree(); members = MakeSynthesizedTupleMembers(peMembers); membersCount += members.Count; // account for added tuple error fields members.AddRange(peMembers); Debug.Assert(members is object); } var membersInDeclarationOrder = members.ToImmutable(); if (!ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersInDeclarationOrder, membersInDeclarationOrder)) { members.Free(); members = null; } else { // remove the types members.Clip(membersCount); } } if (_lazyMembersByName == null) { if (members == null) { members = ArrayBuilder<Symbol>.GetInstance(); foreach (var member in _lazyMembersInDeclarationOrder) { if (member.Kind == SymbolKind.NamedType) { break; } members.Add(member); } } Dictionary<string, ImmutableArray<Symbol>> membersDict = GroupByName(members); var exchangeResult = Interlocked.CompareExchange(ref _lazyMembersByName, membersDict, null); if (exchangeResult == null) { // we successfully swapped in the members dictionary. // Now, use these as the canonical member names. This saves us memory by not having // two collections around at the same time with redundant data in them. // // NOTE(cyrusn): We must use an interlocked exchange here so that the full // construction of this object will be seen from 'MemberNames'. Also, doing a // straight InterlockedExchange here is the right thing to do. Consider the case // where one thread is calling in through "MemberNames" while we are in the middle // of this method. Either that thread will compute the member names and store it // first (in which case we overwrite it), or we will store first (in which case // their CompareExchange(..., ..., null) will fail. Either way, this will be certain // to become the canonical set of member names. // // NOTE(cyrusn): This means that it is possible (and by design) for people to get a // different object back when they call MemberNames multiple times. However, outside // of object identity, both collections should appear identical to the user. var memberNames = SpecializedCollections.ReadOnlyCollection(membersDict.Keys); Interlocked.Exchange(ref _lazyMemberNames, memberNames); } } if (members != null) { members.Free(); } } internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { EnsureAllMembersAreLoaded(); ImmutableArray<Symbol> m; if (!_lazyMembersByName.TryGetValue(name, out m)) { m = ImmutableArray<Symbol>.Empty; } return m; } public override ImmutableArray<Symbol> GetMembers(string name) { EnsureAllMembersAreLoaded(); ImmutableArray<Symbol> m; if (!_lazyMembersByName.TryGetValue(name, out m)) { m = ImmutableArray<Symbol>.Empty; } // nested types are not common, but we need to check just in case ImmutableArray<PENamedTypeSymbol> t; if (_lazyNestedTypes.TryGetValue(name, out t)) { m = m.Concat(StaticCast<Symbol>.From(t)); } return m; } internal sealed override bool HasPossibleWellKnownCloneMethod() => MemberNames.Contains(WellKnownMemberNames.CloneMethodName); internal override FieldSymbol FixedElementField { get { FieldSymbol result = null; var candidates = this.GetMembers(FixedFieldImplementationType.FixedElementFieldName); if (!candidates.IsDefault && candidates.Length == 1) { result = candidates[0] as FieldSymbol; } return result; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembers().ConditionallyDeOrder(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { EnsureNestedTypesAreLoaded(); return GetMemberTypesPrivate(); } private ImmutableArray<NamedTypeSymbol> GetMemberTypesPrivate() { var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); foreach (var typeArray in _lazyNestedTypes.Values) { builder.AddRange(typeArray); } return builder.ToImmutableAndFree(); } private void EnsureNestedTypesAreLoaded() { if (_lazyNestedTypes == null) { var types = ArrayBuilder<PENamedTypeSymbol>.GetInstance(); types.AddRange(this.CreateNestedTypes()); var typesDict = GroupByName(types); var exchangeResult = Interlocked.CompareExchange(ref _lazyNestedTypes, typesDict, null); if (exchangeResult == null) { // Build cache of TypeDef Tokens // Potentially this can be done in the background. var moduleSymbol = this.ContainingPEModule; moduleSymbol.OnNewTypeDeclarationsLoaded(typesDict); } types.Free(); } } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { EnsureNestedTypesAreLoaded(); ImmutableArray<PENamedTypeSymbol> t; if (_lazyNestedTypes.TryGetValue(name, out t)) { return StaticCast<NamedTypeSymbol>.From(t); } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((type, arity) => type.Arity == arity, arity); } public override ImmutableArray<Location> Locations { get { return ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override string Name { get { return _name; } } internal override bool HasSpecialName { get { return (_flags & TypeAttributes.SpecialName) != 0; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override bool IsStatic { get { return (_flags & TypeAttributes.Sealed) != 0 && (_flags & TypeAttributes.Abstract) != 0; } } public override bool IsAbstract { get { return (_flags & TypeAttributes.Abstract) != 0 && (_flags & TypeAttributes.Sealed) == 0; } } internal override bool IsMetadataAbstract { get { return (_flags & TypeAttributes.Abstract) != 0; } } public override bool IsSealed { get { return (_flags & TypeAttributes.Sealed) != 0 && (_flags & TypeAttributes.Abstract) == 0; } } internal override bool IsMetadataSealed { get { return (_flags & TypeAttributes.Sealed) != 0; } } internal TypeAttributes Flags { get { return _flags; } } public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } public override bool MightContainExtensionMethods { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyContainsExtensionMethods.HasValue()) { var contains = ThreeState.False; // Dev11 supports extension methods defined on non-static // classes, structs, delegates, and generic types. switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Delegate: var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; bool moduleHasExtension = module.HasExtensionAttribute(_handle, ignoreCase: false); var containingAssembly = this.ContainingAssembly as PEAssemblySymbol; if ((object)containingAssembly != null) { contains = (moduleHasExtension && containingAssembly.MightContainExtensionMethods).ToThreeState(); } else { contains = moduleHasExtension.ToThreeState(); } break; } uncommon.lazyContainsExtensionMethods = contains; } return uncommon.lazyContainsExtensionMethods.Value(); } } public override TypeKind TypeKind { get { TypeKind result = _lazyKind; if (result == TypeKind.Unknown) { if (_flags.IsInterface()) { result = TypeKind.Interface; } else { TypeSymbol @base = GetDeclaredBaseType(skipTransformsIfNecessary: true); result = TypeKind.Class; if ((object)@base != null) { SpecialType baseCorTypeId = @base.SpecialType; switch (baseCorTypeId) { case SpecialType.System_Enum: // Enum result = TypeKind.Enum; break; case SpecialType.System_MulticastDelegate: // Delegate result = TypeKind.Delegate; break; case SpecialType.System_ValueType: // System.Enum is the only class that derives from ValueType if (this.SpecialType != SpecialType.System_Enum) { // Struct result = TypeKind.Struct; } break; } } } _lazyKind = result; } return result; } } internal sealed override bool IsInterface { get { return _flags.IsInterface(); } } private static ExtendedErrorTypeSymbol CyclicInheritanceError(PENamedTypeSymbol type, TypeSymbol declaredBase) { var info = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase, type); return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, info, true); } private NamedTypeSymbol MakeAcyclicBaseType() { NamedTypeSymbol declaredBase = GetDeclaredBaseType(null); // implicit base is not interesting for metadata cycle detection if ((object)declaredBase == null) { return null; } if (BaseTypeAnalysis.TypeDependsOn(declaredBase, this)) { return CyclicInheritanceError(this, declaredBase); } this.SetKnownToHaveNoDeclaredBaseCycles(); return declaredBase; } private ImmutableArray<NamedTypeSymbol> MakeAcyclicInterfaces() { var declaredInterfaces = GetDeclaredInterfaces(null); if (!IsInterface) { // only interfaces needs to check for inheritance cycles via interfaces. return declaredInterfaces; } return declaredInterfaces .SelectAsArray(t => BaseTypeAnalysis.TypeDependsOn(t, this) ? CyclicInheritanceError(this, t) : t); } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return PEDocumentationCommentUtils.GetDocumentationComment(this, ContainingPEModule, preferredCulture, cancellationToken, ref _lazyDocComment); } private IEnumerable<PENamedTypeSymbol> CreateNestedTypes() { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; ImmutableArray<TypeDefinitionHandle> nestedTypeDefs; try { nestedTypeDefs = module.GetNestedTypeDefsOrThrow(_handle); } catch (BadImageFormatException) { yield break; } foreach (var typeRid in nestedTypeDefs) { if (module.ShouldImportNestedType(typeRid)) { yield return PENamedTypeSymbol.Create(moduleSymbol, this, typeRid); } } } private MultiDictionary<string, PEFieldSymbol> CreateFields(ArrayBuilder<PEFieldSymbol> fieldMembers) { var privateFieldNameToSymbols = new MultiDictionary<string, PEFieldSymbol>(); var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; // for ordinary struct types we import private fields so that we can distinguish empty structs from non-empty structs var isOrdinaryStruct = false; // for ordinary embeddable struct types we import private members so that we can report appropriate errors if the structure is used var isOrdinaryEmbeddableStruct = false; if (this.TypeKind == TypeKind.Struct) { if (this.SpecialType == Microsoft.CodeAnalysis.SpecialType.None) { isOrdinaryStruct = true; isOrdinaryEmbeddableStruct = this.ContainingAssembly.IsLinked; } else { isOrdinaryStruct = (this.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Nullable_T); } } try { foreach (var fieldRid in module.GetFieldsOfTypeOrThrow(_handle)) { try { if (!(isOrdinaryEmbeddableStruct || (isOrdinaryStruct && (module.GetFieldDefFlagsOrThrow(fieldRid) & FieldAttributes.Static) == 0) || module.ShouldImportField(fieldRid, moduleSymbol.ImportOptions))) { continue; } } catch (BadImageFormatException) { } var symbol = new PEFieldSymbol(moduleSymbol, this, fieldRid); fieldMembers.Add(symbol); // Only private fields are potentially backing fields for field-like events. if (symbol.DeclaredAccessibility == Accessibility.Private) { var name = symbol.Name; if (name.Length > 0) { privateFieldNameToSymbols.Add(name, symbol); } } } } catch (BadImageFormatException) { } return privateFieldNameToSymbols; } private PooledDictionary<MethodDefinitionHandle, PEMethodSymbol> CreateMethods(ArrayBuilder<Symbol> members) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; var map = PooledDictionary<MethodDefinitionHandle, PEMethodSymbol>.GetInstance(); // for ordinary embeddable struct types we import private members so that we can report appropriate errors if the structure is used var isOrdinaryEmbeddableStruct = (this.TypeKind == TypeKind.Struct) && (this.SpecialType == Microsoft.CodeAnalysis.SpecialType.None) && this.ContainingAssembly.IsLinked; try { foreach (var methodHandle in module.GetMethodsOfTypeOrThrow(_handle)) { if (isOrdinaryEmbeddableStruct || module.ShouldImportMethod(_handle, methodHandle, moduleSymbol.ImportOptions)) { var method = new PEMethodSymbol(moduleSymbol, this, methodHandle); members.Add(method); map.Add(methodHandle, method); } } } catch (BadImageFormatException) { } return map; } private void CreateProperties(Dictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol, ArrayBuilder<Symbol> members) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; try { foreach (var propertyDef in module.GetPropertiesOfTypeOrThrow(_handle)) { try { var methods = module.GetPropertyMethodsOrThrow(propertyDef); PEMethodSymbol getMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Getter); PEMethodSymbol setMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Setter); if (((object)getMethod != null) || ((object)setMethod != null)) { members.Add(PEPropertySymbol.Create(moduleSymbol, this, propertyDef, getMethod, setMethod)); } } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } } private void CreateEvents( MultiDictionary<string, PEFieldSymbol> privateFieldNameToSymbols, Dictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol, ArrayBuilder<Symbol> members) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; try { foreach (var eventRid in module.GetEventsOfTypeOrThrow(_handle)) { try { var methods = module.GetEventMethodsOrThrow(eventRid); // NOTE: C# ignores all other accessors (most notably, raise/fire). PEMethodSymbol addMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Adder); PEMethodSymbol removeMethod = GetAccessorMethod(module, methodHandleToSymbol, _handle, methods.Remover); // NOTE: both accessors are required, but that will be reported separately. // Create the symbol unless both accessors are missing. if (((object)addMethod != null) || ((object)removeMethod != null)) { members.Add(new PEEventSymbol(moduleSymbol, this, eventRid, addMethod, removeMethod, privateFieldNameToSymbols)); } } catch (BadImageFormatException) { } } } catch (BadImageFormatException) { } } private PEMethodSymbol GetAccessorMethod(PEModule module, Dictionary<MethodDefinitionHandle, PEMethodSymbol> methodHandleToSymbol, TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef) { if (methodDef.IsNil) { return null; } PEMethodSymbol method; bool found = methodHandleToSymbol.TryGetValue(methodDef, out method); Debug.Assert(found || !module.ShouldImportMethod(typeDef, methodDef, this.ContainingPEModule.ImportOptions)); return method; } private static Dictionary<string, ImmutableArray<Symbol>> GroupByName(ArrayBuilder<Symbol> symbols) { return symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); } private static Dictionary<string, ImmutableArray<PENamedTypeSymbol>> GroupByName(ArrayBuilder<PENamedTypeSymbol> symbols) { if (symbols.Count == 0) { return s_emptyNestedTypes; } return symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (!_lazyCachedUseSiteInfo.IsInitialized) { AssemblySymbol primaryDependency = PrimaryDependency; _lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo<AssemblySymbol>(primaryDependency).AdjustDiagnosticInfo(GetUseSiteDiagnosticImpl())); } return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency); } protected virtual DiagnosticInfo GetUseSiteDiagnosticImpl() { DiagnosticInfo diagnostic = null; if (!MergeUseSiteDiagnostics(ref diagnostic, CalculateUseSiteDiagnostic())) { // Check if this type is marked by RequiredAttribute attribute. // If so mark the type as bad, because it relies upon semantics that are not understood by the C# compiler. if (this.ContainingPEModule.Module.HasRequiredAttributeAttribute(_handle)) { diagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this); } else if (TypeKind == TypeKind.Class && SpecialType != SpecialType.System_Enum) { TypeSymbol @base = GetDeclaredBaseType(null); if (@base?.SpecialType == SpecialType.None && @base.ContainingAssembly?.IsMissing == true) { var missingType = @base as MissingMetadataTypeSymbol.TopLevel; if ((object)missingType != null && missingType.Arity == 0) { string emittedName = MetadataHelpers.BuildQualifiedName(missingType.NamespaceName, missingType.MetadataName); switch (SpecialTypes.GetTypeFromMetadataName(emittedName)) { case SpecialType.System_Enum: case SpecialType.System_MulticastDelegate: case SpecialType.System_ValueType: // This might be a structure, an enum, or a delegate diagnostic = missingType.GetUseSiteInfo().DiagnosticInfo; break; } } } } } return diagnostic; } internal string DefaultMemberName { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ""; } if (uncommon.lazyDefaultMemberName == null) { string defaultMemberName; this.ContainingPEModule.Module.HasDefaultMemberAttribute(_handle, out defaultMemberName); // NOTE: the default member name is frequently null (e.g. if there is not indexer in the type). // Make sure we set a non-null value so that we don't recompute it repeatedly. // CONSIDER: this makes it impossible to distinguish between not having the attribute and // having the attribute with a value of "". Interlocked.CompareExchange(ref uncommon.lazyDefaultMemberName, defaultMemberName ?? "", null); } return uncommon.lazyDefaultMemberName; } } internal override bool IsComImport { get { return (_flags & TypeAttributes.Import) != 0; } } internal override bool ShouldAddWinRTMembers { get { return IsWindowsRuntimeImport; } } internal override bool IsWindowsRuntimeImport { get { return (_flags & TypeAttributes.WindowsRuntime) != 0; } } internal override bool GetGuidString(out string guidString) { return ContainingPEModule.Module.HasGuidAttribute(_handle, out guidString); } internal override TypeLayout Layout { get { return this.ContainingPEModule.Module.GetTypeLayout(_handle); } } internal override CharSet MarshallingCharSet { get { CharSet result = _flags.ToCharSet(); if (result == 0) { // TODO(tomat): report error return CharSet.Ansi; } return result; } } public override bool IsSerializable { get { return (_flags & TypeAttributes.Serializable) != 0; } } public override bool IsRefLikeType { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyIsByRefLike.HasValue()) { var isByRefLike = ThreeState.False; if (this.TypeKind == TypeKind.Struct) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; isByRefLike = module.HasIsByRefLikeAttribute(_handle).ToThreeState(); } uncommon.lazyIsByRefLike = isByRefLike; } return uncommon.lazyIsByRefLike.Value(); } } public override bool IsReadOnly { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return false; } if (!uncommon.lazyIsReadOnly.HasValue()) { var isReadOnly = ThreeState.False; if (this.TypeKind == TypeKind.Struct) { var moduleSymbol = this.ContainingPEModule; var module = moduleSymbol.Module; isReadOnly = module.HasIsReadOnlyAttribute(_handle).ToThreeState(); } uncommon.lazyIsReadOnly = isReadOnly; } return uncommon.lazyIsReadOnly.Value(); } } internal override bool HasDeclarativeSecurity { get { return (_flags & TypeAttributes.HasSecurity) != 0; } } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override NamedTypeSymbol ComImportCoClass { get { if (!this.IsInterfaceType()) { return null; } var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return null; } if (ReferenceEquals(uncommon.lazyComImportCoClassType, ErrorTypeSymbol.UnknownResultType)) { var type = this.ContainingPEModule.TryDecodeAttributeWithTypeArgument(this.Handle, AttributeDescription.CoClassAttribute); var coClassType = ((object)type != null && (type.TypeKind == TypeKind.Class || type.IsErrorType())) ? (NamedTypeSymbol)type : null; Interlocked.CompareExchange(ref uncommon.lazyComImportCoClassType, coClassType, ErrorTypeSymbol.UnknownResultType); } return uncommon.lazyComImportCoClassType; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ImmutableArray<string>.Empty; } if (uncommon.lazyConditionalAttributeSymbols.IsDefault) { ImmutableArray<string> conditionalSymbols = this.ContainingPEModule.Module.GetConditionalAttributeValues(_handle); Debug.Assert(!conditionalSymbols.IsDefault); ImmutableInterlocked.InterlockedCompareExchange(ref uncommon.lazyConditionalAttributeSymbols, conditionalSymbols, default(ImmutableArray<string>)); } return uncommon.lazyConditionalAttributeSymbols; } internal override ObsoleteAttributeData ObsoleteAttributeData { get { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return null; } bool ignoreByRefLikeMarker = this.IsRefLikeType; ObsoleteAttributeHelpers.InitializeObsoleteDataFromMetadata(ref uncommon.lazyObsoleteAttributeData, _handle, ContainingPEModule, ignoreByRefLikeMarker); return uncommon.lazyObsoleteAttributeData; } } internal override AttributeUsageInfo GetAttributeUsageInfo() { var uncommon = GetUncommonProperties(); if (uncommon == s_noUncommonProperties) { return ((object)this.BaseTypeNoUseSiteDiagnostics != null) ? this.BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo() : AttributeUsageInfo.Default; } if (uncommon.lazyAttributeUsageInfo.IsNull) { uncommon.lazyAttributeUsageInfo = this.DecodeAttributeUsageInfo(); } return uncommon.lazyAttributeUsageInfo; } private AttributeUsageInfo DecodeAttributeUsageInfo() { var handle = this.ContainingPEModule.Module.GetAttributeUsageAttributeHandle(_handle); if (!handle.IsNil) { var decoder = new MetadataDecoder(ContainingPEModule); TypedConstant[] positionalArgs; KeyValuePair<string, TypedConstant>[] namedArgs; if (decoder.GetCustomAttribute(handle, out positionalArgs, out namedArgs)) { AttributeUsageInfo info = AttributeData.DecodeAttributeUsageAttribute(positionalArgs[0], namedArgs.AsImmutableOrNull()); return info.HasValidAttributeTargets ? info : AttributeUsageInfo.Default; } } return ((object)this.BaseTypeNoUseSiteDiagnostics != null) ? this.BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo() : AttributeUsageInfo.Default; } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } /// <summary> /// Returns the index of the first member of the specific kind. /// Returns the number of members if not found. /// </summary> private static int GetIndexOfFirstMember(ImmutableArray<Symbol> members, SymbolKind kind) { int n = members.Length; for (int i = 0; i < n; i++) { if (members[i].Kind == kind) { return i; } } return n; } /// <summary> /// Returns all members of the specific kind, starting at the optional offset. /// Members of the same kind are assumed to be contiguous. /// </summary> private static IEnumerable<TSymbol> GetMembers<TSymbol>(ImmutableArray<Symbol> members, SymbolKind kind, int offset = -1) where TSymbol : Symbol { if (offset < 0) { offset = GetIndexOfFirstMember(members, kind); } int n = members.Length; for (int i = offset; i < n; i++) { var member = members[i]; if (member.Kind != kind) { yield break; } yield return (TSymbol)member; } } internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } /// <summary> /// Specialized PENamedTypeSymbol for types with no type parameters in /// metadata (no type parameters on this type and all containing types). /// </summary> private sealed class PENamedTypeSymbolNonGeneric : PENamedTypeSymbol { internal PENamedTypeSymbolNonGeneric( PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, out bool mangleName) : base(moduleSymbol, container, handle, emittedNamespaceName, 0, out mangleName) { } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; public override int Arity { get { return 0; } } internal override bool MangleName { get { return false; } } internal override int MetadataArity { get { var containingType = _container as PENamedTypeSymbol; return (object)containingType == null ? 0 : containingType.MetadataArity; } } internal override NamedTypeSymbol AsNativeInteger() { Debug.Assert(this.SpecialType == SpecialType.System_IntPtr || this.SpecialType == SpecialType.System_UIntPtr); return ContainingAssembly.GetNativeIntegerType(this); } internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return t2 is NativeIntegerTypeSymbol nativeInteger ? nativeInteger.Equals(this, comparison) : base.Equals(t2, comparison); } } /// <summary> /// Specialized PENamedTypeSymbol for types with type parameters in metadata. /// NOTE: the type may have Arity == 0 if it has same metadata arity as the metadata arity of the containing type. /// </summary> private sealed class PENamedTypeSymbolGeneric : PENamedTypeSymbol { private readonly GenericParameterHandleCollection _genericParameterHandles; private readonly ushort _arity; private readonly bool _mangleName; private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; internal PENamedTypeSymbolGeneric( PEModuleSymbol moduleSymbol, NamespaceOrTypeSymbol container, TypeDefinitionHandle handle, string emittedNamespaceName, GenericParameterHandleCollection genericParameterHandles, ushort arity, out bool mangleName ) : base(moduleSymbol, container, handle, emittedNamespaceName, arity, out mangleName) { Debug.Assert(genericParameterHandles.Count > 0); _arity = arity; _genericParameterHandles = genericParameterHandles; _mangleName = mangleName; } protected sealed override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; public override int Arity { get { return _arity; } } internal override bool MangleName { get { return _mangleName; } } internal override int MetadataArity { get { return _genericParameterHandles.Count; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { // This is always the instance type, so the type arguments are the same as the type parameters. return GetTypeParametersAsTypeArguments(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { EnsureTypeParametersAreLoaded(); return _lazyTypeParameters; } } internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; private void EnsureTypeParametersAreLoaded() { if (_lazyTypeParameters.IsDefault) { var moduleSymbol = ContainingPEModule; // If this is a nested type generic parameters in metadata include generic parameters of the outer types. int firstIndex = _genericParameterHandles.Count - _arity; TypeParameterSymbol[] ownedParams = new TypeParameterSymbol[_arity]; for (int i = 0; i < ownedParams.Length; i++) { ownedParams[i] = new PETypeParameterSymbol(moduleSymbol, this, (ushort)i, _genericParameterHandles[firstIndex + i]); } ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameters, ImmutableArray.Create<TypeParameterSymbol>(ownedParams)); } } protected override DiagnosticInfo GetUseSiteDiagnosticImpl() { DiagnosticInfo diagnostic = null; if (!MergeUseSiteDiagnostics(ref diagnostic, base.GetUseSiteDiagnosticImpl())) { // Verify type parameters for containing types // match those on the containing types. if (!MatchesContainingTypeParameters()) { diagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this); } } return diagnostic; } /// <summary> /// Return true if the type parameters specified on the nested type (this), /// that represent the corresponding type parameters on the containing /// types, in fact match the actual type parameters on the containing types. /// </summary> private bool MatchesContainingTypeParameters() { var container = this.ContainingType; if ((object)container == null) { return true; } var containingTypeParameters = container.GetAllTypeParameters(); int n = containingTypeParameters.Length; if (n == 0) { return true; } // Create an instance of PENamedTypeSymbol for the nested type, but // with all type parameters, from the nested type and all containing // types. The type parameters on this temporary type instance are used // for comparison with those on the actual containing types. The // containing symbol for the temporary type is the namespace directly. var nestedType = Create(this.ContainingPEModule, (PENamespaceSymbol)this.ContainingNamespace, _handle, null); var nestedTypeParameters = nestedType.TypeParameters; var containingTypeMap = new TypeMap(containingTypeParameters, IndexedTypeParameterSymbol.Take(n), allowAlpha: false); var nestedTypeMap = new TypeMap(nestedTypeParameters, IndexedTypeParameterSymbol.Take(nestedTypeParameters.Length), allowAlpha: false); for (int i = 0; i < n; i++) { var containingTypeParameter = containingTypeParameters[i]; var nestedTypeParameter = nestedTypeParameters[i]; if (!MemberSignatureComparer.HaveSameConstraints(containingTypeParameter, containingTypeMap, nestedTypeParameter, nestedTypeMap)) { return false; } } return true; } } } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.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.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type symbol whose members are declared in source. /// </summary> internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol { // The flags type is used to compact many different bits of information efficiently. private struct Flags { // We current pack everything into one 32-bit int; layout is given below. // // | |vvv|zzzz|f|d|yy|wwwwww| // // w = special type. 6 bits. // y = IsManagedType. 2 bits. // d = FieldDefinitionsNoted. 1 bit // f = FlattenedMembersIsSorted. 1 bit. // z = TypeKind. 4 bits. // v = NullableContext. 3 bits. private int _flags; private const int SpecialTypeOffset = 0; private const int SpecialTypeSize = 6; private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize; private const int ManagedKindSize = 2; private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize; private const int FieldDefinitionsNotedSize = 1; private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize; private const int FlattenedMembersIsSortedSize = 1; private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize; private const int TypeKindSize = 4; private const int NullableContextOffset = TypeKindOffset + TypeKindSize; private const int NullableContextSize = 3; private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1; private const int ManagedKindMask = (1 << ManagedKindSize) - 1; private const int TypeKindMask = (1 << TypeKindSize) - 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset; private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset; public SpecialType SpecialType { get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); } } public ManagedKind ManagedKind { get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); } } public bool FieldDefinitionsNoted { get { return (_flags & FieldDefinitionsNotedBit) != 0; } } // True if "lazyMembersFlattened" is sorted. public bool FlattenedMembersIsSorted { get { return (_flags & FlattenedMembersIsSortedBit) != 0; } } public TypeKind TypeKind { get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif public Flags(SpecialType specialType, TypeKind typeKind) { int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset; int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset; _flags = specialTypeInt | typeKindInt; } public void SetFieldDefinitionsNoted() { ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit); } public void SetFlattenedMembersIsSorted() { ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit)); } private static bool BitsAreUnsetOrSame(int bits, int mask) { return (bits & mask) == 0 || (bits & mask) == mask; } public void SetManagedKind(ManagedKind managedKind) { int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset; Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet)); ThreadSafeFlagOperations.Set(ref _flags, bitsToSet); } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary = PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer); protected SymbolCompletionState state; private Flags _flags; private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics; private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies; private readonly DeclarationModifiers _declModifiers; private readonly NamespaceOrTypeSymbol _containingSymbol; protected readonly MergedTypeDeclaration declaration; // The entry point symbol (resulting from top-level statements) is needed to construct non-type members because // it contributes to their binders, so we have to compute it first. // The value changes from "default" to "real value". The transition from "default" can only happen once. private ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> _lazySimpleProgramEntryPoints; // To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set) // The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once. private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel; private MembersAndInitializers? _lazyMembersAndInitializers; private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary; private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary; private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance); private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers; private ImmutableArray<Symbol> _lazyMembersFlattened; private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations; private int _lazyKnownCircularStruct; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; private ThreeState _lazyContainsExtensionMethods; private ThreeState _lazyAnyMemberHasAttributes; #region Construction internal SourceMemberContainerTypeSymbol( NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData? tupleData = null) : base(tupleData) { // If we're dealing with a simple program, then we must be in the global namespace Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram)); _containingSymbol = containingSymbol; this.declaration = declaration; TypeKind typeKind = declaration.Kind.ToTypeKind(); var modifiers = MakeModifiers(typeKind, diagnostics); foreach (var singleDeclaration in declaration.Declarations) { diagnostics.AddRange(singleDeclaration.Diagnostics); } int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask); if ((access & (access - 1)) != 0) { // more than one access modifier if ((modifiers & DeclarationModifiers.Partial) != 0) diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this); access = access & ~(access - 1); // narrow down to one access modifier modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all modifiers |= (DeclarationModifiers)access; // except the one } _declModifiers = modifiers; var specialType = access == (int)DeclarationModifiers.Public ? MakeSpecialType() : SpecialType.None; _flags = new Flags(specialType, typeKind); var containingType = this.ContainingType; if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected()) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this); } state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately } private SpecialType MakeSpecialType() { // check if this is one of the COR library types if (ContainingSymbol.Kind == SymbolKind.Namespace && ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) { //for a namespace, the emitted name is a dot-separated list of containing namespaces var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName); return SpecialTypes.GetTypeFromMetadataName(emittedName); } else { return SpecialType.None; } } private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics) { Symbol containingSymbol = this.ContainingSymbol; DeclarationModifiers defaultAccess; var allowedModifiers = DeclarationModifiers.AccessibilityMask; if (containingSymbol.Kind == SymbolKind.Namespace) { defaultAccess = DeclarationModifiers.Internal; } else { allowedModifiers |= DeclarationModifiers.New; if (((NamedTypeSymbol)containingSymbol).IsInterface) { defaultAccess = DeclarationModifiers.Public; } else { defaultAccess = DeclarationModifiers.Private; } } switch (typeKind) { case TypeKind.Class: case TypeKind.Submission: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Unsafe; if (!this.IsRecord) { allowedModifiers |= DeclarationModifiers.Static; } break; case TypeKind.Struct: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe; if (!this.IsRecordStruct) { allowedModifiers |= DeclarationModifiers.Ref; } break; case TypeKind.Interface: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; break; case TypeKind.Delegate: allowedModifiers |= DeclarationModifiers.Unsafe; break; } bool modifierErrors; var mods = MakeAndCheckTypeModifiers( defaultAccess, allowedModifiers, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); if (!modifierErrors && (mods & DeclarationModifiers.Abstract) != 0 && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this); } if (!modifierErrors && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) { diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this); } switch (typeKind) { case TypeKind.Interface: mods |= DeclarationModifiers.Abstract; break; case TypeKind.Struct: case TypeKind.Enum: mods |= DeclarationModifiers.Sealed; break; case TypeKind.Delegate: mods |= DeclarationModifiers.Sealed; break; } return mods; } private DeclarationModifiers MakeAndCheckTypeModifiers( DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { modifierErrors = false; var result = DeclarationModifiers.Unset; var partCount = declaration.Declarations.Length; var missingPartial = false; for (var i = 0; i < partCount; i++) { var decl = declaration.Declarations[i]; var mods = decl.Modifiers; if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0) { missingPartial = true; } if (!modifierErrors) { mods = ModifierUtils.CheckModifiers( mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics, modifierTokens: null, modifierErrors: out modifierErrors); // It is an error for the same modifier to appear multiple times. if (!modifierErrors) { var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, this.Locations[0]); modifierErrors = true; } } } if (result == DeclarationModifiers.Unset) { result = mods; } else { result |= mods; } } if ((result & DeclarationModifiers.AccessibilityMask) == 0) { result |= defaultAccess; } if (missingPartial) { if ((result & DeclarationModifiers.Partial) == 0) { // duplicate definitions switch (this.ContainingSymbol.Kind) { case SymbolKind.Namespace: for (var i = 1; i < partCount; i++) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol); modifierErrors = true; } break; case SymbolKind.NamedType: for (var i = 1; i < partCount; i++) { if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial()) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name); modifierErrors = true; } break; } } else { for (var i = 0; i < partCount; i++) { var singleDeclaration = declaration.Declarations[i]; var mods = singleDeclaration.Modifiers; if ((mods & DeclarationModifiers.Partial) == 0) { diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name); modifierErrors = true; } } } } if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword)) { foreach (var syntaxRef in SyntaxReferences) { SyntaxToken? identifier = syntaxRef.GetSyntax() switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => null }; ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None); } } return result; } internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location) { if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) && compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion()) { diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name); } } #endregion #region Completion internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } protected abstract void CheckBase(BindingDiagnosticBag diagnostics); protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics); internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) { while (true) { // NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers. cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartBaseType: case CompletionPart.FinishBaseType: if (state.NotePartComplete(CompletionPart.StartBaseType)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckBase(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishBaseType); diagnostics.Free(); } break; case CompletionPart.StartInterfaces: case CompletionPart.FinishInterfaces: if (state.NotePartComplete(CompletionPart.StartInterfaces)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckInterfaces(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishInterfaces); diagnostics.Free(); } break; case CompletionPart.EnumUnderlyingType: var discarded = this.EnumUnderlyingType; break; case CompletionPart.TypeArguments: { var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments } break; case CompletionPart.TypeParameters: // force type parameters foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.Members: this.GetMembersByName(); break; case CompletionPart.TypeMembers: this.GetTypeMembersUnordered(); break; case CompletionPart.SynthesizedExplicitImplementations: this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked break; case CompletionPart.StartMemberChecks: case CompletionPart.FinishMemberChecks: if (state.NotePartComplete(CompletionPart.StartMemberChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); AfterMembersChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); // We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.MembersCompleted: { ImmutableArray<Symbol> members = this.GetMembersUnordered(); bool allCompleted = true; if (locationOpt == null) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (!allCompleted) { // We did not complete all members so we won't have enough information for // the PointedAtManagedTypeChecks, so just kick out now. var allParts = CompletionPart.NamedTypeSymbolWithLocationAll; state.SpinWaitComplete(allParts, cancellationToken); return; } EnsureFieldDefinitionsNoted(); // We've completed all members, so we're ready for the PointedAtManagedTypeChecks; // proceed to the next iteration. state.NotePartComplete(CompletionPart.MembersCompleted); break; } case CompletionPart.None: return; default: // This assert will trigger if we forgot to handle any of the completion parts Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0); // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } throw ExceptionUtilities.Unreachable; } internal void EnsureFieldDefinitionsNoted() { if (_flags.FieldDefinitionsNoted) { return; } NoteFieldDefinitions(); } private void NoteFieldDefinitions() { // we must note all fields once therefore we need to lock var membersAndInitializers = this.GetMembersAndInitializers(); lock (membersAndInitializers) { if (!_flags.FieldDefinitionsNoted) { var assembly = (SourceAssemblySymbol)ContainingAssembly; Accessibility containerEffectiveAccessibility = EffectiveAccessibility(); foreach (var member in membersAndInitializers.NonTypeMembers) { FieldSymbol field; if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer) { continue; } Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility; if (fieldDeclaredAccessibility == Accessibility.Private) { // mark private fields as tentatively unassigned and unread unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true); } else if (containerEffectiveAccessibility == Accessibility.Private) { // mark effectively private fields as tentatively unassigned unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false); } else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal) { // mark effectively internal fields as tentatively unassigned unless we discover otherwise. // NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly. // See property SourceAssemblySymbol.UnusedFieldWarnings. assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false); } } _flags.SetFieldDefinitionsNoted(); } } } #endregion #region Containers public sealed override NamedTypeSymbol? ContainingType { get { return _containingSymbol as NamedTypeSymbol; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } #endregion #region Flags Encoded Properties public override SpecialType SpecialType { get { return _flags.SpecialType; } } public override TypeKind TypeKind { get { return _flags.TypeKind; } } internal MergedTypeDeclaration MergedDeclaration { get { return this.declaration; } } internal sealed override bool IsInterface { get { // TypeKind is computed eagerly, so this is cheap. return this.TypeKind == TypeKind.Interface; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var managedKind = _flags.ManagedKind; if (managedKind == ManagedKind.Unknown) { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly); managedKind = base.GetManagedKind(ref managedKindUseSiteInfo); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty); _flags.SetManagedKind(managedKind); } if (useSiteInfo.AccumulatesDiagnostics) { ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics; // Ensure we have the latest value from the field useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics); Debug.Assert(!useSiteDiagnostics.IsDefault); useSiteInfo.AddDiagnostics(useSiteDiagnostics); } if (useSiteInfo.AccumulatesDependencies) { ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies; // Ensure we have the latest value from the field useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies); Debug.Assert(!useSiteDependencies.IsDefault); useSiteInfo.AddDependencies(useSiteDependencies); } return managedKind; } public override bool IsStatic => HasFlag(DeclarationModifiers.Static); public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref); public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly); public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed); public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract); internal bool IsPartial => HasFlag(DeclarationModifiers.Partial); internal bool IsNew => HasFlag(DeclarationModifiers.New); [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0; public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_declModifiers); } } /// <summary> /// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields. /// </summary> private Accessibility EffectiveAccessibility() { var result = DeclaredAccessibility; if (result == Accessibility.Private) return Accessibility.Private; for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType) { switch (container.DeclaredAccessibility) { case Accessibility.Private: return Accessibility.Private; case Accessibility.Internal: result = Accessibility.Internal; continue; } } return result; } #endregion #region Syntax public override bool IsScriptClass { get { var kind = this.declaration.Declarations[0].Kind; return kind == DeclarationKind.Script || kind == DeclarationKind.Submission; } } public override bool IsImplicitClass { get { return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass; } } internal override bool IsRecord { get { return this.declaration.Declarations[0].Kind == DeclarationKind.Record; } } internal override bool IsRecordStruct { get { return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct; } } public override bool IsImplicitlyDeclared { get { return IsImplicitClass || IsScriptClass; } } public override int Arity { get { return declaration.Arity; } } public override string Name { get { return declaration.Name; } } internal override bool MangleName { get { return Arity > 0; } } internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public sealed override ImmutableArray<Location> Locations { get { return declaration.NameLocations.Cast<SourceLocation, Location>(); } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return this.declaration.SyntaxReferences; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return SyntaxReferences; } } // This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { var declarations = declaration.Declarations; if (IsImplicitlyDeclared && declarations.IsEmpty) { return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var syntaxRef = declaration.SyntaxReference; if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } #endregion #region Members /// <summary> /// Encapsulates information about the non-type members of a (i.e. this) type. /// 1) For non-initializers, symbols are created and stored in a list. /// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are /// stored with other initialized fields and properties from the same syntax tree with /// the same static-ness. /// </summary> protected sealed class MembersAndInitializers { internal readonly ImmutableArray<Symbol> NonTypeMembers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; internal readonly bool HaveIndexers; internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields; internal readonly bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields) { Debug.Assert(!nonTypeMembers.IsDefault); Debug.Assert(!staticInitializers.IsDefault); Debug.Assert(staticInitializers.All(g => !g.IsDefault)); Debug.Assert(!instanceInitializers.IsDefault); Debug.Assert(instanceInitializers.All(g => !g.IsDefault)); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer())); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers { get { return GetMembersAndInitializers().StaticInitializers; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers { get { return GetMembersAndInitializers().InstanceInitializers; } } internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic) { if (IsScriptClass && !isStatic) { int aggregateLength = 0; foreach (var declaration in this.declaration.Declarations) { var syntaxRef = declaration.SyntaxReference; if (tree == syntaxRef.SyntaxTree) { return aggregateLength + position; } aggregateLength += syntaxRef.Span.Length; } throw ExceptionUtilities.Unreachable; } int syntaxOffset; if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset)) { return syntaxOffset; } if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start) { // With dynamic analysis instrumentation, the introducing declaration of a type can provide // the syntax associated with both the analysis payload local of a synthesized constructor // and with the constructor itself. If the synthesized constructor includes an initializer with a lambda, // that lambda needs a closure that captures the analysis payload of the constructor, // and the offset of the syntax for the local within the constructor is by definition zero. return 0; } // an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer throw ExceptionUtilities.Unreachable; } /// <summary> /// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one). /// </summary> internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset) { Debug.Assert(ctorInitializerLength >= 0); var membersAndInitializers = GetMembersAndInitializers(); var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers; if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength)) { syntaxOffset = 0; return false; } // |<-----------distanceFromCtorBody----------->| // [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body] // |<--preceding init len-->| ^ // position int initializersLength = getInitializersLength(allInitializers); int distanceFromInitializerStart = position - initializer.Syntax.Span.Start; int distanceFromCtorBody = initializersLength + ctorInitializerLength - (precedingLength + distanceFromInitializerStart); Debug.Assert(distanceFromCtorBody > 0); // syntax offset 0 is at the start of the ctor body: syntaxOffset = -distanceFromCtorBody; return true; static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree, out FieldOrPropertyInitializer found, out int precedingLength) { precedingLength = 0; foreach (var group in initializers) { if (!group.IsEmpty && group[0].Syntax.SyntaxTree == tree && position < group.Last().Syntax.Span.End) { // Found group of interest var initializerIndex = IndexOfInitializerContainingPosition(group, position); if (initializerIndex < 0) { break; } precedingLength += getPrecedingInitializersLength(group, initializerIndex); found = group[initializerIndex]; return true; } precedingLength += getGroupLength(group); } found = default; return false; } static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers) { int length = 0; foreach (var initializer in initializers) { length += getInitializerLength(initializer); } return length; } static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index) { int length = 0; for (var i = 0; i < index; i++) { length += getInitializerLength(initializers[i]); } return length; } static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { int length = 0; foreach (var group in initializers) { length += getGroupLength(group); } return length; } static int getInitializerLength(FieldOrPropertyInitializer initializer) { // A constant field of type decimal needs a field initializer, so // check if it is a metadata constant, not just a constant to exclude // decimals. Other constants do not need field initializers. if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant) { // ignore leading and trailing trivia of the node: return initializer.Syntax.Span.Length; } return 0; } } private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position) { // Search for the start of the span (the spans are non-overlapping and sorted) int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos)); // Binary search returns non-negative result if the position is exactly the start of some span. if (index >= 0) { return index; } // Otherwise, ~index is the closest span whose start is greater than the position. // => Check if the preceding initializer span contains the position. int precedingInitializerIndex = ~index - 1; if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position)) { return precedingInitializerIndex; } return -1; } public override IEnumerable<string> MemberNames { get { return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembersDictionary().Flatten(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; if (GetTypeMembersDictionary().TryGetValue(name, out members)) { return members; } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary() { if (_lazyTypeMembers == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.TypeMembers); } diagnostics.Free(); } return _lazyTypeMembers; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>(); try { foreach (var childDeclaration in declaration.Children) { var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics); this.CheckMemberNameDistinctFromType(t, diagnostics); var key = (t.Name, t.Arity); SourceNamedTypeSymbol? other; if (conflictDict.TryGetValue(key, out other)) { if (Locations.Length == 1 || IsPartial) { if (t.IsPartial && other.IsPartial) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name); } } } else { conflictDict.Add(key, t); } symbols.Add(t); } if (IsInterface) { foreach (var t in symbols) { Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]); } } Debug.Assert(s_emptyTypeMembers.Count == 0); return symbols.Count > 0 ? symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) : s_emptyTypeMembers; } finally { symbols.Free(); } } private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics) { switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: if (member.Name == this.Name) { diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name); } break; case TypeKind.Interface: if (member.IsStatic) { goto case TypeKind.Class; } break; } } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyMembersFlattened; if (result.IsDefault) { result = GetMembersByName().Flatten(null); // do not sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result); result = _lazyMembersFlattened; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if (_flags.FlattenedMembersIsSorted) { return _lazyMembersFlattened; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length > 1) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers); } _flags.SetFlattenedMembersIsSorted(); return allMembers; } } public sealed override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<Symbol> members; if (GetMembersByName().TryGetValue(name, out members)) { return members; } return ImmutableArray<Symbol>.Empty; } /// <remarks> /// For source symbols, there can only be a valid clone method if this is a record, which is a /// simple syntax check. This will need to change when we generalize cloning, but it's a good /// heuristic for now. /// </remarks> internal override bool HasPossibleWellKnownCloneMethod() => IsRecord; internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct) { return GetMembers(name); } return ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { // For consistency with Dev10, emit value__ field first. var valueField = ((SourceNamedTypeSymbol)this).EnumValueField; RoslynDebug.Assert((object)valueField != null); yield return valueField; } foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: if (m is TupleErrorFieldSymbol) { break; } yield return (FieldSymbol)m; break; case SymbolKind.Event: FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField; if ((object?)associatedField != null) { yield return associatedField; } break; } } } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return GetEarlyAttributeDecodingMembersDictionary().Flatten(); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { ImmutableArray<Symbol> result; return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty; } private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary() { if (_lazyEarlyAttributeDecodingMembersDictionary == null) { if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result) { return result; } var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached // NOTE: members were added in a single pass over the syntax, so they're already // in lexical order. Dictionary<string, ImmutableArray<Symbol>> membersByName; if (!membersAndInitializers.HaveIndexers) { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name); } else { // We can't include indexer symbol yet, because we don't know // what name it will have after attribute binding (because of // IndexerNameAttribute). membersByName = membersAndInitializers.NonTypeMembers. WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)). ToDictionary(s => s.Name); } AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null); } return _lazyEarlyAttributeDecodingMembersDictionary; } // NOTE: this method should do as little work as possible // we often need to get members just to do a lookup. // All additional checks and diagnostics may be not // needed yet or at all. protected MembersAndInitializers GetMembersAndInitializers() { var membersAndInitializers = _lazyMembersAndInitializers; if (membersAndInitializers != null) { return membersAndInitializers; } var diagnostics = BindingDiagnosticBag.GetInstance(); membersAndInitializers = BuildMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null); if (alreadyKnown != null) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); _lazyDeclaredMembersAndInitializers = null; return membersAndInitializers!; } /// <summary> /// The purpose of this function is to assert that the <paramref name="member"/> symbol /// is actually among the symbols cached by this type symbol in a way that ensures /// that any consumer of standard APIs to get to type's members is going to get the same /// symbol (same instance) for the member rather than an equivalent, but different instance. /// </summary> [Conditional("DEBUG")] internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false) { if (member is FieldSymbol && forDiagnostics && this.IsTupleType) { // There is a problem with binding types of fields in tuple types. // Skipping verification for them temporarily. return; } if (member is NamedTypeSymbol type) { RoslynDebug.AssertOrFailFast(forDiagnostics); RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true); return; } else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol) { RoslynDebug.AssertOrFailFast(forDiagnostics); return; } else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e) { RoslynDebug.AssertOrFailFast(forDiagnostics); // Backing fields for field-like events are not added to the members list. member = e; } var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } if (membersAndInitializers is null) { if (member is SynthesizedSimpleProgramEntryPointSymbol) { RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member)); return; } var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers); RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel); if (declared is object) { if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member) { return; } } else { // It looks like there was a race and we need to check _lazyMembersAndInitializers again membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); RoslynDebug.AssertOrFailFast(membersAndInitializers is object); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } } } RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure."); static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member) { return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true; } } protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName() { if (this.state.HasComplete(CompletionPart.Members)) { return _lazyMembersDictionary!; } return GetMembersByNameSlow(); } private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow() { if (_lazyMembersDictionary == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var membersDictionary = MakeAllMembers(diagnostics); if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.Members); } diagnostics.Free(); } state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken)); return _lazyMembersDictionary; } internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents() { var membersAndInitializers = this.GetMembersAndInitializers(); return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent); } protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) { if (IsInterface) { CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics); } CheckMemberNamesDistinctFromType(diagnostics); CheckMemberNameConflicts(diagnostics); CheckRecordMemberNames(diagnostics); CheckSpecialMemberErrors(diagnostics); CheckTypeParameterNameConflicts(diagnostics); CheckAccessorNameConflicts(diagnostics); bool unused = KnownCircularStruct; CheckSequentialOnPartialType(diagnostics); CheckForProtectedInStaticClass(diagnostics); CheckForUnmatchedOperators(diagnostics); var location = Locations[0]; var compilation = DeclaringCompilation; if (this.IsRefLikeType) { compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true); } if (this.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } var baseType = BaseTypeNoUseSiteDiagnostics; var interfaces = GetInterfacesToEmit(); // https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations. if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger())) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute())) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } } if (interfaces.Any(t => needsTupleElementNamesAttribute(t))) { // Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding) // so the checking of all interfaces here involves some redundancy. Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics); } bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate) { return ((object)baseType != null && predicate(baseType)) || interfaces.Any(predicate); } static bool needsTupleElementNamesAttribute(TypeSymbol type) { if (type is null) { return false; } var resultType = type.VisitType( predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(), arg: (object?)null); return resultType is object; } } private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics) { foreach (var member in GetMembersAndInitializers().NonTypeMembers) { CheckMemberNameDistinctFromType(member, diagnostics); } } private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics) { if (declaration.Kind != DeclarationKind.Record && declaration.Kind != DeclarationKind.RecordStruct) { return; } foreach (var member in GetMembers("Clone")) { diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]); } } private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName(); // Collisions involving indexers are handled specially. CheckIndexerNameConflicts(diagnostics, membersByName); // key and value will be the same object in these dictionaries. var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer); // SPEC: The signature of an operator must differ from the signatures of all other // SPEC: operators declared in the same class. // DELIBERATE SPEC VIOLATION: // The specification does not state that a user-defined conversion reserves the names // op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt // to define a field or a conflicting method with the metadata name of a user-defined // conversion is an error. We preserve this reasonable behavior. // // Similarly, we treat "public static C operator +(C, C)" as colliding with // "public static C op_Addition(C, C)". Fortunately, this behavior simply // falls out of treating user-defined operators as ordinary methods; we do // not need any special handling in this method. // // However, we must have special handling for conversions because conversions // use a completely different rule for detecting collisions between two // conversions: conversion signatures consist only of the source and target // types of the conversions, and not the kind of the conversion (implicit or explicit), // the name of the method, and so on. // // Therefore we must detect the following kinds of member name conflicts: // // 1. a method, conversion or field has the same name as a (different) field (* see note below) // 2. a method has the same method signature as another method or conversion // 3. a conversion has the same conversion signature as another conversion. // // However, we must *not* detect "a conversion has the same *method* signature // as another conversion" because conversions are allowed to overload on // return type but methods are not. // // (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for // "non-method, non-conversion, non-type member", rather than spelling out // "field, property or event...") foreach (var pair in membersByName) { var name = pair.Key; Symbol? lastSym = GetTypeMembers(name).FirstOrDefault(); methodsBySignature.Clear(); // Conversion collisions do not consider the name of the conversion, // so do not clear that dictionary. foreach (var symbol in pair.Value) { if (symbol.Kind == SymbolKind.NamedType || symbol.IsAccessor() || symbol.IsIndexer()) { continue; } // We detect the first category of conflict by running down the list of members // of the same name, and producing an error when we discover any of the following // "bad transitions". // // * a method or conversion that comes after any field (not necessarily directly) // * a field directly following a field // * a field directly following a method or conversion // // Furthermore: we do not wish to detect collisions between nested types in // this code; that is tested elsewhere. However, we do wish to detect a collision // between a nested type and a field, method or conversion. Therefore we // initialize our "bad transition" detector with a type of the given name, // if there is one. That way we also detect the transitions of "method following // type", and so on. // // The "lastSym" local below is used to detect these transitions. Its value is // one of the following: // // * a nested type of the given name, or // * the first method of the given name, or // * the most recently processed field of the given name. // // If either the current symbol or the "last symbol" are not methods then // there must be a collision: // // * if the current symbol is not a method and the last symbol is, then // there is a field directly following a method of the same name // * if the current symbol is a method and the last symbol is not, then // there is a method directly or indirectly following a field of the same name, // or a method of the same name as a nested type. // * if neither are methods then either we have a field directly // following a field of the same name, or a field and a nested type of the same name. // if (lastSym is object) { if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method) { if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name); } } if (lastSym.Kind == SymbolKind.Method) { lastSym = symbol; } } } else { lastSym = symbol; } // That takes care of the first category of conflict; we detect the // second and third categories as follows: var conversion = symbol as SourceUserDefinedConversionSymbol; var method = symbol as SourceMemberMethodSymbol; if (!(conversion is null)) { // Does this conversion collide *as a conversion* with any previously-seen // conversion? if (!conversionsAsConversions.Add(conversion)) { // CS0557: Duplicate user-defined conversion in type 'C' diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this); } else { // The other set might already contain a conversion which would collide // *as a method* with the current conversion. if (!conversionsAsMethods.ContainsKey(conversion)) { conversionsAsMethods.Add(conversion, conversion); } } // Does this conversion collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(conversion, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, conversion, previousMethod); } // Do not add the conversion to the set of previously-seen methods; that set // is only non-conversion methods. } else if (!(method is null)) { // Does this method collide *as a method* with any previously-seen // conversion? if (conversionsAsMethods.TryGetValue(method, out var previousConversion)) { ReportMethodSignatureCollision(diagnostics, method, previousConversion); } // Do not add the method to the set of previously-seen conversions. // Does this method collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(method, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, method, previousMethod); } else { // We haven't seen this method before. Make a note of it in case // we see a colliding method later. methodsBySignature.Add(method, method); } } } } } // Report a name conflict; the error is reported on the location of method1. // UNDONE: Consider adding a secondary location pointing to the second method. private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2) { switch (method1, method2) { case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }): case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }): // these could be 2 parts of the same partial method. // Partial methods are allowed to collide by signature. return; case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }): return; } // If method1 is a constructor only because its return type is missing, then // we've already produced a diagnostic for the missing return type and we suppress the // diagnostic about duplicate signature. if (method1.MethodKind == MethodKind.Constructor && ((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name) { return; } Debug.Assert(method1.ParameterCount == method2.ParameterCount); for (int i = 0; i < method1.ParameterCount; i++) { var refKind1 = method1.Parameters[i].RefKind; var refKind2 = method2.Parameters[i].RefKind; if (refKind1 != refKind2) { // '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}' var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD; diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString()); return; } } // Special case: if there are two destructors, use the destructor syntax instead of "Finalize" var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ? "~" + this.Name : (method1.IsConstructor() ? this.Name : method1.Name); // Type '{1}' already defines a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this); } private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName) { PooledHashSet<string>? typeParameterNames = null; if (this.Arity > 0) { typeParameterNames = PooledHashSet<string>.GetInstance(); foreach (TypeParameterSymbol typeParameter in this.TypeParameters) { typeParameterNames.Add(typeParameter.Name); } } var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer); // Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because // they may be explicit interface implementations. foreach (var members in membersByName.Values) { string? lastIndexerName = null; indexersBySignature.Clear(); foreach (var symbol in members) { if (symbol.IsIndexer()) { PropertySymbol indexer = (PropertySymbol)symbol; CheckIndexerSignatureCollisions( indexer, diagnostics, membersByName, indexersBySignature, ref lastIndexerName); // Also check for collisions with type parameters, which aren't in the member map. // NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts. if (typeParameterNames != null) { string indexerName = indexer.MetadataName; if (typeParameterNames.Contains(indexerName)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); continue; } } } } } typeParameterNames?.Free(); } private void CheckIndexerSignatureCollisions( PropertySymbol indexer, BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<PropertySymbol, PropertySymbol> indexersBySignature, ref string? lastIndexerName) { if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked { string indexerName = indexer.MetadataName; if (lastIndexerName != null && lastIndexerName != indexerName) { // NOTE: dev10 checks indexer names by comparing each to the previous. // For example, if indexers are declared with names A, B, A, B, then there // will be three errors - one for each time the name is different from the // previous one. If, on the other hand, the names are A, A, B, B, then // there will only be one error because only one indexer has a different // name from the previous one. diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]); } lastIndexerName = indexerName; if (Locations.Length == 1 || IsPartial) { if (membersByName.ContainsKey(indexerName)) { // The name of the indexer is reserved - it can only be used by other indexers. Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer)); diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); } } } if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature)) { // Type '{1}' already defines a member called '{0}' with the same parameter types // NOTE: Dev10 prints "this" as the name of the indexer. diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this); } else { indexersBySignature[indexer] = indexer; } } private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics) { var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary); foreach (var member in this.GetMembersUnordered()) { member.AfterAddingTypeMembersChecks(conversions, diagnostics); } } private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics) { if (this.TypeKind == TypeKind.Delegate) { // Delegates do not have conflicts between their type parameter // names and their methods; it is legal (though odd) to say // delegate void D<Invoke>(Invoke x); return; } if (Locations.Length == 1 || IsPartial) { foreach (var tp in TypeParameters) { foreach (var dup in GetMembers(tp.Name)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name); } } } } private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics) { // Report errors where property and event accessors // conflict with other members of the same name. foreach (Symbol symbol in this.GetMembersUnordered()) { if (symbol.IsExplicitInterfaceImplementation()) { // If there's a name conflict it will show up as a more specific // interface implementation error. continue; } switch (symbol.Kind) { case SymbolKind.Property: { var propertySymbol = (PropertySymbol)symbol; this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics); this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics); break; } case SymbolKind.Event: { var eventSymbol = (EventSymbol)symbol; this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics); this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics); break; } } } } internal override bool KnownCircularStruct { get { if (_lazyKnownCircularStruct == (int)ThreeState.Unknown) { if (TypeKind != TypeKind.Struct) { Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); var value = (int)CheckStructCircularity(diagnostics).ToThreeState(); if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown) { AddDeclarationDiagnostics(diagnostics); } Debug.Assert(value == _lazyKnownCircularStruct); diagnostics.Free(); } } return _lazyKnownCircularStruct == (int)ThreeState.True; } } private bool CheckStructCircularity(BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); CheckFiniteFlatteningGraph(diagnostics); return HasStructCircularity(diagnostics); } private bool HasStructCircularity(BindingDiagnosticBag diagnostics) { foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member.Kind != SymbolKind.Field) { // NOTE: don't have to check field-like events, because they can't have struct types. continue; } var field = (FieldSymbol)member; if (field.IsStatic) { continue; } var type = field.NonPointerType(); if (((object)type != null) && (type.TypeKind == TypeKind.Struct) && BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) && !type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type { // If this is a backing field, report the error on the associated property. var symbol = field.AssociatedSymbol ?? field; if (symbol.Kind == SymbolKind.Parameter) { // We should stick to members for this error. symbol = field; } // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type); return true; } } } return false; } private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) { if (!IsStatic) { return; } // no protected members allowed foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member is TypeSymbol) { // Duplicate Dev10's failure to diagnose this error. continue; } if (member.DeclaredAccessibility.HasProtected()) { if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor) { diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member); } } } } } private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) { // SPEC: The true and false unary operators require pairwise declaration. // SPEC: A compile-time error occurs if a class or struct declares one // SPEC: of these operators without also declaring the other. // // SPEC DEFICIENCY: The line of the specification quoted above should say // the same thing as the lines below: that the formal parameters of the // paired true/false operators must match exactly. You can't do // op true(S) and op false(S?) for example. // SPEC: Certain binary operators require pairwise declaration. For every // SPEC: declaration of either operator of a pair, there must be a matching // SPEC: declaration of the other operator of the pair. Two operator // SPEC: declarations match when they have the same return type and the same // SPEC: type for each parameter. The following operators require pairwise // SPEC: declaration: == and !=, > and <, >= and <=. CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); // We also produce a warning if == / != is overridden without also overriding // Equals and GetHashCode, or if Equals is overridden without GetHashCode. CheckForEqualityAndGetHashCode(diagnostics); } private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2) { var ops1 = this.GetOperators(operatorName1); var ops2 = this.GetOperators(operatorName2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2); CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1); } private static void CheckForUnmatchedOperator( BindingDiagnosticBag diagnostics, ImmutableArray<MethodSymbol> ops1, ImmutableArray<MethodSymbol> ops2, string operatorName2) { foreach (var op1 in ops1) { bool foundMatch = false; foreach (var op2 in ops2) { foundMatch = DoOperatorsPair(op1, op2); if (foundMatch) { break; } } if (!foundMatch) { // CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2))); } } } private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) { if (op1.ParameterCount != op2.ParameterCount) { return false; } for (int p = 0; p < op1.ParameterCount; ++p) { if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions)) { return false; } } if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions)) { return false; } return true; } private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) { if (this.IsInterfaceType()) { // Interfaces are allowed to define Equals without GetHashCode if they want. return; } if (IsRecord || IsRecordStruct) { // For records the warnings reported below are simply going to echo record specific errors, // producing more noise. return; } bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() || this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any(); bool overridesEquals = this.TypeOverridesObjectMethod("Equals"); if (hasOp || overridesEquals) { bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode"); if (overridesEquals && !overridesGHC) { // CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this); } if (hasOp && !overridesEquals) { // CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o) diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this); } if (hasOp && !overridesGHC) { // CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this); } } } private bool TypeOverridesObjectMethod(string name) { foreach (var method in this.GetMembers(name).OfType<MethodSymbol>()) { if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object) { return true; } } return false; } private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics) { Debug.Assert(ReferenceEquals(this, this.OriginalDefinition)); if (AllTypeArgumentCount() == 0) return; var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance); instanceMap.Add(this, this); foreach (var m in this.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(this, type, instanceMap)) { // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type); //this.KnownCircularStruct = true; return; } } } private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap) { if (!t.ContainsTypeParameter()) return false; var tOriginal = t.OriginalDefinition; if (instanceMap.TryGetValue(tOriginal, out var oldInstance)) { // short circuit when we find a cycle, but only return true when the cycle contains the top struct return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top); } else { instanceMap.Add(tOriginal, t); try { foreach (var m in t.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(top, type, instanceMap)) return true; } return false; } finally { instanceMap.Remove(tOriginal); } } } private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics) { if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential) { return; } SyntaxReference? whereFoundField = null; if (this.SyntaxReferences.Length <= 1) { return; } foreach (var syntaxRef in this.SyntaxReferences) { var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax; if (syntax == null) { continue; } foreach (var m in syntax.Members) { if (HasInstanceData(m)) { if (whereFoundField != null && whereFoundField != syntaxRef) { diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this); return; } whereFoundField = syntaxRef; } } } } private static bool HasInstanceData(MemberDeclarationSyntax m) { switch (m.Kind()) { case SyntaxKind.FieldDeclaration: var fieldDecl = (FieldDeclarationSyntax)m; return !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword); case SyntaxKind.PropertyDeclaration: // auto-property var propertyDecl = (PropertyDeclarationSyntax)m; return !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) && propertyDecl.AccessorList != null && All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null); case SyntaxKind.EventFieldDeclaration: // field-like event declaration var eventFieldDecl = (EventFieldDeclarationSyntax)m; return !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword); default: return false; } } private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode { foreach (var t in list) { if (predicate(t)) return true; }; return false; } private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier) { foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; }; return false; } private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName; var membersAndInitializers = GetMembersAndInitializers(); // Most types don't have indexers. If this is one of those types, // just reuse the dictionary we build for early attribute decoding. // For tuples, we also need to take the slow path. if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object) { membersByName = _lazyEarlyAttributeDecodingMembersDictionary; } else { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); // Merge types into the member dictionary AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); } MergePartialMembers(ref membersByName, diagnostics); return membersByName; } private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName) { foreach (var pair in typesByName) { string name = pair.Key; ImmutableArray<NamedTypeSymbol> types = pair.Value; ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types); ImmutableArray<Symbol> membersForName; if (membersByName.TryGetValue(name, out membersForName)) { membersByName[name] = membersForName.Concat(typesAsSymbols); } else { membersByName.Add(name, typesAsSymbols); } } } private sealed class DeclaredMembersAndInitializersBuilder { public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public bool HaveIndexers; public RecordDeclarationSyntax? RecordDeclarationWithParameters; public SynthesizedRecordConstructor? RecordPrimaryConstructor; public bool IsNullableEnabledForInstanceConstructorsAndFields; public bool IsNullableEnabledForStaticConstructorsAndFields; public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation) { return new DeclaredMembersAndInitializers( NonTypeMembers.ToImmutableAndFree(), MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers), MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers), HaveIndexers, RecordDeclarationWithParameters, RecordPrimaryConstructor, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields, compilation); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || value; } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } public void Free() { NonTypeMembers.Free(); foreach (var group in StaticInitializers) { group.Free(); } StaticInitializers.Free(); foreach (var group in InstanceInitializers) { group.Free(); } InstanceInitializers.Free(); } internal void AddOrWrapTupleMembers(SourceMemberContainerTypeSymbol type) { this.NonTypeMembers = type.AddOrWrapTupleMembers(this.NonTypeMembers.ToImmutableAndFree()); } } protected sealed class DeclaredMembersAndInitializers { public readonly ImmutableArray<Symbol> NonTypeMembers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; public readonly bool HaveIndexers; public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters; public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor; public readonly bool IsNullableEnabledForInstanceConstructorsAndFields; public readonly bool IsNullableEnabledForStaticConstructorsAndFields; public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers(); private DeclaredMembersAndInitializers() { } public DeclaredMembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, RecordDeclarationSyntax? recordDeclarationWithParameters, SynthesizedRecordConstructor? recordPrimaryConstructor, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields, CSharpCompilation compilation) { Debug.Assert(!nonTypeMembers.IsDefault); AssertInitializers(staticInitializers, compilation); AssertInitializers(instanceInitializers, compilation); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.RecordDeclarationWithParameters = recordDeclarationWithParameters; this.RecordPrimaryConstructor = recordPrimaryConstructor; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } [Conditional("DEBUG")] public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation) { Debug.Assert(!initializers.IsDefault); if (initializers.IsEmpty) { return; } foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers) { Debug.Assert(!group.IsDefaultOrEmpty); } for (int i = 0; i < initializers.Length; i++) { if (i > 0) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } if (i + 1 < initializers.Length) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0); } if (initializers[i].Length != 1) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } } } } private sealed class MembersAndInitializersBuilder { public ArrayBuilder<Symbol>? NonTypeMembers; private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers; private bool IsNullableEnabledForInstanceConstructorsAndFields; private bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers) { Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel); this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; } public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers) { var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers; var instanceInitializers = InstanceInitializersForPositionalMembers is null ? declaredMembers.InstanceInitializers : mergeInitializers(); return new MembersAndInitializers( nonTypeMembers, declaredMembers.StaticInitializers, instanceInitializers, declaredMembers.HaveIndexers, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields); ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers() { Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0); Debug.Assert(declaredMembers.RecordPrimaryConstructor is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start)); var groupCount = declaredMembers.InstanceInitializers.Length; if (groupCount == 0) { return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); } var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation; var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation); int insertAt; for (insertAt = 0; insertAt < groupCount; insertAt++) { if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0) { break; } } ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder; if (insertAt != groupCount && declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start)) { // Need to merge into the previous group var declaredInitializers = declaredMembers.InstanceInitializers[insertAt]; var insertedInitializers = InstanceInitializersForPositionalMembers; #if DEBUG // initializers should be added in syntax order: Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree); Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start); #endif insertedInitializers.AddRange(declaredInitializers); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(insertedInitializers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1)); Debug.Assert(groupsBuilder.Count == groupCount); } else { Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start))); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt); Debug.Assert(groupsBuilder.Count == groupCount + 1); } var result = groupsBuilder.ToImmutableAndFree(); DeclaredMembersAndInitializers.AssertInitializers(result, compilation); return result; } } public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer) { if (InstanceInitializersForPositionalMembers is null) { InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } InstanceInitializersForPositionalMembers.Add(initializer); } public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers) { return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers; } public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers) { if (NonTypeMembers is null) { NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1); NonTypeMembers.AddRange(declaredMembers.NonTypeMembers); } NonTypeMembers.Add(member); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers) { if (initializers.Count == 0) { initializers.Free(); return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty; } var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count); foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers) { builder.Add(group.ToImmutableAndFree()); } initializers.Free(); return builder.ToImmutableAndFree(); } public void Free() { NonTypeMembers?.Free(); InstanceInitializersForPositionalMembers?.Free(); } } private MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics) { var declaredMembersAndInitializers = getDeclaredMembersAndInitializers(); if (declaredMembersAndInitializers is null) { // Another thread completed the work before this one return null; } var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers); AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics); if (Volatile.Read(ref _lazyMembersAndInitializers) != null) { // Another thread completed the work before this one membersAndInitializersBuilder.Free(); return null; } return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers); DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers() { var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers; if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) { return declaredMembersAndInitializers; } if (Volatile.Read(ref _lazyMembersAndInitializers) is not null) { // We're previously computed declared members and already cleared them out // No need to compute them again return null; } var diagnostics = BindingDiagnosticBag.GetInstance(); declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel); if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); return declaredMembersAndInitializers!; } // Builds explicitly declared members (as opposed to synthesized members). // This should not attempt to bind any method parameters as that would cause // the members being built to be captured in the binder cache before the final // list of members is determined. DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics) { var builder = new DeclaredMembersAndInitializersBuilder(); AddDeclaredNontypeMembers(builder, diagnostics); switch (TypeKind) { case TypeKind.Struct: CheckForStructBadInitializers(builder, diagnostics); CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics); break; case TypeKind.Enum: CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics); break; case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: // No additional checking required. break; default: break; } if (IsTupleType) { builder.AddOrWrapTupleMembers(this); } if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel) { // _lazyDeclaredMembersAndInitializers is already computed. no point to continue. builder.Free(); return null; } return builder.ToReadOnlyAndFree(DeclaringCompilation); } } internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints() { if (_lazySimpleProgramEntryPoints.IsDefault) { var diagnostics = BindingDiagnosticBag.GetInstance(); var simpleProgramEntryPoints = buildSimpleProgramEntryPoint(diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazySimpleProgramEntryPoints, simpleProgramEntryPoints)) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } Debug.Assert(!_lazySimpleProgramEntryPoints.IsDefault); return _lazySimpleProgramEntryPoints; ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics) { if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true } || this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null; foreach (var singleDecl in declaration.Declarations) { if (singleDecl.IsSimpleProgram) { if (builder is null) { builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance(); } else { Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation); } builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics)); } } if (builder is null) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } return builder.ToImmutableAndFree(); } } private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (TypeKind is TypeKind.Class) { AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers); } switch (TypeKind) { case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics); AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics); break; default: break; } } private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { foreach (var decl in this.declaration.Declarations) { if (!decl.HasAnyNontypeMembers) { continue; } if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } var syntax = decl.SyntaxReference.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.EnumDeclaration: AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.DelegateDeclaration: SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit. AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics); break; case SyntaxKind.CompilationUnit: AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)syntax; AddNonTypeMembers(builder, typeDecl.Members, diagnostics); break; case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var recordDecl = (RecordDeclarationSyntax)syntax; var parameterList = recordDecl.ParameterList; noteRecordParameters(recordDecl, parameterList, builder, diagnostics); AddNonTypeMembers(builder, recordDecl.Members, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { if (parameterList is null) { return; } if (builder.RecordDeclarationWithParameters is null) { builder.RecordDeclarationWithParameters = syntax; var ctor = new SynthesizedRecordConstructor(this, syntax); builder.RecordPrimaryConstructor = ctor; var compilation = DeclaringCompilation; builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList); if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } }) { builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList); } } else { diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location); } } } internal Binder GetBinder(CSharpSyntaxNode syntaxNode) { return this.DeclaringCompilation.GetBinder(syntaxNode); } private void MergePartialMembers( ref Dictionary<string, ImmutableArray<Symbol>> membersByName, BindingDiagnosticBag diagnostics) { var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count); memberNames.AddRange(membersByName.Keys); //key and value will be the same object var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer); foreach (var name in memberNames) { methodsBySignature.Clear(); foreach (var symbol in membersByName[name]) { var method = symbol as SourceMemberMethodSymbol; if (method is null || !method.IsPartial) { continue; // only partial methods need to be merged } if (methodsBySignature.TryGetValue(method, out var prev)) { var prevPart = (SourceOrdinaryMethodSymbol)prev; var methodPart = (SourceOrdinaryMethodSymbol)method; if (methodPart.IsPartialImplementation && (prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart))) { // A partial method may not have multiple implementing declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]); } else if (methodPart.IsPartialDefinition && (prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart))) { // A partial method may not have multiple defining declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]); } else { if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary) { // Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel. membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName); } membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart); } } else { methodsBySignature.Add(method, method); } } foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values) { // partial implementations not paired with a definition if (method.IsPartialImplementation && method.OtherPartOfPartial is null) { diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method); } else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true }) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method); } } } memberNames.Free(); } /// <summary> /// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name), /// and returning the combined symbol. /// </summary> /// <param name="symbols">The symbols array containing both the latent and implementing declaration</param> /// <param name="part1">One of the two declarations</param> /// <param name="part2">The other declaration</param> /// <returns>An updated symbols array containing only one method symbol representing the two parts</returns> private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2) { SourceOrdinaryMethodSymbol definition; SourceOrdinaryMethodSymbol implementation; if (part1.IsPartialDefinition) { definition = part1; implementation = part2; } else { definition = part2; implementation = part1; } SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation); // a partial method is represented in the member list by its definition part: return Remove(symbols, implementation); } private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol) { var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var s in symbols) { if (!ReferenceEquals(s, symbol)) { builder.Add(s); } } return builder.ToImmutableAndFree(); } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the property accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithPropertyAccessor( PropertySymbol propertySymbol, bool getNotSet, BindingDiagnosticBag diagnostics) { Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod; string accessorName; if ((object)accessor != null) { accessorName = accessor.Name; } else { string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name; accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName, getNotSet, propertySymbol.IsCompilationOutputWinMdObj()); } foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this); return; } } } } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the event accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithEventAccessor( EventSymbol eventSymbol, bool isAdder, BindingDiagnosticBag diagnostics) { Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder); foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this); return; } } } } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the property. /// </summary> private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet) { var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the event. /// </summary> private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder) { var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return true if the method parameters match the parameters of the /// property accessor, including the value parameter for the setter. /// </summary> private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams) { var propertyParams = propertySymbol.Parameters; var numParams = propertyParams.Length + (getNotSet ? 0 : 1); if (numParams != methodParams.Length) { return false; } for (int i = 0; i < numParams; i++) { var methodParam = methodParams[i]; if (methodParam.RefKind != RefKind.None) { return false; } var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type; if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions)) { return false; } } return true; } /// <summary> /// Return true if the method parameters match the parameters of the /// event accessor, including the value parameter. /// </summary> private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams) { return methodParams.Length == 1 && methodParams[0].RefKind == RefKind.None && eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions); } private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { // The previous enum constant used to calculate subsequent // implicit enum constants. (This is the most recent explicit // enum constant or the first implicit constant if no explicit values.) SourceEnumConstantSymbol? otherSymbol = null; // Offset from "otherSymbol". int otherSymbolOffset = 0; foreach (var member in syntax.Members) { SourceEnumConstantSymbol symbol; var valueOpt = member.EqualsValue; if (valueOpt != null) { symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics); } else { symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics); } result.NonTypeMembers.Add(symbol); if (valueOpt != null || otherSymbol is null) { otherSymbol = symbol; otherSymbolOffset = 1; } else { otherSymbolOffset++; } } } private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node) { if (initializers == null) { initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } else if (initializers.Count != 0) { // initializers should be added in syntax order: Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree); Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start); } initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node)); } private static void AddInitializers( ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers, ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt) { if (siblingsOpt != null) { allInitializers.Add(siblingsOpt); } } private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics) { foreach (var member in nonTypeMembers) { CheckInterfaceMember(member, diagnostics); } } private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics) { switch (member.Kind) { case SymbolKind.Field: break; case SymbolKind.Method: var meth = (MethodSymbol)member; switch (meth.MethodKind) { case MethodKind.Constructor: diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]); break; case MethodKind.Conversion: if (!meth.IsAbstract) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.UserDefinedOperator: if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName)) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.Destructor: diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]); break; case MethodKind.ExplicitInterfaceImplementation: //CS0541 is handled in SourcePropertySymbol case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.StaticConstructor: break; default: throw ExceptionUtilities.UnexpectedValue(meth.MethodKind); } break; case SymbolKind.Property: break; case SymbolKind.Event: break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static void CheckForStructDefaultConstructors( ArrayBuilder<Symbol> members, bool isEnum, BindingDiagnosticBag diagnostics) { foreach (var s in members) { var m = s as MethodSymbol; if (!(m is null)) { if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0) { var location = m.Locations[0]; if (isEnum) { diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location); } else { MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location); if (m.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location); } } } } } } private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); if (builder.RecordDeclarationWithParameters is not null) { Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record && record.Kind() == SyntaxKind.RecordStructDeclaration); return; } foreach (var initializers in builder.InstanceInitializers) { foreach (FieldOrPropertyInitializer initializer in initializers) { var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt; MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]); } } } private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers) { var simpleProgramEntryPoints = GetSimpleProgramEntryPoints(); foreach (var member in simpleProgramEntryPoints) { builder.AddNonTypeMember(member, declaredMembersAndInitializers); } } private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct)) { return; } ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList; var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate(); var fieldsByName = PooledDictionary<string, Symbol>.GetInstance(); var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1); var memberNames = PooledHashSet<string>.GetInstance(); foreach (var member in membersSoFar) { memberNames.Add(member.Name); switch (member) { case EventSymbol: case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }: continue; case FieldSymbol { Name: var fieldName }: if (!fieldsByName.ContainsKey(fieldName)) { fieldsByName.Add(fieldName, member); } continue; } if (!memberSignatures.ContainsKey(member)) { memberSignatures.Add(member, member); } } CSharpCompilation compilation = this.DeclaringCompilation; bool isRecordClass = declaration.Kind == DeclarationKind.Record; // Positional record bool primaryAndCopyCtorAmbiguity = false; if (!(paramList is null)) { Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object); // primary ctor var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor; Debug.Assert(ctor is object); members.Add(ctor); if (ctor.ParameterCount != 0) { // properties and Deconstruct var existingOrAddedMembers = addProperties(ctor.Parameters); addDeconstruct(ctor, existingOrAddedMembers); } if (isRecordClass) { primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions); } } if (isRecordClass) { addCopyCtor(primaryAndCopyCtorAmbiguity); addCloneMethod(); } PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null; var thisEquals = addThisEquals(equalityContract); if (isRecordClass) { addBaseEquals(); } addObjectEquals(thisEquals); var getHashCode = addGetHashCode(equalityContract); addEqualityOperators(); if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode) { diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name); } var printMembers = addPrintMembersMethod(membersSoFar); addToStringMethod(printMembers); memberSignatures.Free(); fieldsByName.Free(); memberNames.Free(); // Synthesizing non-readonly properties in struct would require changing readonly logic for PrintMembers method synthesis Debug.Assert(isRecordClass || !members.Any(m => m is PropertySymbol { GetMethod.IsEffectivelyReadOnly: false })); // We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all // going to the record declaration members.AddRange(membersSoFar); builder.NonTypeMembers?.Free(); builder.NonTypeMembers = members; return; void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol)); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.DeconstructMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.Out )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod)) { members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics)); } else { var deconstruct = (MethodSymbol)existingDeconstructMethod; if (deconstruct.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct); } if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType); } if (deconstruct.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct); } } } void addCopyCtor(bool primaryAndCopyCtorAmbiguity) { Debug.Assert(isRecordClass); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.InstanceConstructorName, this, MethodKind.Constructor, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor)) { var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count); members.Add(copyCtor); if (primaryAndCopyCtorAmbiguity) { diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]); } } else { var constructor = (MethodSymbol)existingConstructor; if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor); } } } void addCloneMethod() { Debug.Assert(isRecordClass); members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics)); } MethodSymbol addPrintMembersMethod(IEnumerable<Symbol> userDefinedMembers) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.PrintMembersMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None)), RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); MethodSymbol printMembersMethod; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod)) { printMembersMethod = new SynthesizedRecordPrintMembers(this, userDefinedMembers, memberOffset: members.Count, diagnostics); members.Add(printMembersMethod); } else { printMembersMethod = (MethodSymbol)existingPrintMembersMethod; if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())) { if (printMembersMethod.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } } else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) { if (!printMembersMethod.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType); } } else if (isRecordClass) { SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics); } reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics); } return printMembersMethod; } void addToStringMethod(MethodSymbol printMethod) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectToString, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); var baseToStringMethod = getBaseToStringMethod(); if (baseToStringMethod is { IsSealed: true }) { if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord)) { var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion; var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion(); diagnostics.Add( ErrorCode.ERR_InheritingFromRecordWithSealedToString, this.Locations[0], languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } else { if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod)) { var toStringMethod = new SynthesizedRecordToString( this, printMethod, memberOffset: members.Count, isReadOnly: printMethod.IsEffectivelyReadOnly, diagnostics); members.Add(toStringMethod); } else { var toStringMethod = (MethodSymbol)existingToStringMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed) { MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability( diagnostics, this.DeclaringCompilation, toStringMethod.Locations[0]); } } } MethodSymbol? getBaseToStringMethod() { var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString); var currentBaseType = this.BaseTypeNoUseSiteDiagnostics; while (currentBaseType is not null) { foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString)) { if (member is not MethodSymbol method) continue; if (method.GetLeastOverriddenMethod(null) == objectToString) return method; } currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics; } return null; } } ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters) { var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length); int addedCount = 0; foreach (ParameterSymbol param in recordParameters) { bool isInherited = false; var syntax = param.GetNonNullSyntaxNode(); var targetProperty = new SignatureOnlyPropertySymbol(param.Name, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); if (!memberSignatures.TryGetValue(targetProperty, out var existingMember) && !fieldsByName.TryGetValue(param.Name, out existingMember)) { existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true); isInherited = true; } // There should be an error if we picked a member that is hidden // This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630 if (existingMember is null) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics)); } else if (existingMember is FieldSymbol { IsStatic: false } field && field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics); if (!isInherited || checkMemberNotHidden(field, param)) { existingOrAddedMembers.Add(field); } } else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop && prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { // There already exists a member corresponding to the candidate synthesized property. if (isInherited && prop.IsAbstract) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics)); } else if (!isInherited || checkMemberNotHidden(prop, param)) { // Deconstruct() is specified to simply assign from this property to the corresponding out parameter. existingOrAddedMembers.Add(prop); } } else { diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter, param.Locations[0], new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)), param.TypeWithAnnotations, param.Name); } void addProperty(SynthesizedRecordPropertySymbol property) { existingOrAddedMembers.Add(property); members.Add(property); Debug.Assert(property.GetMethod is object); Debug.Assert(property.SetMethod is object); members.Add(property.GetMethod); members.Add(property.SetMethod); members.Add(property.BackingField); builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal])); addedCount++; } } return existingOrAddedMembers.ToImmutableAndFree(); bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param) { if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name)) { diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol); return false; } return true; } } void addObjectEquals(MethodSymbol thisEquals) { members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics)); } MethodSymbol addGetHashCode(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectGetHashCode, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol getHashCode; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod)) { getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(getHashCode); } else { getHashCode = (MethodSymbol)existingHashCodeMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed) { diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode); } } return getHashCode; } PropertySymbol addEqualityContract() { Debug.Assert(isRecordClass); var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)), ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); PropertySymbol equalityContract; if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty)) { equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics); members.Add(equalityContract); members.Add(equalityContract.GetMethod); } else { equalityContract = (PropertySymbol)existingEqualityContractProperty; if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { if (equalityContract.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract); } } else if (equalityContract.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract); } if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions)) { if (!equalityContract.Type.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type); } } else { SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics); } if (equalityContract.GetMethod is null) { diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract); } reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics); } return equalityContract; } MethodSymbol addThisEquals(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectEquals, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol thisEquals; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod)) { thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(thisEquals); } else { thisEquals = (MethodSymbol)existingEqualsMethod; if (thisEquals.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals); } if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType); } reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics); } return thisEquals; } void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics) { if (isRecordClass && !IsSealed && ((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed)) { diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol); } else if (symbol.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol); } } void addBaseEquals() { Debug.Assert(isRecordClass); if (!BaseTypeNoUseSiteDiagnostics.IsObjectType()) { members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics)); } } void addEqualityOperators() { members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics)); members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics)); } } private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { //we're not calling the helpers on NamedTypeSymbol base, because those call //GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow) var hasInstanceConstructor = false; var hasParameterlessInstanceConstructor = false; var hasStaticConstructor = false; // CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the // dictionary construction process. For now, this is more encapsulated. var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); foreach (var member in membersSoFar) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; switch (method.MethodKind) { case MethodKind.Constructor: // Ignore the record copy constructor if (!IsRecord || !(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor)) { hasInstanceConstructor = true; hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0; } break; case MethodKind.StaticConstructor: hasStaticConstructor = true; break; } } //kick out early if we've seen everything we're looking for if (hasInstanceConstructor && hasStaticConstructor) { break; } } // NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor". // We won't insert a parameterless constructor for a struct if there already is one. // The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table. if ((!hasParameterlessInstanceConstructor && this.IsStructType()) || (!hasInstanceConstructor && !this.IsStatic && !this.IsInterface)) { builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ? new SynthesizedSubmissionConstructor(this, diagnostics) : new SynthesizedInstanceConstructor(this), declaredMembersAndInitializers); } // constants don't count, since they do not exist as fields at runtime // NOTE: even for decimal constants (which require field initializers), // we do not create .cctor here since a static constructor implicitly created for a decimal // should not appear in the list returned by public API like GetMembers(). if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers)) { // Note: we don't have to put anything in the method - the binder will // do that when processing field initializers. builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers); } if (this.IsScriptClass) { var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics); builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers); var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics); builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers); } static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst)); } } private void AddNonTypeMembers( DeclaredMembersAndInitializersBuilder builder, SyntaxList<MemberDeclarationSyntax> members, BindingDiagnosticBag diagnostics) { if (members.Count == 0) { return; } var firstMember = members[0]; var bodyBinder = this.GetBinder(firstMember); ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null; ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null; var compilation = DeclaringCompilation; foreach (var m in members) { if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } bool reportMisplacedGlobalCode = !m.HasErrors; switch (m.Kind()) { case SyntaxKind.FieldDeclaration: { var fieldSyntax = (FieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier)); } bool modifierErrors; var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors); foreach (var variable in fieldSyntax.Declaration.Variables) { var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0 ? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics) : new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics); builder.NonTypeMembers.Add(fieldSymbol); // All fields are included in the nullable context for constructors and initializers, even fields without // initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker. builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable); if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this, DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static), fieldSymbol); } if (variable.Initializer != null) { if (fieldSymbol.IsStatic) { AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer); } else { AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer); } } } } break; case SyntaxKind.MethodDeclaration: { var methodSyntax = (MethodDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(methodSyntax.Identifier)); } var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.ConstructorDeclaration: { var constructorSyntax = (ConstructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(constructorSyntax.Identifier)); } bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax); var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics); builder.NonTypeMembers.Add(constructor); if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer) { builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled); } } break; case SyntaxKind.DestructorDeclaration: { var destructorSyntax = (DestructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(destructorSyntax.Identifier)); } // CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the // runtime won't consider it a finalizer and it will not be marked as a destructor // when it is loaded from metadata. Perhaps we should just treat it as an Ordinary // method in such cases? var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics); builder.NonTypeMembers.Add(destructor); } break; case SyntaxKind.PropertyDeclaration: { var propertySyntax = (PropertyDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(propertySyntax.Identifier)); } var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics); builder.NonTypeMembers.Add(property); AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod); FieldSymbol backingField = property.BackingField; // TODO: can we leave this out of the member list? // From the 10/12/11 design notes: // In addition, we will change autoproperties to behavior in // a similar manner and make the autoproperty fields private. if ((object)backingField != null) { builder.NonTypeMembers.Add(backingField); builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax); var initializer = propertySyntax.Initializer; if (initializer != null) { if (IsScriptClass) { // also gather expression-declared variables from the initializer ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, initializer, this, DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0), backingField); } if (property.IsStatic) { AddInitializer(ref staticInitializers, backingField, initializer); } else { AddInitializer(ref instanceInitializers, backingField, initializer); } } } } break; case SyntaxKind.EventFieldDeclaration: { var eventFieldSyntax = (EventFieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add( ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier)); } foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables) { SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics); builder.NonTypeMembers.Add(@event); FieldSymbol? associatedField = @event.AssociatedField; if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this, DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0), associatedField); } if ((object?)associatedField != null) { // NOTE: specifically don't add the associated field to the members list // (regard it as an implementation detail). builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator); if (declarator.Initializer != null) { if (associatedField.IsStatic) { AddInitializer(ref staticInitializers, associatedField, declarator.Initializer); } else { AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer); } } } Debug.Assert((object)@event.AddMethod != null); Debug.Assert((object)@event.RemoveMethod != null); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); } } break; case SyntaxKind.EventDeclaration: { var eventSyntax = (EventDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventSyntax.Identifier)); } var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics); builder.NonTypeMembers.Add(@event); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); Debug.Assert(@event.AssociatedField is null); } break; case SyntaxKind.IndexerDeclaration: { var indexerSyntax = (IndexerDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(indexerSyntax.ThisKeyword)); } var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics); builder.HaveIndexers = true; builder.NonTypeMembers.Add(indexer); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod); } break; case SyntaxKind.ConversionOperatorDeclaration: { var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(conversionOperatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol( this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.OperatorDeclaration: { var operatorSyntax = (OperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(operatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol( this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.GlobalStatement: { var globalStatement = ((GlobalStatementSyntax)m).Statement; if (IsScriptClass) { var innerStatement = globalStatement; // drill into any LabeledStatements while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: // We shouldn't reach this place, but field declarations preceded with a label end up here. // This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now. var decl = (LocalDeclarationStatementSyntax)innerStatement; foreach (var vdecl in decl.Declaration.Variables) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private, containingFieldOpt: null); } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, innerStatement, this, DeclarationModifiers.Private, containingFieldOpt: null); break; default: // no other statement introduces variables into the enclosing scope break; } AddInitializer(ref instanceInitializers, null, globalStatement); } else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m)) { diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement)); } } break; default: Debug.Assert( SyntaxFacts.IsTypeDeclaration(m.Kind()) || m.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration or SyntaxKind.IncompleteMember); break; } } AddInitializers(builder.InstanceInitializers, instanceInitializers); AddInitializers(builder.StaticInitializers, staticInitializers); } private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt) { if (!(accessorOpt is null)) { symbols.Add(accessorOpt); } } internal override byte? GetLocalNullableContextValue() { byte? value; if (!_flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); _flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); var baseType = BaseTypeNoUseSiteDiagnostics; if (baseType is object) { builder.AddValue(TypeWithAnnotations.Create(baseType)); } foreach (var @interface in GetInterfacesToEmit()) { builder.AddValue(TypeWithAnnotations.Create(@interface)); } foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } foreach (var member in GetMembersUnordered()) { member.GetCommonNullableValues(compilation, ref builder); } // Not including lambdas or local functions. return builder.MostCommonValue; } /// <summary> /// Returns true if the overall nullable context is enabled for constructors and initializers. /// </summary> /// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param> internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic) { var membersAndInitializers = GetMembersAndInitializers(); return useStatic ? membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields : membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = DeclaringCompilation; NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (baseType is object) { if (baseType.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0)); } if (baseType.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType)); } if (baseType.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType)); } } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (baseType is object) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType))); } } } #endregion #region Extension Methods internal bool ContainsExtensionMethods { get { if (!_lazyContainsExtensionMethods.HasValue()) { bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods; _lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } } internal bool AnyMemberHasAttributes { get { if (!_lazyAnyMemberHasAttributes.HasValue()) { bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes; _lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState(); } return _lazyAnyMemberHasAttributes.Value(); } } public override bool MightContainExtensionMethods { get { return this.ContainsExtensionMethods; } } #endregion public sealed override NamedTypeSymbol ConstructedFrom { get { return this; } } internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0; internal class SynthesizedExplicitImplementations { public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty); public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods; public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls; private SynthesizedExplicitImplementations( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { ForwardingMethods = forwardingMethods.NullToEmpty(); MethodImpls = methodImpls.NullToEmpty(); } internal static SynthesizedExplicitImplementations Create( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty) { return Empty; } return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls); } } } }
// 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.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type symbol whose members are declared in source. /// </summary> internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol { // The flags type is used to compact many different bits of information efficiently. private struct Flags { // We current pack everything into one 32-bit int; layout is given below. // // | |vvv|zzzz|f|d|yy|wwwwww| // // w = special type. 6 bits. // y = IsManagedType. 2 bits. // d = FieldDefinitionsNoted. 1 bit // f = FlattenedMembersIsSorted. 1 bit. // z = TypeKind. 4 bits. // v = NullableContext. 3 bits. private int _flags; private const int SpecialTypeOffset = 0; private const int SpecialTypeSize = 6; private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize; private const int ManagedKindSize = 2; private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize; private const int FieldDefinitionsNotedSize = 1; private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize; private const int FlattenedMembersIsSortedSize = 1; private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize; private const int TypeKindSize = 4; private const int NullableContextOffset = TypeKindOffset + TypeKindSize; private const int NullableContextSize = 3; private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1; private const int ManagedKindMask = (1 << ManagedKindSize) - 1; private const int TypeKindMask = (1 << TypeKindSize) - 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset; private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset; public SpecialType SpecialType { get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); } } public ManagedKind ManagedKind { get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); } } public bool FieldDefinitionsNoted { get { return (_flags & FieldDefinitionsNotedBit) != 0; } } // True if "lazyMembersFlattened" is sorted. public bool FlattenedMembersIsSorted { get { return (_flags & FlattenedMembersIsSortedBit) != 0; } } public TypeKind TypeKind { get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif public Flags(SpecialType specialType, TypeKind typeKind) { int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset; int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset; _flags = specialTypeInt | typeKindInt; } public void SetFieldDefinitionsNoted() { ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit); } public void SetFlattenedMembersIsSorted() { ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit)); } private static bool BitsAreUnsetOrSame(int bits, int mask) { return (bits & mask) == 0 || (bits & mask) == mask; } public void SetManagedKind(ManagedKind managedKind) { int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset; Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet)); ThreadSafeFlagOperations.Set(ref _flags, bitsToSet); } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary = PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer); protected SymbolCompletionState state; private Flags _flags; private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics; private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies; private readonly DeclarationModifiers _declModifiers; private readonly NamespaceOrTypeSymbol _containingSymbol; protected readonly MergedTypeDeclaration declaration; // The entry point symbol (resulting from top-level statements) is needed to construct non-type members because // it contributes to their binders, so we have to compute it first. // The value changes from "default" to "real value". The transition from "default" can only happen once. private ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> _lazySimpleProgramEntryPoints; // To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set) // The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once. private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel; private MembersAndInitializers? _lazyMembersAndInitializers; private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary; private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary; private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance); private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers; private ImmutableArray<Symbol> _lazyMembersFlattened; private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations; private int _lazyKnownCircularStruct; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; private ThreeState _lazyContainsExtensionMethods; private ThreeState _lazyAnyMemberHasAttributes; #region Construction internal SourceMemberContainerTypeSymbol( NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData? tupleData = null) : base(tupleData) { // If we're dealing with a simple program, then we must be in the global namespace Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram)); _containingSymbol = containingSymbol; this.declaration = declaration; TypeKind typeKind = declaration.Kind.ToTypeKind(); var modifiers = MakeModifiers(typeKind, diagnostics); foreach (var singleDeclaration in declaration.Declarations) { diagnostics.AddRange(singleDeclaration.Diagnostics); } int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask); if ((access & (access - 1)) != 0) { // more than one access modifier if ((modifiers & DeclarationModifiers.Partial) != 0) diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this); access = access & ~(access - 1); // narrow down to one access modifier modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all modifiers |= (DeclarationModifiers)access; // except the one } _declModifiers = modifiers; var specialType = access == (int)DeclarationModifiers.Public ? MakeSpecialType() : SpecialType.None; _flags = new Flags(specialType, typeKind); var containingType = this.ContainingType; if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected()) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this); } state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately } private SpecialType MakeSpecialType() { // check if this is one of the COR library types if (ContainingSymbol.Kind == SymbolKind.Namespace && ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) { //for a namespace, the emitted name is a dot-separated list of containing namespaces var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName); return SpecialTypes.GetTypeFromMetadataName(emittedName); } else { return SpecialType.None; } } private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics) { Symbol containingSymbol = this.ContainingSymbol; DeclarationModifiers defaultAccess; var allowedModifiers = DeclarationModifiers.AccessibilityMask; if (containingSymbol.Kind == SymbolKind.Namespace) { defaultAccess = DeclarationModifiers.Internal; } else { allowedModifiers |= DeclarationModifiers.New; if (((NamedTypeSymbol)containingSymbol).IsInterface) { defaultAccess = DeclarationModifiers.Public; } else { defaultAccess = DeclarationModifiers.Private; } } switch (typeKind) { case TypeKind.Class: case TypeKind.Submission: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Unsafe; if (!this.IsRecord) { allowedModifiers |= DeclarationModifiers.Static; } break; case TypeKind.Struct: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe; if (!this.IsRecordStruct) { allowedModifiers |= DeclarationModifiers.Ref; } break; case TypeKind.Interface: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; break; case TypeKind.Delegate: allowedModifiers |= DeclarationModifiers.Unsafe; break; } bool modifierErrors; var mods = MakeAndCheckTypeModifiers( defaultAccess, allowedModifiers, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); if (!modifierErrors && (mods & DeclarationModifiers.Abstract) != 0 && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this); } if (!modifierErrors && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) { diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this); } switch (typeKind) { case TypeKind.Interface: mods |= DeclarationModifiers.Abstract; break; case TypeKind.Struct: case TypeKind.Enum: mods |= DeclarationModifiers.Sealed; break; case TypeKind.Delegate: mods |= DeclarationModifiers.Sealed; break; } return mods; } private DeclarationModifiers MakeAndCheckTypeModifiers( DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { modifierErrors = false; var result = DeclarationModifiers.Unset; var partCount = declaration.Declarations.Length; var missingPartial = false; for (var i = 0; i < partCount; i++) { var decl = declaration.Declarations[i]; var mods = decl.Modifiers; if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0) { missingPartial = true; } if (!modifierErrors) { mods = ModifierUtils.CheckModifiers( mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics, modifierTokens: null, modifierErrors: out modifierErrors); // It is an error for the same modifier to appear multiple times. if (!modifierErrors) { var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, this.Locations[0]); modifierErrors = true; } } } if (result == DeclarationModifiers.Unset) { result = mods; } else { result |= mods; } } if ((result & DeclarationModifiers.AccessibilityMask) == 0) { result |= defaultAccess; } if (missingPartial) { if ((result & DeclarationModifiers.Partial) == 0) { // duplicate definitions switch (this.ContainingSymbol.Kind) { case SymbolKind.Namespace: for (var i = 1; i < partCount; i++) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol); modifierErrors = true; } break; case SymbolKind.NamedType: for (var i = 1; i < partCount; i++) { if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial()) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name); modifierErrors = true; } break; } } else { for (var i = 0; i < partCount; i++) { var singleDeclaration = declaration.Declarations[i]; var mods = singleDeclaration.Modifiers; if ((mods & DeclarationModifiers.Partial) == 0) { diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name); modifierErrors = true; } } } } if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword)) { foreach (var syntaxRef in SyntaxReferences) { SyntaxToken? identifier = syntaxRef.GetSyntax() switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => null }; ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None); } } return result; } internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location) { if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) && compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion()) { diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name); } } #endregion #region Completion internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } protected abstract void CheckBase(BindingDiagnosticBag diagnostics); protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics); internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) { while (true) { // NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers. cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartBaseType: case CompletionPart.FinishBaseType: if (state.NotePartComplete(CompletionPart.StartBaseType)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckBase(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishBaseType); diagnostics.Free(); } break; case CompletionPart.StartInterfaces: case CompletionPart.FinishInterfaces: if (state.NotePartComplete(CompletionPart.StartInterfaces)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckInterfaces(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishInterfaces); diagnostics.Free(); } break; case CompletionPart.EnumUnderlyingType: var discarded = this.EnumUnderlyingType; break; case CompletionPart.TypeArguments: { var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments } break; case CompletionPart.TypeParameters: // force type parameters foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.Members: this.GetMembersByName(); break; case CompletionPart.TypeMembers: this.GetTypeMembersUnordered(); break; case CompletionPart.SynthesizedExplicitImplementations: this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked break; case CompletionPart.StartMemberChecks: case CompletionPart.FinishMemberChecks: if (state.NotePartComplete(CompletionPart.StartMemberChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); AfterMembersChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); // We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.MembersCompleted: { ImmutableArray<Symbol> members = this.GetMembersUnordered(); bool allCompleted = true; if (locationOpt == null) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (!allCompleted) { // We did not complete all members so we won't have enough information for // the PointedAtManagedTypeChecks, so just kick out now. var allParts = CompletionPart.NamedTypeSymbolWithLocationAll; state.SpinWaitComplete(allParts, cancellationToken); return; } EnsureFieldDefinitionsNoted(); // We've completed all members, so we're ready for the PointedAtManagedTypeChecks; // proceed to the next iteration. state.NotePartComplete(CompletionPart.MembersCompleted); break; } case CompletionPart.None: return; default: // This assert will trigger if we forgot to handle any of the completion parts Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0); // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } throw ExceptionUtilities.Unreachable; } internal void EnsureFieldDefinitionsNoted() { if (_flags.FieldDefinitionsNoted) { return; } NoteFieldDefinitions(); } private void NoteFieldDefinitions() { // we must note all fields once therefore we need to lock var membersAndInitializers = this.GetMembersAndInitializers(); lock (membersAndInitializers) { if (!_flags.FieldDefinitionsNoted) { var assembly = (SourceAssemblySymbol)ContainingAssembly; Accessibility containerEffectiveAccessibility = EffectiveAccessibility(); foreach (var member in membersAndInitializers.NonTypeMembers) { FieldSymbol field; if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer) { continue; } Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility; if (fieldDeclaredAccessibility == Accessibility.Private) { // mark private fields as tentatively unassigned and unread unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true); } else if (containerEffectiveAccessibility == Accessibility.Private) { // mark effectively private fields as tentatively unassigned unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false); } else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal) { // mark effectively internal fields as tentatively unassigned unless we discover otherwise. // NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly. // See property SourceAssemblySymbol.UnusedFieldWarnings. assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false); } } _flags.SetFieldDefinitionsNoted(); } } } #endregion #region Containers public sealed override NamedTypeSymbol? ContainingType { get { return _containingSymbol as NamedTypeSymbol; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } #endregion #region Flags Encoded Properties public override SpecialType SpecialType { get { return _flags.SpecialType; } } public override TypeKind TypeKind { get { return _flags.TypeKind; } } internal MergedTypeDeclaration MergedDeclaration { get { return this.declaration; } } internal sealed override bool IsInterface { get { // TypeKind is computed eagerly, so this is cheap. return this.TypeKind == TypeKind.Interface; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var managedKind = _flags.ManagedKind; if (managedKind == ManagedKind.Unknown) { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly); managedKind = base.GetManagedKind(ref managedKindUseSiteInfo); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty); _flags.SetManagedKind(managedKind); } if (useSiteInfo.AccumulatesDiagnostics) { ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics; // Ensure we have the latest value from the field useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics); Debug.Assert(!useSiteDiagnostics.IsDefault); useSiteInfo.AddDiagnostics(useSiteDiagnostics); } if (useSiteInfo.AccumulatesDependencies) { ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies; // Ensure we have the latest value from the field useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies); Debug.Assert(!useSiteDependencies.IsDefault); useSiteInfo.AddDependencies(useSiteDependencies); } return managedKind; } public override bool IsStatic => HasFlag(DeclarationModifiers.Static); public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref); public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly); public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed); public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract); internal bool IsPartial => HasFlag(DeclarationModifiers.Partial); internal bool IsNew => HasFlag(DeclarationModifiers.New); [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0; public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_declModifiers); } } /// <summary> /// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields. /// </summary> private Accessibility EffectiveAccessibility() { var result = DeclaredAccessibility; if (result == Accessibility.Private) return Accessibility.Private; for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType) { switch (container.DeclaredAccessibility) { case Accessibility.Private: return Accessibility.Private; case Accessibility.Internal: result = Accessibility.Internal; continue; } } return result; } #endregion #region Syntax public override bool IsScriptClass { get { var kind = this.declaration.Declarations[0].Kind; return kind == DeclarationKind.Script || kind == DeclarationKind.Submission; } } public override bool IsImplicitClass { get { return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass; } } internal override bool IsRecord { get { return this.declaration.Declarations[0].Kind == DeclarationKind.Record; } } internal override bool IsRecordStruct { get { return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct; } } public override bool IsImplicitlyDeclared { get { return IsImplicitClass || IsScriptClass; } } public override int Arity { get { return declaration.Arity; } } public override string Name { get { return declaration.Name; } } internal override bool MangleName { get { return Arity > 0; } } internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public sealed override ImmutableArray<Location> Locations { get { return declaration.NameLocations.Cast<SourceLocation, Location>(); } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return this.declaration.SyntaxReferences; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return SyntaxReferences; } } // This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { var declarations = declaration.Declarations; if (IsImplicitlyDeclared && declarations.IsEmpty) { return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var syntaxRef = declaration.SyntaxReference; if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } #endregion #region Members /// <summary> /// Encapsulates information about the non-type members of a (i.e. this) type. /// 1) For non-initializers, symbols are created and stored in a list. /// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are /// stored with other initialized fields and properties from the same syntax tree with /// the same static-ness. /// </summary> protected sealed class MembersAndInitializers { internal readonly ImmutableArray<Symbol> NonTypeMembers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; internal readonly bool HaveIndexers; internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields; internal readonly bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields) { Debug.Assert(!nonTypeMembers.IsDefault); Debug.Assert(!staticInitializers.IsDefault); Debug.Assert(staticInitializers.All(g => !g.IsDefault)); Debug.Assert(!instanceInitializers.IsDefault); Debug.Assert(instanceInitializers.All(g => !g.IsDefault)); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer())); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers { get { return GetMembersAndInitializers().StaticInitializers; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers { get { return GetMembersAndInitializers().InstanceInitializers; } } internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic) { if (IsScriptClass && !isStatic) { int aggregateLength = 0; foreach (var declaration in this.declaration.Declarations) { var syntaxRef = declaration.SyntaxReference; if (tree == syntaxRef.SyntaxTree) { return aggregateLength + position; } aggregateLength += syntaxRef.Span.Length; } throw ExceptionUtilities.Unreachable; } int syntaxOffset; if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset)) { return syntaxOffset; } if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start) { // With dynamic analysis instrumentation, the introducing declaration of a type can provide // the syntax associated with both the analysis payload local of a synthesized constructor // and with the constructor itself. If the synthesized constructor includes an initializer with a lambda, // that lambda needs a closure that captures the analysis payload of the constructor, // and the offset of the syntax for the local within the constructor is by definition zero. return 0; } // an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer throw ExceptionUtilities.Unreachable; } /// <summary> /// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one). /// </summary> internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset) { Debug.Assert(ctorInitializerLength >= 0); var membersAndInitializers = GetMembersAndInitializers(); var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers; if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength)) { syntaxOffset = 0; return false; } // |<-----------distanceFromCtorBody----------->| // [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body] // |<--preceding init len-->| ^ // position int initializersLength = getInitializersLength(allInitializers); int distanceFromInitializerStart = position - initializer.Syntax.Span.Start; int distanceFromCtorBody = initializersLength + ctorInitializerLength - (precedingLength + distanceFromInitializerStart); Debug.Assert(distanceFromCtorBody > 0); // syntax offset 0 is at the start of the ctor body: syntaxOffset = -distanceFromCtorBody; return true; static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree, out FieldOrPropertyInitializer found, out int precedingLength) { precedingLength = 0; foreach (var group in initializers) { if (!group.IsEmpty && group[0].Syntax.SyntaxTree == tree && position < group.Last().Syntax.Span.End) { // Found group of interest var initializerIndex = IndexOfInitializerContainingPosition(group, position); if (initializerIndex < 0) { break; } precedingLength += getPrecedingInitializersLength(group, initializerIndex); found = group[initializerIndex]; return true; } precedingLength += getGroupLength(group); } found = default; return false; } static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers) { int length = 0; foreach (var initializer in initializers) { length += getInitializerLength(initializer); } return length; } static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index) { int length = 0; for (var i = 0; i < index; i++) { length += getInitializerLength(initializers[i]); } return length; } static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { int length = 0; foreach (var group in initializers) { length += getGroupLength(group); } return length; } static int getInitializerLength(FieldOrPropertyInitializer initializer) { // A constant field of type decimal needs a field initializer, so // check if it is a metadata constant, not just a constant to exclude // decimals. Other constants do not need field initializers. if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant) { // ignore leading and trailing trivia of the node: return initializer.Syntax.Span.Length; } return 0; } } private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position) { // Search for the start of the span (the spans are non-overlapping and sorted) int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos)); // Binary search returns non-negative result if the position is exactly the start of some span. if (index >= 0) { return index; } // Otherwise, ~index is the closest span whose start is greater than the position. // => Check if the preceding initializer span contains the position. int precedingInitializerIndex = ~index - 1; if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position)) { return precedingInitializerIndex; } return -1; } public override IEnumerable<string> MemberNames { get { return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembersDictionary().Flatten(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; if (GetTypeMembersDictionary().TryGetValue(name, out members)) { return members; } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary() { if (_lazyTypeMembers == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.TypeMembers); } diagnostics.Free(); } return _lazyTypeMembers; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>(); try { foreach (var childDeclaration in declaration.Children) { var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics); this.CheckMemberNameDistinctFromType(t, diagnostics); var key = (t.Name, t.Arity); SourceNamedTypeSymbol? other; if (conflictDict.TryGetValue(key, out other)) { if (Locations.Length == 1 || IsPartial) { if (t.IsPartial && other.IsPartial) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name); } } } else { conflictDict.Add(key, t); } symbols.Add(t); } if (IsInterface) { foreach (var t in symbols) { Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]); } } Debug.Assert(s_emptyTypeMembers.Count == 0); return symbols.Count > 0 ? symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) : s_emptyTypeMembers; } finally { symbols.Free(); } } private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics) { switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: if (member.Name == this.Name) { diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name); } break; case TypeKind.Interface: if (member.IsStatic) { goto case TypeKind.Class; } break; } } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyMembersFlattened; if (result.IsDefault) { result = GetMembersByName().Flatten(null); // do not sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result); result = _lazyMembersFlattened; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if (_flags.FlattenedMembersIsSorted) { return _lazyMembersFlattened; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length > 1) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers); } _flags.SetFlattenedMembersIsSorted(); return allMembers; } } public sealed override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<Symbol> members; if (GetMembersByName().TryGetValue(name, out members)) { return members; } return ImmutableArray<Symbol>.Empty; } /// <remarks> /// For source symbols, there can only be a valid clone method if this is a record, which is a /// simple syntax check. This will need to change when we generalize cloning, but it's a good /// heuristic for now. /// </remarks> internal override bool HasPossibleWellKnownCloneMethod() => IsRecord; internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct) { return GetMembers(name); } return ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { // For consistency with Dev10, emit value__ field first. var valueField = ((SourceNamedTypeSymbol)this).EnumValueField; RoslynDebug.Assert((object)valueField != null); yield return valueField; } foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: if (m is TupleErrorFieldSymbol) { break; } yield return (FieldSymbol)m; break; case SymbolKind.Event: FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField; if ((object?)associatedField != null) { yield return associatedField; } break; } } } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return GetEarlyAttributeDecodingMembersDictionary().Flatten(); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { ImmutableArray<Symbol> result; return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty; } private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary() { if (_lazyEarlyAttributeDecodingMembersDictionary == null) { if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result) { return result; } var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached // NOTE: members were added in a single pass over the syntax, so they're already // in lexical order. Dictionary<string, ImmutableArray<Symbol>> membersByName; if (!membersAndInitializers.HaveIndexers) { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name); } else { // We can't include indexer symbol yet, because we don't know // what name it will have after attribute binding (because of // IndexerNameAttribute). membersByName = membersAndInitializers.NonTypeMembers. WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)). ToDictionary(s => s.Name); } AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null); } return _lazyEarlyAttributeDecodingMembersDictionary; } // NOTE: this method should do as little work as possible // we often need to get members just to do a lookup. // All additional checks and diagnostics may be not // needed yet or at all. protected MembersAndInitializers GetMembersAndInitializers() { var membersAndInitializers = _lazyMembersAndInitializers; if (membersAndInitializers != null) { return membersAndInitializers; } var diagnostics = BindingDiagnosticBag.GetInstance(); membersAndInitializers = BuildMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null); if (alreadyKnown != null) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); _lazyDeclaredMembersAndInitializers = null; return membersAndInitializers!; } /// <summary> /// The purpose of this function is to assert that the <paramref name="member"/> symbol /// is actually among the symbols cached by this type symbol in a way that ensures /// that any consumer of standard APIs to get to type's members is going to get the same /// symbol (same instance) for the member rather than an equivalent, but different instance. /// </summary> [Conditional("DEBUG")] internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false) { if (member is NamedTypeSymbol type) { RoslynDebug.AssertOrFailFast(forDiagnostics); RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true); return; } else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol) { RoslynDebug.AssertOrFailFast(forDiagnostics); return; } else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e) { RoslynDebug.AssertOrFailFast(forDiagnostics); // Backing fields for field-like events are not added to the members list. member = e; } var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } if (membersAndInitializers is null) { if (member is SynthesizedSimpleProgramEntryPointSymbol) { RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member)); return; } var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers); RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel); if (declared is object) { if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member) { return; } } else { // It looks like there was a race and we need to check _lazyMembersAndInitializers again membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); RoslynDebug.AssertOrFailFast(membersAndInitializers is object); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } } } RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure."); static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member) { return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true; } } protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName() { if (this.state.HasComplete(CompletionPart.Members)) { return _lazyMembersDictionary!; } return GetMembersByNameSlow(); } private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow() { if (_lazyMembersDictionary == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var membersDictionary = MakeAllMembers(diagnostics); if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.Members); } diagnostics.Free(); } state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken)); return _lazyMembersDictionary; } internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents() { var membersAndInitializers = this.GetMembersAndInitializers(); return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent); } protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) { if (IsInterface) { CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics); } CheckMemberNamesDistinctFromType(diagnostics); CheckMemberNameConflicts(diagnostics); CheckRecordMemberNames(diagnostics); CheckSpecialMemberErrors(diagnostics); CheckTypeParameterNameConflicts(diagnostics); CheckAccessorNameConflicts(diagnostics); bool unused = KnownCircularStruct; CheckSequentialOnPartialType(diagnostics); CheckForProtectedInStaticClass(diagnostics); CheckForUnmatchedOperators(diagnostics); var location = Locations[0]; var compilation = DeclaringCompilation; if (this.IsRefLikeType) { compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true); } if (this.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } var baseType = BaseTypeNoUseSiteDiagnostics; var interfaces = GetInterfacesToEmit(); // https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations. if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger())) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute())) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } } if (interfaces.Any(t => needsTupleElementNamesAttribute(t))) { // Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding) // so the checking of all interfaces here involves some redundancy. Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics); } bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate) { return ((object)baseType != null && predicate(baseType)) || interfaces.Any(predicate); } static bool needsTupleElementNamesAttribute(TypeSymbol type) { if (type is null) { return false; } var resultType = type.VisitType( predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(), arg: (object?)null); return resultType is object; } } private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics) { foreach (var member in GetMembersAndInitializers().NonTypeMembers) { CheckMemberNameDistinctFromType(member, diagnostics); } } private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics) { if (declaration.Kind != DeclarationKind.Record && declaration.Kind != DeclarationKind.RecordStruct) { return; } foreach (var member in GetMembers("Clone")) { diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]); } } private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName(); // Collisions involving indexers are handled specially. CheckIndexerNameConflicts(diagnostics, membersByName); // key and value will be the same object in these dictionaries. var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer); // SPEC: The signature of an operator must differ from the signatures of all other // SPEC: operators declared in the same class. // DELIBERATE SPEC VIOLATION: // The specification does not state that a user-defined conversion reserves the names // op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt // to define a field or a conflicting method with the metadata name of a user-defined // conversion is an error. We preserve this reasonable behavior. // // Similarly, we treat "public static C operator +(C, C)" as colliding with // "public static C op_Addition(C, C)". Fortunately, this behavior simply // falls out of treating user-defined operators as ordinary methods; we do // not need any special handling in this method. // // However, we must have special handling for conversions because conversions // use a completely different rule for detecting collisions between two // conversions: conversion signatures consist only of the source and target // types of the conversions, and not the kind of the conversion (implicit or explicit), // the name of the method, and so on. // // Therefore we must detect the following kinds of member name conflicts: // // 1. a method, conversion or field has the same name as a (different) field (* see note below) // 2. a method has the same method signature as another method or conversion // 3. a conversion has the same conversion signature as another conversion. // // However, we must *not* detect "a conversion has the same *method* signature // as another conversion" because conversions are allowed to overload on // return type but methods are not. // // (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for // "non-method, non-conversion, non-type member", rather than spelling out // "field, property or event...") foreach (var pair in membersByName) { var name = pair.Key; Symbol? lastSym = GetTypeMembers(name).FirstOrDefault(); methodsBySignature.Clear(); // Conversion collisions do not consider the name of the conversion, // so do not clear that dictionary. foreach (var symbol in pair.Value) { if (symbol.Kind == SymbolKind.NamedType || symbol.IsAccessor() || symbol.IsIndexer()) { continue; } // We detect the first category of conflict by running down the list of members // of the same name, and producing an error when we discover any of the following // "bad transitions". // // * a method or conversion that comes after any field (not necessarily directly) // * a field directly following a field // * a field directly following a method or conversion // // Furthermore: we do not wish to detect collisions between nested types in // this code; that is tested elsewhere. However, we do wish to detect a collision // between a nested type and a field, method or conversion. Therefore we // initialize our "bad transition" detector with a type of the given name, // if there is one. That way we also detect the transitions of "method following // type", and so on. // // The "lastSym" local below is used to detect these transitions. Its value is // one of the following: // // * a nested type of the given name, or // * the first method of the given name, or // * the most recently processed field of the given name. // // If either the current symbol or the "last symbol" are not methods then // there must be a collision: // // * if the current symbol is not a method and the last symbol is, then // there is a field directly following a method of the same name // * if the current symbol is a method and the last symbol is not, then // there is a method directly or indirectly following a field of the same name, // or a method of the same name as a nested type. // * if neither are methods then either we have a field directly // following a field of the same name, or a field and a nested type of the same name. // if (lastSym is object) { if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method) { if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name); } } if (lastSym.Kind == SymbolKind.Method) { lastSym = symbol; } } } else { lastSym = symbol; } // That takes care of the first category of conflict; we detect the // second and third categories as follows: var conversion = symbol as SourceUserDefinedConversionSymbol; var method = symbol as SourceMemberMethodSymbol; if (!(conversion is null)) { // Does this conversion collide *as a conversion* with any previously-seen // conversion? if (!conversionsAsConversions.Add(conversion)) { // CS0557: Duplicate user-defined conversion in type 'C' diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this); } else { // The other set might already contain a conversion which would collide // *as a method* with the current conversion. if (!conversionsAsMethods.ContainsKey(conversion)) { conversionsAsMethods.Add(conversion, conversion); } } // Does this conversion collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(conversion, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, conversion, previousMethod); } // Do not add the conversion to the set of previously-seen methods; that set // is only non-conversion methods. } else if (!(method is null)) { // Does this method collide *as a method* with any previously-seen // conversion? if (conversionsAsMethods.TryGetValue(method, out var previousConversion)) { ReportMethodSignatureCollision(diagnostics, method, previousConversion); } // Do not add the method to the set of previously-seen conversions. // Does this method collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(method, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, method, previousMethod); } else { // We haven't seen this method before. Make a note of it in case // we see a colliding method later. methodsBySignature.Add(method, method); } } } } } // Report a name conflict; the error is reported on the location of method1. // UNDONE: Consider adding a secondary location pointing to the second method. private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2) { switch (method1, method2) { case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }): case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }): // these could be 2 parts of the same partial method. // Partial methods are allowed to collide by signature. return; case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }): return; } // If method1 is a constructor only because its return type is missing, then // we've already produced a diagnostic for the missing return type and we suppress the // diagnostic about duplicate signature. if (method1.MethodKind == MethodKind.Constructor && ((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name) { return; } Debug.Assert(method1.ParameterCount == method2.ParameterCount); for (int i = 0; i < method1.ParameterCount; i++) { var refKind1 = method1.Parameters[i].RefKind; var refKind2 = method2.Parameters[i].RefKind; if (refKind1 != refKind2) { // '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}' var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD; diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString()); return; } } // Special case: if there are two destructors, use the destructor syntax instead of "Finalize" var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ? "~" + this.Name : (method1.IsConstructor() ? this.Name : method1.Name); // Type '{1}' already defines a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this); } private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName) { PooledHashSet<string>? typeParameterNames = null; if (this.Arity > 0) { typeParameterNames = PooledHashSet<string>.GetInstance(); foreach (TypeParameterSymbol typeParameter in this.TypeParameters) { typeParameterNames.Add(typeParameter.Name); } } var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer); // Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because // they may be explicit interface implementations. foreach (var members in membersByName.Values) { string? lastIndexerName = null; indexersBySignature.Clear(); foreach (var symbol in members) { if (symbol.IsIndexer()) { PropertySymbol indexer = (PropertySymbol)symbol; CheckIndexerSignatureCollisions( indexer, diagnostics, membersByName, indexersBySignature, ref lastIndexerName); // Also check for collisions with type parameters, which aren't in the member map. // NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts. if (typeParameterNames != null) { string indexerName = indexer.MetadataName; if (typeParameterNames.Contains(indexerName)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); continue; } } } } } typeParameterNames?.Free(); } private void CheckIndexerSignatureCollisions( PropertySymbol indexer, BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<PropertySymbol, PropertySymbol> indexersBySignature, ref string? lastIndexerName) { if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked { string indexerName = indexer.MetadataName; if (lastIndexerName != null && lastIndexerName != indexerName) { // NOTE: dev10 checks indexer names by comparing each to the previous. // For example, if indexers are declared with names A, B, A, B, then there // will be three errors - one for each time the name is different from the // previous one. If, on the other hand, the names are A, A, B, B, then // there will only be one error because only one indexer has a different // name from the previous one. diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]); } lastIndexerName = indexerName; if (Locations.Length == 1 || IsPartial) { if (membersByName.ContainsKey(indexerName)) { // The name of the indexer is reserved - it can only be used by other indexers. Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer)); diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); } } } if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature)) { // Type '{1}' already defines a member called '{0}' with the same parameter types // NOTE: Dev10 prints "this" as the name of the indexer. diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this); } else { indexersBySignature[indexer] = indexer; } } private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics) { var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary); foreach (var member in this.GetMembersUnordered()) { member.AfterAddingTypeMembersChecks(conversions, diagnostics); } } private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics) { if (this.TypeKind == TypeKind.Delegate) { // Delegates do not have conflicts between their type parameter // names and their methods; it is legal (though odd) to say // delegate void D<Invoke>(Invoke x); return; } if (Locations.Length == 1 || IsPartial) { foreach (var tp in TypeParameters) { foreach (var dup in GetMembers(tp.Name)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name); } } } } private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics) { // Report errors where property and event accessors // conflict with other members of the same name. foreach (Symbol symbol in this.GetMembersUnordered()) { if (symbol.IsExplicitInterfaceImplementation()) { // If there's a name conflict it will show up as a more specific // interface implementation error. continue; } switch (symbol.Kind) { case SymbolKind.Property: { var propertySymbol = (PropertySymbol)symbol; this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics); this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics); break; } case SymbolKind.Event: { var eventSymbol = (EventSymbol)symbol; this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics); this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics); break; } } } } internal override bool KnownCircularStruct { get { if (_lazyKnownCircularStruct == (int)ThreeState.Unknown) { if (TypeKind != TypeKind.Struct) { Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); var value = (int)CheckStructCircularity(diagnostics).ToThreeState(); if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown) { AddDeclarationDiagnostics(diagnostics); } Debug.Assert(value == _lazyKnownCircularStruct); diagnostics.Free(); } } return _lazyKnownCircularStruct == (int)ThreeState.True; } } private bool CheckStructCircularity(BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); CheckFiniteFlatteningGraph(diagnostics); return HasStructCircularity(diagnostics); } private bool HasStructCircularity(BindingDiagnosticBag diagnostics) { foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member.Kind != SymbolKind.Field) { // NOTE: don't have to check field-like events, because they can't have struct types. continue; } var field = (FieldSymbol)member; if (field.IsStatic) { continue; } var type = field.NonPointerType(); if (((object)type != null) && (type.TypeKind == TypeKind.Struct) && BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) && !type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type { // If this is a backing field, report the error on the associated property. var symbol = field.AssociatedSymbol ?? field; if (symbol.Kind == SymbolKind.Parameter) { // We should stick to members for this error. symbol = field; } // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type); return true; } } } return false; } private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) { if (!IsStatic) { return; } // no protected members allowed foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member is TypeSymbol) { // Duplicate Dev10's failure to diagnose this error. continue; } if (member.DeclaredAccessibility.HasProtected()) { if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor) { diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member); } } } } } private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) { // SPEC: The true and false unary operators require pairwise declaration. // SPEC: A compile-time error occurs if a class or struct declares one // SPEC: of these operators without also declaring the other. // // SPEC DEFICIENCY: The line of the specification quoted above should say // the same thing as the lines below: that the formal parameters of the // paired true/false operators must match exactly. You can't do // op true(S) and op false(S?) for example. // SPEC: Certain binary operators require pairwise declaration. For every // SPEC: declaration of either operator of a pair, there must be a matching // SPEC: declaration of the other operator of the pair. Two operator // SPEC: declarations match when they have the same return type and the same // SPEC: type for each parameter. The following operators require pairwise // SPEC: declaration: == and !=, > and <, >= and <=. CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); // We also produce a warning if == / != is overridden without also overriding // Equals and GetHashCode, or if Equals is overridden without GetHashCode. CheckForEqualityAndGetHashCode(diagnostics); } private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2) { var ops1 = this.GetOperators(operatorName1); var ops2 = this.GetOperators(operatorName2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2); CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1); } private static void CheckForUnmatchedOperator( BindingDiagnosticBag diagnostics, ImmutableArray<MethodSymbol> ops1, ImmutableArray<MethodSymbol> ops2, string operatorName2) { foreach (var op1 in ops1) { bool foundMatch = false; foreach (var op2 in ops2) { foundMatch = DoOperatorsPair(op1, op2); if (foundMatch) { break; } } if (!foundMatch) { // CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2))); } } } private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) { if (op1.ParameterCount != op2.ParameterCount) { return false; } for (int p = 0; p < op1.ParameterCount; ++p) { if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions)) { return false; } } if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions)) { return false; } return true; } private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) { if (this.IsInterfaceType()) { // Interfaces are allowed to define Equals without GetHashCode if they want. return; } if (IsRecord || IsRecordStruct) { // For records the warnings reported below are simply going to echo record specific errors, // producing more noise. return; } bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() || this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any(); bool overridesEquals = this.TypeOverridesObjectMethod("Equals"); if (hasOp || overridesEquals) { bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode"); if (overridesEquals && !overridesGHC) { // CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this); } if (hasOp && !overridesEquals) { // CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o) diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this); } if (hasOp && !overridesGHC) { // CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this); } } } private bool TypeOverridesObjectMethod(string name) { foreach (var method in this.GetMembers(name).OfType<MethodSymbol>()) { if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object) { return true; } } return false; } private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics) { Debug.Assert(ReferenceEquals(this, this.OriginalDefinition)); if (AllTypeArgumentCount() == 0) return; var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance); instanceMap.Add(this, this); foreach (var m in this.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(this, type, instanceMap)) { // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type); //this.KnownCircularStruct = true; return; } } } private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap) { if (!t.ContainsTypeParameter()) return false; var tOriginal = t.OriginalDefinition; if (instanceMap.TryGetValue(tOriginal, out var oldInstance)) { // short circuit when we find a cycle, but only return true when the cycle contains the top struct return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top); } else { instanceMap.Add(tOriginal, t); try { foreach (var m in t.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(top, type, instanceMap)) return true; } return false; } finally { instanceMap.Remove(tOriginal); } } } private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics) { if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential) { return; } SyntaxReference? whereFoundField = null; if (this.SyntaxReferences.Length <= 1) { return; } foreach (var syntaxRef in this.SyntaxReferences) { var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax; if (syntax == null) { continue; } foreach (var m in syntax.Members) { if (HasInstanceData(m)) { if (whereFoundField != null && whereFoundField != syntaxRef) { diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this); return; } whereFoundField = syntaxRef; } } } } private static bool HasInstanceData(MemberDeclarationSyntax m) { switch (m.Kind()) { case SyntaxKind.FieldDeclaration: var fieldDecl = (FieldDeclarationSyntax)m; return !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword); case SyntaxKind.PropertyDeclaration: // auto-property var propertyDecl = (PropertyDeclarationSyntax)m; return !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) && propertyDecl.AccessorList != null && All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null); case SyntaxKind.EventFieldDeclaration: // field-like event declaration var eventFieldDecl = (EventFieldDeclarationSyntax)m; return !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword); default: return false; } } private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode { foreach (var t in list) { if (predicate(t)) return true; }; return false; } private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier) { foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; }; return false; } private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName; var membersAndInitializers = GetMembersAndInitializers(); // Most types don't have indexers. If this is one of those types, // just reuse the dictionary we build for early attribute decoding. // For tuples, we also need to take the slow path. if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object) { membersByName = _lazyEarlyAttributeDecodingMembersDictionary; } else { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); // Merge types into the member dictionary AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); } MergePartialMembers(ref membersByName, diagnostics); return membersByName; } private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName) { foreach (var pair in typesByName) { string name = pair.Key; ImmutableArray<NamedTypeSymbol> types = pair.Value; ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types); ImmutableArray<Symbol> membersForName; if (membersByName.TryGetValue(name, out membersForName)) { membersByName[name] = membersForName.Concat(typesAsSymbols); } else { membersByName.Add(name, typesAsSymbols); } } } private sealed class DeclaredMembersAndInitializersBuilder { public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public bool HaveIndexers; public RecordDeclarationSyntax? RecordDeclarationWithParameters; public SynthesizedRecordConstructor? RecordPrimaryConstructor; public bool IsNullableEnabledForInstanceConstructorsAndFields; public bool IsNullableEnabledForStaticConstructorsAndFields; public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation) { return new DeclaredMembersAndInitializers( NonTypeMembers.ToImmutableAndFree(), MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers), MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers), HaveIndexers, RecordDeclarationWithParameters, RecordPrimaryConstructor, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields, compilation); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || value; } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } public void Free() { NonTypeMembers.Free(); foreach (var group in StaticInitializers) { group.Free(); } StaticInitializers.Free(); foreach (var group in InstanceInitializers) { group.Free(); } InstanceInitializers.Free(); } } protected sealed class DeclaredMembersAndInitializers { public readonly ImmutableArray<Symbol> NonTypeMembers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; public readonly bool HaveIndexers; public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters; public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor; public readonly bool IsNullableEnabledForInstanceConstructorsAndFields; public readonly bool IsNullableEnabledForStaticConstructorsAndFields; public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers(); private DeclaredMembersAndInitializers() { } public DeclaredMembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, RecordDeclarationSyntax? recordDeclarationWithParameters, SynthesizedRecordConstructor? recordPrimaryConstructor, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields, CSharpCompilation compilation) { Debug.Assert(!nonTypeMembers.IsDefault); AssertInitializers(staticInitializers, compilation); AssertInitializers(instanceInitializers, compilation); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.RecordDeclarationWithParameters = recordDeclarationWithParameters; this.RecordPrimaryConstructor = recordPrimaryConstructor; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } [Conditional("DEBUG")] public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation) { Debug.Assert(!initializers.IsDefault); if (initializers.IsEmpty) { return; } foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers) { Debug.Assert(!group.IsDefaultOrEmpty); } for (int i = 0; i < initializers.Length; i++) { if (i > 0) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } if (i + 1 < initializers.Length) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0); } if (initializers[i].Length != 1) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } } } } private sealed class MembersAndInitializersBuilder { private ArrayBuilder<Symbol>? NonTypeMembers; private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers; private bool IsNullableEnabledForInstanceConstructorsAndFields; private bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers) { Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel); this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; } public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers) { var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers; var instanceInitializers = InstanceInitializersForPositionalMembers is null ? declaredMembers.InstanceInitializers : mergeInitializers(); return new MembersAndInitializers( nonTypeMembers, declaredMembers.StaticInitializers, instanceInitializers, declaredMembers.HaveIndexers, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields); ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers() { Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0); Debug.Assert(declaredMembers.RecordPrimaryConstructor is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start)); var groupCount = declaredMembers.InstanceInitializers.Length; if (groupCount == 0) { return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); } var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation; var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation); int insertAt; for (insertAt = 0; insertAt < groupCount; insertAt++) { if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0) { break; } } ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder; if (insertAt != groupCount && declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start)) { // Need to merge into the previous group var declaredInitializers = declaredMembers.InstanceInitializers[insertAt]; var insertedInitializers = InstanceInitializersForPositionalMembers; #if DEBUG // initializers should be added in syntax order: Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree); Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start); #endif insertedInitializers.AddRange(declaredInitializers); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(insertedInitializers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1)); Debug.Assert(groupsBuilder.Count == groupCount); } else { Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start))); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt); Debug.Assert(groupsBuilder.Count == groupCount + 1); } var result = groupsBuilder.ToImmutableAndFree(); DeclaredMembersAndInitializers.AssertInitializers(result, compilation); return result; } } public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer) { if (InstanceInitializersForPositionalMembers is null) { InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } InstanceInitializersForPositionalMembers.Add(initializer); } public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers) { return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers; } public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers) { if (NonTypeMembers is null) { NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1); NonTypeMembers.AddRange(declaredMembers.NonTypeMembers); } NonTypeMembers.Add(member); } public void SetNonTypeMembers(ArrayBuilder<Symbol> members) { NonTypeMembers?.Free(); NonTypeMembers = members; } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers) { if (initializers.Count == 0) { initializers.Free(); return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty; } var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count); foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers) { builder.Add(group.ToImmutableAndFree()); } initializers.Free(); return builder.ToImmutableAndFree(); } public void Free() { NonTypeMembers?.Free(); InstanceInitializersForPositionalMembers?.Free(); } } private MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics) { var declaredMembersAndInitializers = getDeclaredMembersAndInitializers(); if (declaredMembersAndInitializers is null) { // Another thread completed the work before this one return null; } var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers); AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics); if (Volatile.Read(ref _lazyMembersAndInitializers) != null) { // Another thread completed the work before this one membersAndInitializersBuilder.Free(); return null; } return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers); DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers() { var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers; if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) { return declaredMembersAndInitializers; } if (Volatile.Read(ref _lazyMembersAndInitializers) is not null) { // We're previously computed declared members and already cleared them out // No need to compute them again return null; } var diagnostics = BindingDiagnosticBag.GetInstance(); declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel); if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); return declaredMembersAndInitializers!; } // Builds explicitly declared members (as opposed to synthesized members). // This should not attempt to bind any method parameters as that would cause // the members being built to be captured in the binder cache before the final // list of members is determined. DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics) { var builder = new DeclaredMembersAndInitializersBuilder(); AddDeclaredNontypeMembers(builder, diagnostics); switch (TypeKind) { case TypeKind.Struct: CheckForStructBadInitializers(builder, diagnostics); CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics); break; case TypeKind.Enum: CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics); break; case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: // No additional checking required. break; default: break; } if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel) { // _lazyDeclaredMembersAndInitializers is already computed. no point to continue. builder.Free(); return null; } return builder.ToReadOnlyAndFree(DeclaringCompilation); } } internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints() { if (_lazySimpleProgramEntryPoints.IsDefault) { var diagnostics = BindingDiagnosticBag.GetInstance(); var simpleProgramEntryPoints = buildSimpleProgramEntryPoint(diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazySimpleProgramEntryPoints, simpleProgramEntryPoints)) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } Debug.Assert(!_lazySimpleProgramEntryPoints.IsDefault); return _lazySimpleProgramEntryPoints; ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics) { if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true } || this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null; foreach (var singleDecl in declaration.Declarations) { if (singleDecl.IsSimpleProgram) { if (builder is null) { builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance(); } else { Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation); } builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics)); } } if (builder is null) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } return builder.ToImmutableAndFree(); } } private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (TypeKind is TypeKind.Class) { AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers); } switch (TypeKind) { case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics); AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics); break; default: break; } AddSynthesizedTupleMembersIfNecessary(builder, declaredMembersAndInitializers); } private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { foreach (var decl in this.declaration.Declarations) { if (!decl.HasAnyNontypeMembers) { continue; } if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } var syntax = decl.SyntaxReference.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.EnumDeclaration: AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.DelegateDeclaration: SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit. AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics); break; case SyntaxKind.CompilationUnit: AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)syntax; AddNonTypeMembers(builder, typeDecl.Members, diagnostics); break; case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var recordDecl = (RecordDeclarationSyntax)syntax; var parameterList = recordDecl.ParameterList; noteRecordParameters(recordDecl, parameterList, builder, diagnostics); AddNonTypeMembers(builder, recordDecl.Members, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { if (parameterList is null) { return; } if (builder.RecordDeclarationWithParameters is null) { builder.RecordDeclarationWithParameters = syntax; var ctor = new SynthesizedRecordConstructor(this, syntax); builder.RecordPrimaryConstructor = ctor; var compilation = DeclaringCompilation; builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList); if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } }) { builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList); } } else { diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location); } } } internal Binder GetBinder(CSharpSyntaxNode syntaxNode) { return this.DeclaringCompilation.GetBinder(syntaxNode); } private void MergePartialMembers( ref Dictionary<string, ImmutableArray<Symbol>> membersByName, BindingDiagnosticBag diagnostics) { var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count); memberNames.AddRange(membersByName.Keys); //key and value will be the same object var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer); foreach (var name in memberNames) { methodsBySignature.Clear(); foreach (var symbol in membersByName[name]) { var method = symbol as SourceMemberMethodSymbol; if (method is null || !method.IsPartial) { continue; // only partial methods need to be merged } if (methodsBySignature.TryGetValue(method, out var prev)) { var prevPart = (SourceOrdinaryMethodSymbol)prev; var methodPart = (SourceOrdinaryMethodSymbol)method; if (methodPart.IsPartialImplementation && (prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart))) { // A partial method may not have multiple implementing declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]); } else if (methodPart.IsPartialDefinition && (prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart))) { // A partial method may not have multiple defining declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]); } else { if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary) { // Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel. membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName); } membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart); } } else { methodsBySignature.Add(method, method); } } foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values) { // partial implementations not paired with a definition if (method.IsPartialImplementation && method.OtherPartOfPartial is null) { diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method); } else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true }) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method); } } } memberNames.Free(); } /// <summary> /// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name), /// and returning the combined symbol. /// </summary> /// <param name="symbols">The symbols array containing both the latent and implementing declaration</param> /// <param name="part1">One of the two declarations</param> /// <param name="part2">The other declaration</param> /// <returns>An updated symbols array containing only one method symbol representing the two parts</returns> private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2) { SourceOrdinaryMethodSymbol definition; SourceOrdinaryMethodSymbol implementation; if (part1.IsPartialDefinition) { definition = part1; implementation = part2; } else { definition = part2; implementation = part1; } SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation); // a partial method is represented in the member list by its definition part: return Remove(symbols, implementation); } private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol) { var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var s in symbols) { if (!ReferenceEquals(s, symbol)) { builder.Add(s); } } return builder.ToImmutableAndFree(); } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the property accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithPropertyAccessor( PropertySymbol propertySymbol, bool getNotSet, BindingDiagnosticBag diagnostics) { Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod; string accessorName; if ((object)accessor != null) { accessorName = accessor.Name; } else { string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name; accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName, getNotSet, propertySymbol.IsCompilationOutputWinMdObj()); } foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this); return; } } } } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the event accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithEventAccessor( EventSymbol eventSymbol, bool isAdder, BindingDiagnosticBag diagnostics) { Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder); foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this); return; } } } } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the property. /// </summary> private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet) { var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the event. /// </summary> private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder) { var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return true if the method parameters match the parameters of the /// property accessor, including the value parameter for the setter. /// </summary> private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams) { var propertyParams = propertySymbol.Parameters; var numParams = propertyParams.Length + (getNotSet ? 0 : 1); if (numParams != methodParams.Length) { return false; } for (int i = 0; i < numParams; i++) { var methodParam = methodParams[i]; if (methodParam.RefKind != RefKind.None) { return false; } var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type; if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions)) { return false; } } return true; } /// <summary> /// Return true if the method parameters match the parameters of the /// event accessor, including the value parameter. /// </summary> private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams) { return methodParams.Length == 1 && methodParams[0].RefKind == RefKind.None && eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions); } private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { // The previous enum constant used to calculate subsequent // implicit enum constants. (This is the most recent explicit // enum constant or the first implicit constant if no explicit values.) SourceEnumConstantSymbol? otherSymbol = null; // Offset from "otherSymbol". int otherSymbolOffset = 0; foreach (var member in syntax.Members) { SourceEnumConstantSymbol symbol; var valueOpt = member.EqualsValue; if (valueOpt != null) { symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics); } else { symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics); } result.NonTypeMembers.Add(symbol); if (valueOpt != null || otherSymbol is null) { otherSymbol = symbol; otherSymbolOffset = 1; } else { otherSymbolOffset++; } } } private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node) { if (initializers == null) { initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } else if (initializers.Count != 0) { // initializers should be added in syntax order: Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree); Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start); } initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node)); } private static void AddInitializers( ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers, ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt) { if (siblingsOpt != null) { allInitializers.Add(siblingsOpt); } } private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics) { foreach (var member in nonTypeMembers) { CheckInterfaceMember(member, diagnostics); } } private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics) { switch (member.Kind) { case SymbolKind.Field: break; case SymbolKind.Method: var meth = (MethodSymbol)member; switch (meth.MethodKind) { case MethodKind.Constructor: diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]); break; case MethodKind.Conversion: if (!meth.IsAbstract) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.UserDefinedOperator: if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName)) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.Destructor: diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]); break; case MethodKind.ExplicitInterfaceImplementation: //CS0541 is handled in SourcePropertySymbol case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.StaticConstructor: break; default: throw ExceptionUtilities.UnexpectedValue(meth.MethodKind); } break; case SymbolKind.Property: break; case SymbolKind.Event: break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static void CheckForStructDefaultConstructors( ArrayBuilder<Symbol> members, bool isEnum, BindingDiagnosticBag diagnostics) { foreach (var s in members) { var m = s as MethodSymbol; if (!(m is null)) { if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0) { var location = m.Locations[0]; if (isEnum) { diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location); } else { MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location); if (m.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location); } } } } } } private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); if (builder.RecordDeclarationWithParameters is not null) { Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record && record.Kind() == SyntaxKind.RecordStructDeclaration); return; } foreach (var initializers in builder.InstanceInitializers) { foreach (FieldOrPropertyInitializer initializer in initializers) { var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt; MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]); } } } private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers) { var simpleProgramEntryPoints = GetSimpleProgramEntryPoints(); foreach (var member in simpleProgramEntryPoints) { builder.AddNonTypeMember(member, declaredMembersAndInitializers); } } private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct)) { return; } ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList; var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate(); var fieldsByName = PooledDictionary<string, Symbol>.GetInstance(); var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1); var memberNames = PooledHashSet<string>.GetInstance(); foreach (var member in membersSoFar) { memberNames.Add(member.Name); switch (member) { case EventSymbol: case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }: continue; case FieldSymbol { Name: var fieldName }: if (!fieldsByName.ContainsKey(fieldName)) { fieldsByName.Add(fieldName, member); } continue; } if (!memberSignatures.ContainsKey(member)) { memberSignatures.Add(member, member); } } CSharpCompilation compilation = this.DeclaringCompilation; bool isRecordClass = declaration.Kind == DeclarationKind.Record; // Positional record bool primaryAndCopyCtorAmbiguity = false; if (!(paramList is null)) { Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object); // primary ctor var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor; Debug.Assert(ctor is object); members.Add(ctor); if (ctor.ParameterCount != 0) { // properties and Deconstruct var existingOrAddedMembers = addProperties(ctor.Parameters); addDeconstruct(ctor, existingOrAddedMembers); } if (isRecordClass) { primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions); } } if (isRecordClass) { addCopyCtor(primaryAndCopyCtorAmbiguity); addCloneMethod(); } PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null; var thisEquals = addThisEquals(equalityContract); if (isRecordClass) { addBaseEquals(); } addObjectEquals(thisEquals); var getHashCode = addGetHashCode(equalityContract); addEqualityOperators(); if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode) { diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name); } var printMembers = addPrintMembersMethod(membersSoFar); addToStringMethod(printMembers); memberSignatures.Free(); fieldsByName.Free(); memberNames.Free(); // Synthesizing non-readonly properties in struct would require changing readonly logic for PrintMembers method synthesis Debug.Assert(isRecordClass || !members.Any(m => m is PropertySymbol { GetMethod.IsEffectivelyReadOnly: false })); // We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all // going to the record declaration members.AddRange(membersSoFar); builder.SetNonTypeMembers(members); return; void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol)); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.DeconstructMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.Out )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod)) { members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics)); } else { var deconstruct = (MethodSymbol)existingDeconstructMethod; if (deconstruct.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct); } if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType); } if (deconstruct.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct); } } } void addCopyCtor(bool primaryAndCopyCtorAmbiguity) { Debug.Assert(isRecordClass); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.InstanceConstructorName, this, MethodKind.Constructor, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor)) { var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count); members.Add(copyCtor); if (primaryAndCopyCtorAmbiguity) { diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]); } } else { var constructor = (MethodSymbol)existingConstructor; if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor); } } } void addCloneMethod() { Debug.Assert(isRecordClass); members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics)); } MethodSymbol addPrintMembersMethod(IEnumerable<Symbol> userDefinedMembers) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.PrintMembersMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None)), RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); MethodSymbol printMembersMethod; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod)) { printMembersMethod = new SynthesizedRecordPrintMembers(this, userDefinedMembers, memberOffset: members.Count, diagnostics); members.Add(printMembersMethod); } else { printMembersMethod = (MethodSymbol)existingPrintMembersMethod; if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())) { if (printMembersMethod.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } } else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) { if (!printMembersMethod.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType); } } else if (isRecordClass) { SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics); } reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics); } return printMembersMethod; } void addToStringMethod(MethodSymbol printMethod) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectToString, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); var baseToStringMethod = getBaseToStringMethod(); if (baseToStringMethod is { IsSealed: true }) { if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord)) { var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion; var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion(); diagnostics.Add( ErrorCode.ERR_InheritingFromRecordWithSealedToString, this.Locations[0], languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } else { if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod)) { var toStringMethod = new SynthesizedRecordToString( this, printMethod, memberOffset: members.Count, isReadOnly: printMethod.IsEffectivelyReadOnly, diagnostics); members.Add(toStringMethod); } else { var toStringMethod = (MethodSymbol)existingToStringMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed) { MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability( diagnostics, this.DeclaringCompilation, toStringMethod.Locations[0]); } } } MethodSymbol? getBaseToStringMethod() { var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString); var currentBaseType = this.BaseTypeNoUseSiteDiagnostics; while (currentBaseType is not null) { foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString)) { if (member is not MethodSymbol method) continue; if (method.GetLeastOverriddenMethod(null) == objectToString) return method; } currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics; } return null; } } ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters) { var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length); int addedCount = 0; foreach (ParameterSymbol param in recordParameters) { bool isInherited = false; var syntax = param.GetNonNullSyntaxNode(); var targetProperty = new SignatureOnlyPropertySymbol(param.Name, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); if (!memberSignatures.TryGetValue(targetProperty, out var existingMember) && !fieldsByName.TryGetValue(param.Name, out existingMember)) { existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true); isInherited = true; } // There should be an error if we picked a member that is hidden // This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630 if (existingMember is null) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics)); } else if (existingMember is FieldSymbol { IsStatic: false } field && field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics); if (!isInherited || checkMemberNotHidden(field, param)) { existingOrAddedMembers.Add(field); } } else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop && prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { // There already exists a member corresponding to the candidate synthesized property. if (isInherited && prop.IsAbstract) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics)); } else if (!isInherited || checkMemberNotHidden(prop, param)) { // Deconstruct() is specified to simply assign from this property to the corresponding out parameter. existingOrAddedMembers.Add(prop); } } else { diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter, param.Locations[0], new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)), param.TypeWithAnnotations, param.Name); } void addProperty(SynthesizedRecordPropertySymbol property) { existingOrAddedMembers.Add(property); members.Add(property); Debug.Assert(property.GetMethod is object); Debug.Assert(property.SetMethod is object); members.Add(property.GetMethod); members.Add(property.SetMethod); members.Add(property.BackingField); builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal])); addedCount++; } } return existingOrAddedMembers.ToImmutableAndFree(); bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param) { if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name)) { diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol); return false; } return true; } } void addObjectEquals(MethodSymbol thisEquals) { members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics)); } MethodSymbol addGetHashCode(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectGetHashCode, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol getHashCode; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod)) { getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(getHashCode); } else { getHashCode = (MethodSymbol)existingHashCodeMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed) { diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode); } } return getHashCode; } PropertySymbol addEqualityContract() { Debug.Assert(isRecordClass); var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)), ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); PropertySymbol equalityContract; if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty)) { equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics); members.Add(equalityContract); members.Add(equalityContract.GetMethod); } else { equalityContract = (PropertySymbol)existingEqualityContractProperty; if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { if (equalityContract.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract); } } else if (equalityContract.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract); } if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions)) { if (!equalityContract.Type.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type); } } else { SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics); } if (equalityContract.GetMethod is null) { diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract); } reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics); } return equalityContract; } MethodSymbol addThisEquals(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectEquals, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol thisEquals; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod)) { thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(thisEquals); } else { thisEquals = (MethodSymbol)existingEqualsMethod; if (thisEquals.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals); } if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType); } reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics); } return thisEquals; } void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics) { if (isRecordClass && !IsSealed && ((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed)) { diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol); } else if (symbol.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol); } } void addBaseEquals() { Debug.Assert(isRecordClass); if (!BaseTypeNoUseSiteDiagnostics.IsObjectType()) { members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics)); } } void addEqualityOperators() { members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics)); members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics)); } } private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { //we're not calling the helpers on NamedTypeSymbol base, because those call //GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow) var hasInstanceConstructor = false; var hasParameterlessInstanceConstructor = false; var hasStaticConstructor = false; // CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the // dictionary construction process. For now, this is more encapsulated. var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); foreach (var member in membersSoFar) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; switch (method.MethodKind) { case MethodKind.Constructor: // Ignore the record copy constructor if (!IsRecord || !(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor)) { hasInstanceConstructor = true; hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0; } break; case MethodKind.StaticConstructor: hasStaticConstructor = true; break; } } //kick out early if we've seen everything we're looking for if (hasInstanceConstructor && hasStaticConstructor) { break; } } // NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor". // We won't insert a parameterless constructor for a struct if there already is one. // The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table. if ((!hasParameterlessInstanceConstructor && this.IsStructType()) || (!hasInstanceConstructor && !this.IsStatic && !this.IsInterface)) { builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ? new SynthesizedSubmissionConstructor(this, diagnostics) : new SynthesizedInstanceConstructor(this), declaredMembersAndInitializers); } // constants don't count, since they do not exist as fields at runtime // NOTE: even for decimal constants (which require field initializers), // we do not create .cctor here since a static constructor implicitly created for a decimal // should not appear in the list returned by public API like GetMembers(). if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers)) { // Note: we don't have to put anything in the method - the binder will // do that when processing field initializers. builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers); } if (this.IsScriptClass) { var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics); builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers); var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics); builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers); } static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst)); } } private void AddSynthesizedTupleMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers) { if (!this.IsTupleType) { return; } var synthesizedMembers = this.MakeSynthesizedTupleMembers(declaredMembersAndInitializers.NonTypeMembers); if (synthesizedMembers is null) { return; } foreach (var synthesizedMember in synthesizedMembers) { builder.AddNonTypeMember(synthesizedMember, declaredMembersAndInitializers); } synthesizedMembers.Free(); } private void AddNonTypeMembers( DeclaredMembersAndInitializersBuilder builder, SyntaxList<MemberDeclarationSyntax> members, BindingDiagnosticBag diagnostics) { if (members.Count == 0) { return; } var firstMember = members[0]; var bodyBinder = this.GetBinder(firstMember); ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null; ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null; var compilation = DeclaringCompilation; foreach (var m in members) { if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } bool reportMisplacedGlobalCode = !m.HasErrors; switch (m.Kind()) { case SyntaxKind.FieldDeclaration: { var fieldSyntax = (FieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier)); } bool modifierErrors; var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors); foreach (var variable in fieldSyntax.Declaration.Variables) { var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0 ? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics) : new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics); builder.NonTypeMembers.Add(fieldSymbol); // All fields are included in the nullable context for constructors and initializers, even fields without // initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker. builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable); if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this, DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static), fieldSymbol); } if (variable.Initializer != null) { if (fieldSymbol.IsStatic) { AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer); } else { AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer); } } } } break; case SyntaxKind.MethodDeclaration: { var methodSyntax = (MethodDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(methodSyntax.Identifier)); } var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.ConstructorDeclaration: { var constructorSyntax = (ConstructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(constructorSyntax.Identifier)); } bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax); var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics); builder.NonTypeMembers.Add(constructor); if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer) { builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled); } } break; case SyntaxKind.DestructorDeclaration: { var destructorSyntax = (DestructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(destructorSyntax.Identifier)); } // CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the // runtime won't consider it a finalizer and it will not be marked as a destructor // when it is loaded from metadata. Perhaps we should just treat it as an Ordinary // method in such cases? var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics); builder.NonTypeMembers.Add(destructor); } break; case SyntaxKind.PropertyDeclaration: { var propertySyntax = (PropertyDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(propertySyntax.Identifier)); } var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics); builder.NonTypeMembers.Add(property); AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod); FieldSymbol backingField = property.BackingField; // TODO: can we leave this out of the member list? // From the 10/12/11 design notes: // In addition, we will change autoproperties to behavior in // a similar manner and make the autoproperty fields private. if ((object)backingField != null) { builder.NonTypeMembers.Add(backingField); builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax); var initializer = propertySyntax.Initializer; if (initializer != null) { if (IsScriptClass) { // also gather expression-declared variables from the initializer ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, initializer, this, DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0), backingField); } if (property.IsStatic) { AddInitializer(ref staticInitializers, backingField, initializer); } else { AddInitializer(ref instanceInitializers, backingField, initializer); } } } } break; case SyntaxKind.EventFieldDeclaration: { var eventFieldSyntax = (EventFieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add( ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier)); } foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables) { SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics); builder.NonTypeMembers.Add(@event); FieldSymbol? associatedField = @event.AssociatedField; if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this, DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0), associatedField); } if ((object?)associatedField != null) { // NOTE: specifically don't add the associated field to the members list // (regard it as an implementation detail). builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator); if (declarator.Initializer != null) { if (associatedField.IsStatic) { AddInitializer(ref staticInitializers, associatedField, declarator.Initializer); } else { AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer); } } } Debug.Assert((object)@event.AddMethod != null); Debug.Assert((object)@event.RemoveMethod != null); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); } } break; case SyntaxKind.EventDeclaration: { var eventSyntax = (EventDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventSyntax.Identifier)); } var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics); builder.NonTypeMembers.Add(@event); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); Debug.Assert(@event.AssociatedField is null); } break; case SyntaxKind.IndexerDeclaration: { var indexerSyntax = (IndexerDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(indexerSyntax.ThisKeyword)); } var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics); builder.HaveIndexers = true; builder.NonTypeMembers.Add(indexer); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod); } break; case SyntaxKind.ConversionOperatorDeclaration: { var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(conversionOperatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol( this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.OperatorDeclaration: { var operatorSyntax = (OperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(operatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol( this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.GlobalStatement: { var globalStatement = ((GlobalStatementSyntax)m).Statement; if (IsScriptClass) { var innerStatement = globalStatement; // drill into any LabeledStatements while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: // We shouldn't reach this place, but field declarations preceded with a label end up here. // This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now. var decl = (LocalDeclarationStatementSyntax)innerStatement; foreach (var vdecl in decl.Declaration.Variables) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private, containingFieldOpt: null); } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, innerStatement, this, DeclarationModifiers.Private, containingFieldOpt: null); break; default: // no other statement introduces variables into the enclosing scope break; } AddInitializer(ref instanceInitializers, null, globalStatement); } else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m)) { diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement)); } } break; default: Debug.Assert( SyntaxFacts.IsTypeDeclaration(m.Kind()) || m.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration or SyntaxKind.IncompleteMember); break; } } AddInitializers(builder.InstanceInitializers, instanceInitializers); AddInitializers(builder.StaticInitializers, staticInitializers); } private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt) { if (!(accessorOpt is null)) { symbols.Add(accessorOpt); } } internal override byte? GetLocalNullableContextValue() { byte? value; if (!_flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); _flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); var baseType = BaseTypeNoUseSiteDiagnostics; if (baseType is object) { builder.AddValue(TypeWithAnnotations.Create(baseType)); } foreach (var @interface in GetInterfacesToEmit()) { builder.AddValue(TypeWithAnnotations.Create(@interface)); } foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } foreach (var member in GetMembersUnordered()) { member.GetCommonNullableValues(compilation, ref builder); } // Not including lambdas or local functions. return builder.MostCommonValue; } /// <summary> /// Returns true if the overall nullable context is enabled for constructors and initializers. /// </summary> /// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param> internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic) { var membersAndInitializers = GetMembersAndInitializers(); return useStatic ? membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields : membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = DeclaringCompilation; NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (baseType is object) { if (baseType.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0)); } if (baseType.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType)); } if (baseType.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType)); } } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (baseType is object) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType))); } } } #endregion #region Extension Methods internal bool ContainsExtensionMethods { get { if (!_lazyContainsExtensionMethods.HasValue()) { bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods; _lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } } internal bool AnyMemberHasAttributes { get { if (!_lazyAnyMemberHasAttributes.HasValue()) { bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes; _lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState(); } return _lazyAnyMemberHasAttributes.Value(); } } public override bool MightContainExtensionMethods { get { return this.ContainsExtensionMethods; } } #endregion public sealed override NamedTypeSymbol ConstructedFrom { get { return this; } } internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0; internal class SynthesizedExplicitImplementations { public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty); public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods; public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls; private SynthesizedExplicitImplementations( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { ForwardingMethods = forwardingMethods.NullToEmpty(); MethodImpls = methodImpls.NullToEmpty(); } internal static SynthesizedExplicitImplementations Create( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty) { return Empty; } return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls); } } } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/SubstitutedNamedTypeSymbol.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.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Either a SubstitutedNestedTypeSymbol or a ConstructedNamedTypeSymbol, which share in common that they /// have type parameters substituted. /// </summary> internal abstract class SubstitutedNamedTypeSymbol : WrappedNamedTypeSymbol { private static readonly Func<Symbol, NamedTypeSymbol, Symbol> s_symbolAsMemberFunc = SymbolExtensions.SymbolAsMember; private readonly bool _unbound; private readonly TypeMap _inputMap; // The container of a substituted named type symbol is typically a named type or a namespace. // However, in some error-recovery scenarios it might be some other container. For example, // consider "int Goo = 123; Goo<string> x = null;" What is the type of x? We construct an error // type symbol of arity one associated with local variable symbol Goo; when we construct // that error type symbol with <string>, the resulting substituted named type symbol has // the same containing symbol as the local: it is contained in the method. private readonly Symbol _newContainer; private TypeMap _lazyMap; private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; // computed on demand private int _hashCode; // lazily created, does not need to be unique private ConcurrentCache<string, ImmutableArray<Symbol>> _lazyMembersByNameCache; protected SubstitutedNamedTypeSymbol(Symbol newContainer, TypeMap map, NamedTypeSymbol originalDefinition, NamedTypeSymbol constructedFrom = null, bool unbound = false, TupleExtraData tupleData = null) : base(originalDefinition, tupleData) { Debug.Assert(originalDefinition.IsDefinition); Debug.Assert(!originalDefinition.IsErrorType()); _newContainer = newContainer; _inputMap = map; _unbound = unbound; // if we're substituting to create a new unconstructed type as a member of a constructed type, // then we must alpha rename the type parameters. if ((object)constructedFrom != null) { Debug.Assert(ReferenceEquals(constructedFrom.ConstructedFrom, constructedFrom)); _lazyTypeParameters = constructedFrom.TypeParameters; _lazyMap = map; } } public sealed override bool IsUnboundGenericType { get { return _unbound; } } private TypeMap Map { get { EnsureMapAndTypeParameters(); return _lazyMap; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { EnsureMapAndTypeParameters(); return _lazyTypeParameters; } } private void EnsureMapAndTypeParameters() { if (!_lazyTypeParameters.IsDefault) { return; } ImmutableArray<TypeParameterSymbol> typeParameters; // We're creating a new unconstructed Method from another; alpha-rename type parameters. var newMap = _inputMap.WithAlphaRename(OriginalDefinition, this, out typeParameters); var prevMap = Interlocked.CompareExchange(ref _lazyMap, newMap, null); if (prevMap != null) { // There is a race with another thread who has already set the map // need to ensure that typeParameters, matches the map typeParameters = prevMap.SubstituteTypeParameters(OriginalDefinition.TypeParameters); } ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, typeParameters, default(ImmutableArray<TypeParameterSymbol>)); Debug.Assert(_lazyTypeParameters != null); } public sealed override Symbol ContainingSymbol { get { return _newContainer; } } public override NamedTypeSymbol ContainingType { get { return _newContainer as NamedTypeSymbol; } } public sealed override SymbolKind Kind { get { return OriginalDefinition.Kind; } } public sealed override NamedTypeSymbol OriginalDefinition { get { return _underlyingType; } } internal sealed override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) { return _unbound ? null : Map.SubstituteNamedType(OriginalDefinition.GetDeclaredBaseType(basesBeingResolved)); } internal sealed override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) { return _unbound ? ImmutableArray<NamedTypeSymbol>.Empty : Map.SubstituteNamedTypes(OriginalDefinition.GetDeclaredInterfaces(basesBeingResolved)); } internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => _unbound ? null : Map.SubstituteNamedType(OriginalDefinition.BaseTypeNoUseSiteDiagnostics); internal sealed override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { return _unbound ? ImmutableArray<NamedTypeSymbol>.Empty : Map.SubstituteNamedTypes(OriginalDefinition.InterfacesNoUseSiteDiagnostics(basesBeingResolved)); } internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { throw ExceptionUtilities.Unreachable; } internal abstract override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); public sealed override IEnumerable<string> MemberNames { get { if (_unbound) { return new List<string>(GetTypeMembersUnordered().Select(s => s.Name).Distinct()); } if (IsTupleType) { return GetMembers().Select(s => s.Name).Distinct(); } return OriginalDefinition.MemberNames; } } public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return OriginalDefinition.GetAttributes(); } internal sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return OriginalDefinition.GetTypeMembersUnordered().SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return OriginalDefinition.GetTypeMembers().SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return OriginalDefinition.GetTypeMembers(name).SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return OriginalDefinition.GetTypeMembers(name, arity).SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<Symbol> GetMembers() { var builder = ArrayBuilder<Symbol>.GetInstance(); if (_unbound) { // Preserve order of members. foreach (var t in OriginalDefinition.GetMembers()) { if (t.Kind == SymbolKind.NamedType) { builder.Add(((NamedTypeSymbol)t).AsMember(this)); } } } else { foreach (var t in OriginalDefinition.GetMembers()) { builder.Add(t.SymbolAsMember(this)); } } if (IsTupleType) { builder = AddOrWrapTupleMembers(builder.ToImmutableAndFree()); Debug.Assert(builder is object); } return builder.ToImmutableAndFree(); } internal sealed override ImmutableArray<Symbol> GetMembersUnordered() { var builder = ArrayBuilder<Symbol>.GetInstance(); if (_unbound) { foreach (var t in OriginalDefinition.GetMembersUnordered()) { if (t.Kind == SymbolKind.NamedType) { builder.Add(((NamedTypeSymbol)t).AsMember(this)); } } } else { foreach (var t in OriginalDefinition.GetMembersUnordered()) { builder.Add(t.SymbolAsMember(this)); } } if (IsTupleType) { builder = AddOrWrapTupleMembers(builder.ToImmutableAndFree()); Debug.Assert(builder is object); } return builder.ToImmutableAndFree(); } public sealed override ImmutableArray<Symbol> GetMembers(string name) { if (_unbound) return StaticCast<Symbol>.From(GetTypeMembers(name)); ImmutableArray<Symbol> result; var cache = _lazyMembersByNameCache; if (cache != null && cache.TryGetValue(name, out result)) { return result; } return GetMembersWorker(name); } private ImmutableArray<Symbol> GetMembersWorker(string name) { if (IsTupleType) { var result = GetMembers().WhereAsArray((m, name) => m.Name == name, name); cacheResult(result); return result; } var originalMembers = OriginalDefinition.GetMembers(name); if (originalMembers.IsDefaultOrEmpty) { return originalMembers; } var builder = ArrayBuilder<Symbol>.GetInstance(originalMembers.Length); foreach (var t in originalMembers) { builder.Add(t.SymbolAsMember(this)); } var substitutedMembers = builder.ToImmutableAndFree(); cacheResult(substitutedMembers); return substitutedMembers; void cacheResult(ImmutableArray<Symbol> result) { // cache of size 8 seems reasonable here. // considering that substituted methods have about 10 reference fields, // reusing just one may make the cache profitable. var cache = _lazyMembersByNameCache ?? (_lazyMembersByNameCache = new ConcurrentCache<string, ImmutableArray<Symbol>>(8)); cache.TryAdd(name, result); } } #nullable enable internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { if (_unbound) { yield break; } foreach ((MethodSymbol body, MethodSymbol implemented) in OriginalDefinition.SynthesizedInterfaceMethodImpls()) { var newBody = ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementation(body, this.TypeSubstitution); var newImplemented = ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementation(implemented, this.TypeSubstitution); yield return (newBody, newImplemented); } } #nullable disable internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return _unbound ? GetMembers() : OriginalDefinition.GetEarlyAttributeDecodingMembers().SelectAsArray(s_symbolAsMemberFunc, this); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { if (_unbound) return GetMembers(name); var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var t in OriginalDefinition.GetEarlyAttributeDecodingMembers(name)) { builder.Add(t.SymbolAsMember(this)); } return builder.ToImmutableAndFree(); } public sealed override NamedTypeSymbol EnumUnderlyingType { get { return OriginalDefinition.EnumUnderlyingType; } } public override int GetHashCode() { if (_hashCode == 0) { _hashCode = this.ComputeHashCode(); } return _hashCode; } internal sealed override TypeMap TypeSubstitution { get { return this.Map; } } internal sealed override bool IsComImport { get { return OriginalDefinition.IsComImport; } } internal sealed override NamedTypeSymbol ComImportCoClass { get { return OriginalDefinition.ComImportCoClass; } } internal override IEnumerable<MethodSymbol> GetMethodsToEmit() { throw ExceptionUtilities.Unreachable; } internal override IEnumerable<EventSymbol> GetEventsToEmit() { throw ExceptionUtilities.Unreachable; } internal override IEnumerable<PropertySymbol> GetPropertiesToEmit() { throw ExceptionUtilities.Unreachable; } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { throw ExceptionUtilities.Unreachable; } internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override bool IsRecord => _underlyingType.IsRecord; internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct; internal sealed override bool HasPossibleWellKnownCloneMethod() => _underlyingType.HasPossibleWellKnownCloneMethod(); } }
// 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.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Either a SubstitutedNestedTypeSymbol or a ConstructedNamedTypeSymbol, which share in common that they /// have type parameters substituted. /// </summary> internal abstract class SubstitutedNamedTypeSymbol : WrappedNamedTypeSymbol { private static readonly Func<Symbol, NamedTypeSymbol, Symbol> s_symbolAsMemberFunc = SymbolExtensions.SymbolAsMember; private readonly bool _unbound; private readonly TypeMap _inputMap; // The container of a substituted named type symbol is typically a named type or a namespace. // However, in some error-recovery scenarios it might be some other container. For example, // consider "int Goo = 123; Goo<string> x = null;" What is the type of x? We construct an error // type symbol of arity one associated with local variable symbol Goo; when we construct // that error type symbol with <string>, the resulting substituted named type symbol has // the same containing symbol as the local: it is contained in the method. private readonly Symbol _newContainer; private TypeMap _lazyMap; private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; // computed on demand private int _hashCode; // lazily created, does not need to be unique private ConcurrentCache<string, ImmutableArray<Symbol>> _lazyMembersByNameCache; protected SubstitutedNamedTypeSymbol(Symbol newContainer, TypeMap map, NamedTypeSymbol originalDefinition, NamedTypeSymbol constructedFrom = null, bool unbound = false, TupleExtraData tupleData = null) : base(originalDefinition, tupleData) { Debug.Assert(originalDefinition.IsDefinition); Debug.Assert(!originalDefinition.IsErrorType()); _newContainer = newContainer; _inputMap = map; _unbound = unbound; // if we're substituting to create a new unconstructed type as a member of a constructed type, // then we must alpha rename the type parameters. if ((object)constructedFrom != null) { Debug.Assert(ReferenceEquals(constructedFrom.ConstructedFrom, constructedFrom)); _lazyTypeParameters = constructedFrom.TypeParameters; _lazyMap = map; } } public sealed override bool IsUnboundGenericType { get { return _unbound; } } private TypeMap Map { get { EnsureMapAndTypeParameters(); return _lazyMap; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { EnsureMapAndTypeParameters(); return _lazyTypeParameters; } } private void EnsureMapAndTypeParameters() { if (!_lazyTypeParameters.IsDefault) { return; } ImmutableArray<TypeParameterSymbol> typeParameters; // We're creating a new unconstructed Method from another; alpha-rename type parameters. var newMap = _inputMap.WithAlphaRename(OriginalDefinition, this, out typeParameters); var prevMap = Interlocked.CompareExchange(ref _lazyMap, newMap, null); if (prevMap != null) { // There is a race with another thread who has already set the map // need to ensure that typeParameters, matches the map typeParameters = prevMap.SubstituteTypeParameters(OriginalDefinition.TypeParameters); } ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters, typeParameters, default(ImmutableArray<TypeParameterSymbol>)); Debug.Assert(_lazyTypeParameters != null); } public sealed override Symbol ContainingSymbol { get { return _newContainer; } } public override NamedTypeSymbol ContainingType { get { return _newContainer as NamedTypeSymbol; } } public sealed override SymbolKind Kind { get { return OriginalDefinition.Kind; } } public sealed override NamedTypeSymbol OriginalDefinition { get { return _underlyingType; } } internal sealed override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) { return _unbound ? null : Map.SubstituteNamedType(OriginalDefinition.GetDeclaredBaseType(basesBeingResolved)); } internal sealed override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) { return _unbound ? ImmutableArray<NamedTypeSymbol>.Empty : Map.SubstituteNamedTypes(OriginalDefinition.GetDeclaredInterfaces(basesBeingResolved)); } internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => _unbound ? null : Map.SubstituteNamedType(OriginalDefinition.BaseTypeNoUseSiteDiagnostics); internal sealed override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { return _unbound ? ImmutableArray<NamedTypeSymbol>.Empty : Map.SubstituteNamedTypes(OriginalDefinition.InterfacesNoUseSiteDiagnostics(basesBeingResolved)); } internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { throw ExceptionUtilities.Unreachable; } internal abstract override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); public sealed override IEnumerable<string> MemberNames { get { if (_unbound) { return new List<string>(GetTypeMembersUnordered().Select(s => s.Name).Distinct()); } if (IsTupleType) { return GetMembers().Select(s => s.Name).Distinct(); } return OriginalDefinition.MemberNames; } } public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return OriginalDefinition.GetAttributes(); } internal sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return OriginalDefinition.GetTypeMembersUnordered().SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return OriginalDefinition.GetTypeMembers().SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return OriginalDefinition.GetTypeMembers(name).SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return OriginalDefinition.GetTypeMembers(name, arity).SelectAsArray((t, self) => t.AsMember(self), this); } public sealed override ImmutableArray<Symbol> GetMembers() { var builder = ArrayBuilder<Symbol>.GetInstance(); if (_unbound) { // Preserve order of members. foreach (var t in OriginalDefinition.GetMembers()) { if (t.Kind == SymbolKind.NamedType) { builder.Add(((NamedTypeSymbol)t).AsMember(this)); } } } else { foreach (var t in OriginalDefinition.GetMembers()) { builder.Add(t.SymbolAsMember(this)); } } builder = AddOrWrapTupleMembersIfNecessary(builder); return builder.ToImmutableAndFree(); } private ArrayBuilder<Symbol> AddOrWrapTupleMembersIfNecessary(ArrayBuilder<Symbol> builder) { if (IsTupleType) { var existingMembers = builder.ToImmutableAndFree(); var replacedFields = new HashSet<Symbol>(ReferenceEqualityComparer.Instance); builder = MakeSynthesizedTupleMembers(existingMembers, replacedFields); foreach (var existingMember in existingMembers) { // Note: fields for tuple elements have a tuple field symbol instead of a substituted field symbol if (!replacedFields.Contains(existingMember)) { builder.Add(existingMember); } } Debug.Assert(builder is object); } return builder; } internal sealed override ImmutableArray<Symbol> GetMembersUnordered() { var builder = ArrayBuilder<Symbol>.GetInstance(); if (_unbound) { foreach (var t in OriginalDefinition.GetMembersUnordered()) { if (t.Kind == SymbolKind.NamedType) { builder.Add(((NamedTypeSymbol)t).AsMember(this)); } } } else { foreach (var t in OriginalDefinition.GetMembersUnordered()) { builder.Add(t.SymbolAsMember(this)); } } builder = AddOrWrapTupleMembersIfNecessary(builder); return builder.ToImmutableAndFree(); } public sealed override ImmutableArray<Symbol> GetMembers(string name) { if (_unbound) return StaticCast<Symbol>.From(GetTypeMembers(name)); ImmutableArray<Symbol> result; var cache = _lazyMembersByNameCache; if (cache != null && cache.TryGetValue(name, out result)) { return result; } return GetMembersWorker(name); } private ImmutableArray<Symbol> GetMembersWorker(string name) { if (IsTupleType) { var result = GetMembers().WhereAsArray((m, name) => m.Name == name, name); cacheResult(result); return result; } var originalMembers = OriginalDefinition.GetMembers(name); if (originalMembers.IsDefaultOrEmpty) { return originalMembers; } var builder = ArrayBuilder<Symbol>.GetInstance(originalMembers.Length); foreach (var t in originalMembers) { builder.Add(t.SymbolAsMember(this)); } var substitutedMembers = builder.ToImmutableAndFree(); cacheResult(substitutedMembers); return substitutedMembers; void cacheResult(ImmutableArray<Symbol> result) { // cache of size 8 seems reasonable here. // considering that substituted methods have about 10 reference fields, // reusing just one may make the cache profitable. var cache = _lazyMembersByNameCache ?? (_lazyMembersByNameCache = new ConcurrentCache<string, ImmutableArray<Symbol>>(8)); cache.TryAdd(name, result); } } #nullable enable internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { if (_unbound) { yield break; } foreach ((MethodSymbol body, MethodSymbol implemented) in OriginalDefinition.SynthesizedInterfaceMethodImpls()) { var newBody = ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementation(body, this.TypeSubstitution); var newImplemented = ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementation(implemented, this.TypeSubstitution); yield return (newBody, newImplemented); } } #nullable disable internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return _unbound ? GetMembers() : OriginalDefinition.GetEarlyAttributeDecodingMembers().SelectAsArray(s_symbolAsMemberFunc, this); } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { if (_unbound) return GetMembers(name); var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var t in OriginalDefinition.GetEarlyAttributeDecodingMembers(name)) { builder.Add(t.SymbolAsMember(this)); } return builder.ToImmutableAndFree(); } public sealed override NamedTypeSymbol EnumUnderlyingType { get { return OriginalDefinition.EnumUnderlyingType; } } public override int GetHashCode() { if (_hashCode == 0) { _hashCode = this.ComputeHashCode(); } return _hashCode; } internal sealed override TypeMap TypeSubstitution { get { return this.Map; } } internal sealed override bool IsComImport { get { return OriginalDefinition.IsComImport; } } internal sealed override NamedTypeSymbol ComImportCoClass { get { return OriginalDefinition.ComImportCoClass; } } internal override IEnumerable<MethodSymbol> GetMethodsToEmit() { throw ExceptionUtilities.Unreachable; } internal override IEnumerable<EventSymbol> GetEventsToEmit() { throw ExceptionUtilities.Unreachable; } internal override IEnumerable<PropertySymbol> GetPropertiesToEmit() { throw ExceptionUtilities.Unreachable; } internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { throw ExceptionUtilities.Unreachable; } internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override bool IsRecord => _underlyingType.IsRecord; internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct; internal sealed override bool HasPossibleWellKnownCloneMethod() => _underlyingType.HasPossibleWellKnownCloneMethod(); } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPrintMembers.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.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The `bool PrintMembers(StringBuilder)` method is responsible for printing members declared /// in the containing type that are "printable" (public fields and properties), /// and delegating to the base to print inherited printable members. Base members get printed first. /// It returns true if the record contains some printable members. /// The method is used to implement `ToString()`. /// </summary> internal sealed class SynthesizedRecordPrintMembers : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordPrintMembers( SourceMemberContainerTypeSymbol containingType, IEnumerable<Symbol> userDefinedMembers, int memberOffset, BindingDiagnosticBag diagnostics) : base( containingType, WellKnownMemberNames.PrintMembersMethodName, isReadOnly: IsReadOnly(containingType, userDefinedMembers), hasBody: true, memberOffset: memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var result = (ContainingType.IsRecordStruct || (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() && ContainingType.IsSealed)) ? DeclarationModifiers.Private : DeclarationModifiers.Protected; if (ContainingType.IsRecord && !ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { result |= DeclarationModifiers.Override; } else { result |= ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual; } Debug.Assert((result & ~allowedModifiers) == 0); #if DEBUG Debug.Assert(modifiersAreValid(result)); #endif return result; #if DEBUG bool modifiersAreValid(DeclarationModifiers modifiers) { if (ContainingType.IsRecordStruct) { return modifiers == DeclarationModifiers.Private; } if ((modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Private && (modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Protected) { return false; } modifiers &= ~DeclarationModifiers.AccessibilityMask; switch (modifiers) { case DeclarationModifiers.None: case DeclarationModifiers.Override: case DeclarationModifiers.Virtual: return true; default: return false; } } #endif } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; var annotation = ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.NotAnnotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(Binder.GetWellKnownType(compilation, WellKnownType.System_Text_StringBuilder, diagnostics, location), annotation), ordinal: 0, RefKind.None, "builder", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { ImmutableArray<Symbol> printableMembers = ContainingType.GetMembers().WhereAsArray(m => isPrintable(m)); if (ReturnType.IsErrorType() || printableMembers.Any(m => m.GetTypeOrReturnType().Type.IsErrorType())) { F.CloseMethod(F.ThrowNull()); return; } ArrayBuilder<BoundStatement> block; BoundParameter builder = F.Parameter(this.Parameters[0]); if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() || ContainingType.IsRecordStruct) { if (printableMembers.IsEmpty) { // return false; F.CloseMethod(F.Return(F.Literal(false))); return; } block = ArrayBuilder<BoundStatement>.GetInstance(); if (!ContainingType.IsRecordStruct) { var ensureStackMethod = F.WellKnownMethod( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack, isOptional: true); if (ensureStackMethod is not null) { block.Add(F.ExpressionStatement( F.Call(receiver: null, ensureStackMethod))); } } } else { MethodSymbol? basePrintMethod = OverriddenMethod; if (basePrintMethod is null || basePrintMethod.ReturnType.SpecialType != SpecialType.System_Boolean) { F.CloseMethod(F.ThrowNull()); // an error was reported in base checks already return; } var basePrintCall = F.Call(receiver: F.Base(ContainingType.BaseTypeNoUseSiteDiagnostics), basePrintMethod, builder); if (printableMembers.IsEmpty) { // return base.PrintMembers(builder); F.CloseMethod(F.Return(basePrintCall)); return; } else { block = ArrayBuilder<BoundStatement>.GetInstance(); // if (base.PrintMembers(builder)) // builder.Append(", ") block.Add(F.If(basePrintCall, makeAppendString(F, builder, ", "))); } } Debug.Assert(!printableMembers.IsEmpty); for (var i = 0; i < printableMembers.Length; i++) { // builder.Append(", <name> = "); // if previous members exist // builder.Append("<name> = "); // if it is the first member // The only printable members are fields and properties, // which cannot be generic so as to have variant names var member = printableMembers[i]; var memberHeader = $"{member.Name} = "; if (i > 0) { memberHeader = ", " + memberHeader; } block.Add(makeAppendString(F, builder, memberHeader)); var value = member.Kind switch { SymbolKind.Field => F.Field(F.This(), (FieldSymbol)member), SymbolKind.Property => F.Property(F.This(), (PropertySymbol)member), _ => throw ExceptionUtilities.UnexpectedValue(member.Kind) }; // builder.Append((object)<value>); OR builder.Append(<value>.ToString()); for value types Debug.Assert(value.Type is not null); if (value.Type.IsValueType) { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.Call(value, F.SpecialMethod(SpecialMember.System_Object__ToString))))); } else { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendObject), F.Convert(F.SpecialType(SpecialType.System_Object), value)))); } } block.Add(F.Return(F.Literal(true))); F.CloseMethod(F.Block(block.ToImmutableAndFree())); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundParameter builder, string value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.StringLiteral(value))); } static bool isPrintable(Symbol m) { if (!IsPublicInstanceMember(m)) { return false; } if (m.Kind is SymbolKind.Field) { return true; } if (m.Kind is SymbolKind.Property) { var property = (PropertySymbol)m; return IsPrintableProperty(property); } return false; } } internal static void VerifyOverridesPrintMembersFromBase(MethodSymbol overriding, BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = overriding.ContainingType.BaseTypeNoUseSiteDiagnostics; if (baseType.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(baseType, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, overriding.Locations[0], overriding, baseType); } } private static bool IsReadOnly(NamedTypeSymbol containingType, IEnumerable<Symbol> userDefinedMembers) { return containingType.IsReadOnly || (containingType.IsRecordStruct && AreAllPrintablePropertyGettersReadOnly(userDefinedMembers)); } private static bool AreAllPrintablePropertyGettersReadOnly(IEnumerable<Symbol> members) { foreach (var member in members) { if (member.Kind != SymbolKind.Property) { continue; } var property = (PropertySymbol)member; if (!IsPublicInstanceMember(property) || !IsPrintableProperty(property)) { continue; } var getterMethod = property.GetMethod; if (property.GetMethod is not null && !getterMethod.IsEffectivelyReadOnly) { return false; } } return true; } private static bool IsPublicInstanceMember(Symbol m) { return m.DeclaredAccessibility == Accessibility.Public && !m.IsStatic; } private static bool IsPrintableProperty(PropertySymbol property) { return !property.IsIndexer && !property.IsOverride && property.GetMethod is not 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The `bool PrintMembers(StringBuilder)` method is responsible for printing members declared /// in the containing type that are "printable" (public fields and properties), /// and delegating to the base to print inherited printable members. Base members get printed first. /// It returns true if the record contains some printable members. /// The method is used to implement `ToString()`. /// </summary> internal sealed class SynthesizedRecordPrintMembers : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordPrintMembers( SourceMemberContainerTypeSymbol containingType, IEnumerable<Symbol> userDefinedMembers, int memberOffset, BindingDiagnosticBag diagnostics) : base( containingType, WellKnownMemberNames.PrintMembersMethodName, isReadOnly: IsReadOnly(containingType, userDefinedMembers), hasBody: true, memberOffset: memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var result = (ContainingType.IsRecordStruct || (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() && ContainingType.IsSealed)) ? DeclarationModifiers.Private : DeclarationModifiers.Protected; if (ContainingType.IsRecord && !ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { result |= DeclarationModifiers.Override; } else { result |= ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual; } Debug.Assert((result & ~allowedModifiers) == 0); #if DEBUG Debug.Assert(modifiersAreValid(result)); #endif return result; #if DEBUG bool modifiersAreValid(DeclarationModifiers modifiers) { if (ContainingType.IsRecordStruct) { return modifiers == DeclarationModifiers.Private; } if ((modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Private && (modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Protected) { return false; } modifiers &= ~DeclarationModifiers.AccessibilityMask; switch (modifiers) { case DeclarationModifiers.None: case DeclarationModifiers.Override: case DeclarationModifiers.Virtual: return true; default: return false; } } #endif } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; var annotation = ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.NotAnnotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(Binder.GetWellKnownType(compilation, WellKnownType.System_Text_StringBuilder, diagnostics, location), annotation), ordinal: 0, RefKind.None, "builder", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { ImmutableArray<Symbol> printableMembers = ContainingType.GetMembers().WhereAsArray(m => isPrintable(m)); if (ReturnType.IsErrorType() || printableMembers.Any(m => m.GetTypeOrReturnType().Type.IsErrorType())) { F.CloseMethod(F.ThrowNull()); return; } ArrayBuilder<BoundStatement> block; BoundParameter builder = F.Parameter(this.Parameters[0]); if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() || ContainingType.IsRecordStruct) { if (printableMembers.IsEmpty) { // return false; F.CloseMethod(F.Return(F.Literal(false))); return; } block = ArrayBuilder<BoundStatement>.GetInstance(); if (!ContainingType.IsRecordStruct) { var ensureStackMethod = F.WellKnownMethod( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack, isOptional: true); if (ensureStackMethod is not null) { block.Add(F.ExpressionStatement( F.Call(receiver: null, ensureStackMethod))); } } } else { MethodSymbol? basePrintMethod = OverriddenMethod; if (basePrintMethod is null || basePrintMethod.ReturnType.SpecialType != SpecialType.System_Boolean) { F.CloseMethod(F.ThrowNull()); // an error was reported in base checks already return; } var basePrintCall = F.Call(receiver: F.Base(ContainingType.BaseTypeNoUseSiteDiagnostics), basePrintMethod, builder); if (printableMembers.IsEmpty) { // return base.PrintMembers(builder); F.CloseMethod(F.Return(basePrintCall)); return; } else { block = ArrayBuilder<BoundStatement>.GetInstance(); // if (base.PrintMembers(builder)) // builder.Append(", ") block.Add(F.If(basePrintCall, makeAppendString(F, builder, ", "))); } } Debug.Assert(!printableMembers.IsEmpty); for (var i = 0; i < printableMembers.Length; i++) { // builder.Append(", <name> = "); // if previous members exist // builder.Append("<name> = "); // if it is the first member // The only printable members are fields and properties, // which cannot be generic so as to have variant names var member = printableMembers[i]; var memberHeader = $"{member.Name} = "; if (i > 0) { memberHeader = ", " + memberHeader; } block.Add(makeAppendString(F, builder, memberHeader)); var value = member.Kind switch { SymbolKind.Field => F.Field(F.This(), (FieldSymbol)member), SymbolKind.Property => F.Property(F.This(), (PropertySymbol)member), _ => throw ExceptionUtilities.UnexpectedValue(member.Kind) }; // builder.Append((object)<value>); OR builder.Append(<value>.ToString()); for value types Debug.Assert(value.Type is not null); if (value.Type.IsValueType) { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.Call(value, F.SpecialMethod(SpecialMember.System_Object__ToString))))); } else { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendObject), F.Convert(F.SpecialType(SpecialType.System_Object), value)))); } } block.Add(F.Return(F.Literal(true))); F.CloseMethod(F.Block(block.ToImmutableAndFree())); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundParameter builder, string value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.StringLiteral(value))); } static bool isPrintable(Symbol m) { if (!IsPublicInstanceMember(m)) { return false; } if (m.Kind is SymbolKind.Field && m is not TupleErrorFieldSymbol) { return true; } if (m.Kind is SymbolKind.Property) { var property = (PropertySymbol)m; return IsPrintableProperty(property); } return false; } } internal static void VerifyOverridesPrintMembersFromBase(MethodSymbol overriding, BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = overriding.ContainingType.BaseTypeNoUseSiteDiagnostics; if (baseType.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(baseType, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, overriding.Locations[0], overriding, baseType); } } private static bool IsReadOnly(NamedTypeSymbol containingType, IEnumerable<Symbol> userDefinedMembers) { return containingType.IsReadOnly || (containingType.IsRecordStruct && AreAllPrintablePropertyGettersReadOnly(userDefinedMembers)); } private static bool AreAllPrintablePropertyGettersReadOnly(IEnumerable<Symbol> members) { foreach (var member in members) { if (member.Kind != SymbolKind.Property) { continue; } var property = (PropertySymbol)member; if (!IsPublicInstanceMember(property) || !IsPrintableProperty(property)) { continue; } var getterMethod = property.GetMethod; if (property.GetMethod is not null && !getterMethod.IsEffectivelyReadOnly) { return false; } } return true; } private static bool IsPublicInstanceMember(Symbol m) { return m.DeclaredAccessibility == Accessibility.Public && !m.IsStatic; } private static bool IsPrintableProperty(PropertySymbol property) { return !property.IsIndexer && !property.IsOverride && property.GetMethod is not null; } } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.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.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract partial class NamedTypeSymbol { internal const int ValueTupleRestPosition = 8; // The Rest field is in 8th position internal const int ValueTupleRestIndex = ValueTupleRestPosition - 1; internal const string ValueTupleTypeName = "ValueTuple"; internal const string ValueTupleRestFieldName = "Rest"; private TupleExtraData? _lazyTupleData; /// <summary> /// Helps create a tuple type from source. /// </summary> internal static NamedTypeSymbol CreateTuple( Location? locationOpt, ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations, ImmutableArray<Location?> elementLocations, ImmutableArray<string?> elementNames, CSharpCompilation compilation, bool shouldCheckConstraints, bool includeNullability, ImmutableArray<bool> errorPositions, CSharpSyntaxNode? syntax = null, BindingDiagnosticBag? diagnostics = null) { Debug.Assert(!shouldCheckConstraints || syntax is object); Debug.Assert(elementNames.IsDefault || elementTypesWithAnnotations.Length == elementNames.Length); Debug.Assert(!includeNullability || shouldCheckConstraints); int numElements = elementTypesWithAnnotations.Length; if (numElements <= 1) { throw ExceptionUtilities.Unreachable; } NamedTypeSymbol underlyingType = getTupleUnderlyingType(elementTypesWithAnnotations, syntax, compilation, diagnostics); if (numElements >= ValueTupleRestPosition && diagnostics != null && !underlyingType.IsErrorType()) { WellKnownMember wellKnownTupleRest = GetTupleTypeMember(ValueTupleRestPosition, ValueTupleRestPosition); _ = GetWellKnownMemberInType(underlyingType.OriginalDefinition, wellKnownTupleRest, diagnostics, syntax); } if (diagnostics?.DiagnosticBag is object && ((SourceModuleSymbol)compilation.SourceModule).AnyReferencedAssembliesAreLinked) { // Complain about unembeddable types from linked assemblies. Emit.NoPia.EmbeddedTypesManager.IsValidEmbeddableType(underlyingType, syntax, diagnostics.DiagnosticBag); } var locations = locationOpt is null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(locationOpt); var constructedType = CreateTuple(underlyingType, elementNames, errorPositions, elementLocations, locations); if (shouldCheckConstraints && diagnostics != null) { Debug.Assert(syntax is object); constructedType.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, compilation.Conversions, includeNullability, syntax.Location, diagnostics), syntax, elementLocations, nullabilityDiagnosticsOpt: includeNullability ? diagnostics : null); } return constructedType; // Produces the underlying ValueTuple corresponding to this list of element types. // Pass a null diagnostic bag and syntax node if you don't care about diagnostics. static NamedTypeSymbol getTupleUnderlyingType(ImmutableArray<TypeWithAnnotations> elementTypes, CSharpSyntaxNode? syntax, CSharpCompilation compilation, BindingDiagnosticBag? diagnostics) { int numElements = elementTypes.Length; int remainder; int chainLength = NumberOfValueTuples(numElements, out remainder); NamedTypeSymbol firstTupleType = compilation.GetWellKnownType(GetTupleType(remainder)); if (diagnostics is object && syntax is object) { ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, firstTupleType); } NamedTypeSymbol? chainedTupleType = null; if (chainLength > 1) { chainedTupleType = compilation.GetWellKnownType(GetTupleType(ValueTupleRestPosition)); if (diagnostics is object && syntax is object) { ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, chainedTupleType); } } return ConstructTupleUnderlyingType(firstTupleType, chainedTupleType, elementTypes); } } public static NamedTypeSymbol CreateTuple( NamedTypeSymbol tupleCompatibleType, ImmutableArray<string?> elementNames = default, ImmutableArray<bool> errorPositions = default, ImmutableArray<Location?> elementLocations = default, ImmutableArray<Location> locations = default) { Debug.Assert(tupleCompatibleType.IsTupleType); return tupleCompatibleType.WithElementNames(elementNames, elementLocations, errorPositions, locations); } internal NamedTypeSymbol WithTupleDataFrom(NamedTypeSymbol original) { if (!IsTupleType || (original._lazyTupleData == null && this._lazyTupleData == null) || TupleData!.EqualsIgnoringTupleUnderlyingType(original.TupleData)) { return this; } return WithElementNames(original.TupleElementNames, original.TupleElementLocations, original.TupleErrorPositions, original.Locations); } internal NamedTypeSymbol? TupleUnderlyingType => this._lazyTupleData != null ? this.TupleData!.TupleUnderlyingType : (this.IsTupleType ? this : null); /// <summary> /// Copy this tuple, but modify it to use the new element types. /// </summary> internal NamedTypeSymbol WithElementTypes(ImmutableArray<TypeWithAnnotations> newElementTypes) { Debug.Assert(TupleElementTypesWithAnnotations.Length == newElementTypes.Length); Debug.Assert(newElementTypes.All(t => t.HasType)); NamedTypeSymbol firstTupleType; NamedTypeSymbol? chainedTupleType; if (Arity < NamedTypeSymbol.ValueTupleRestPosition) { firstTupleType = OriginalDefinition; chainedTupleType = null; } else { chainedTupleType = OriginalDefinition; var underlyingType = this; do { underlyingType = ((NamedTypeSymbol)underlyingType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestIndex].Type); } while (underlyingType.Arity >= NamedTypeSymbol.ValueTupleRestPosition); firstTupleType = underlyingType.OriginalDefinition; } return CreateTuple( ConstructTupleUnderlyingType(firstTupleType, chainedTupleType, newElementTypes), elementNames: TupleElementNames, elementLocations: TupleElementLocations, errorPositions: TupleErrorPositions, locations: Locations); } /// <summary> /// Copy this tuple, but modify it to use the new element names. /// Also applies new location of the whole tuple as well as each element. /// Drops the inferred positions. /// </summary> internal NamedTypeSymbol WithElementNames(ImmutableArray<string?> newElementNames, ImmutableArray<Location?> newElementLocations, ImmutableArray<bool> errorPositions, ImmutableArray<Location> locations) { Debug.Assert(IsTupleType); Debug.Assert(newElementNames.IsDefault || this.TupleElementTypesWithAnnotations.Length == newElementNames.Length); return WithTupleData(new TupleExtraData(this.TupleUnderlyingType!, newElementNames, newElementLocations, errorPositions, locations)); } private NamedTypeSymbol WithTupleData(TupleExtraData newData) { Debug.Assert(IsTupleType); if (newData.EqualsIgnoringTupleUnderlyingType(TupleData)) { return this; } if (this.IsDefinition) { if (newData.ElementNames.IsDefault) { // We don't want to modify the definition unless we're adding names return this; } // This is for the rare case of making a tuple with names inside the definition of a ValueTuple type // We don't want to call Construct here, as it has a shortcut that would return `this`, thus causing a loop return this.ConstructCore(this.GetTypeParametersAsTypeArguments(), unbound: false).WithTupleData(newData); } return WithTupleDataCore(newData); } protected abstract NamedTypeSymbol WithTupleDataCore(TupleExtraData newData); /// <summary> /// Decompose the underlying tuple type into its links and store them into the underlyingTupleTypeChain. /// /// For instance, ValueTuple&lt;..., ValueTuple&lt; int >> (the underlying type for an 8-tuple) /// will be decomposed into two links: the first one is the entire thing, and the second one is the ValueTuple&lt; int > /// </summary> internal static void GetUnderlyingTypeChain(NamedTypeSymbol underlyingTupleType, ArrayBuilder<NamedTypeSymbol> underlyingTupleTypeChain) { NamedTypeSymbol currentType = underlyingTupleType; while (true) { underlyingTupleTypeChain.Add(currentType); if (currentType.Arity == NamedTypeSymbol.ValueTupleRestPosition) { currentType = (NamedTypeSymbol)currentType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestPosition - 1].Type; } else { break; } } } /// <summary> /// Returns the number of nestings required to represent numElements as nested ValueTuples. /// For example, for 8 elements, you need 2 ValueTuples and the remainder (ie the size of the last nested ValueTuple) is 1. /// </summary> private static int NumberOfValueTuples(int numElements, out int remainder) { remainder = (numElements - 1) % (ValueTupleRestPosition - 1) + 1; return (numElements - 1) / (ValueTupleRestPosition - 1) + 1; } private static NamedTypeSymbol ConstructTupleUnderlyingType(NamedTypeSymbol firstTupleType, NamedTypeSymbol? chainedTupleTypeOpt, ImmutableArray<TypeWithAnnotations> elementTypes) { Debug.Assert(chainedTupleTypeOpt is null == elementTypes.Length < ValueTupleRestPosition); int numElements = elementTypes.Length; int remainder; int chainLength = NumberOfValueTuples(numElements, out remainder); NamedTypeSymbol currentSymbol = firstTupleType.Construct(ImmutableArray.Create(elementTypes, (chainLength - 1) * (ValueTupleRestPosition - 1), remainder)); int loop = chainLength - 1; while (loop > 0) { var chainedTypes = ImmutableArray.Create(elementTypes, (loop - 1) * (ValueTupleRestPosition - 1), ValueTupleRestPosition - 1).Add(TypeWithAnnotations.Create(currentSymbol)); currentSymbol = chainedTupleTypeOpt!.Construct(chainedTypes); loop--; } return currentSymbol; } private static void ReportUseSiteAndObsoleteDiagnostics(CSharpSyntaxNode? syntax, BindingDiagnosticBag diagnostics, NamedTypeSymbol firstTupleType) { Binder.ReportUseSite(firstTupleType, diagnostics, syntax); Binder.ReportDiagnosticsIfObsoleteInternal(diagnostics, firstTupleType, syntax, firstTupleType.ContainingType, BinderFlags.None); } /// <summary> /// For tuples with no natural type, we still need to verify that an underlying type of proper arity exists, and report if otherwise. /// </summary> internal static void VerifyTupleTypePresent(int cardinality, CSharpSyntaxNode? syntax, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(diagnostics is object && syntax is object); int remainder; int chainLength = NumberOfValueTuples(cardinality, out remainder); NamedTypeSymbol firstTupleType = compilation.GetWellKnownType(GetTupleType(remainder)); ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, firstTupleType); if (chainLength > 1) { NamedTypeSymbol chainedTupleType = compilation.GetWellKnownType(GetTupleType(ValueTupleRestPosition)); ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, chainedTupleType); } } internal static void ReportTupleNamesMismatchesIfAny(TypeSymbol destination, BoundTupleLiteral literal, BindingDiagnosticBag diagnostics) { var sourceNames = literal.ArgumentNamesOpt; if (sourceNames.IsDefault) { return; } ImmutableArray<bool> inferredNames = literal.InferredNamesOpt; bool noInferredNames = inferredNames.IsDefault; ImmutableArray<string> destinationNames = destination.TupleElementNames; int sourceLength = sourceNames.Length; bool allMissing = destinationNames.IsDefault; Debug.Assert(allMissing || destinationNames.Length == sourceLength); for (int i = 0; i < sourceLength; i++) { var sourceName = sourceNames[i]; var wasInferred = noInferredNames ? false : inferredNames[i]; if (sourceName != null && !wasInferred && (allMissing || string.CompareOrdinal(destinationNames[i], sourceName) != 0)) { diagnostics.Add(ErrorCode.WRN_TupleLiteralNameMismatch, literal.Arguments[i].Syntax.Parent!.Location, sourceName, destination); } } } /// <summary> /// Find the well-known ValueTuple type of a given arity. /// For example, for arity=2: /// returns WellKnownType.System_ValueTuple_T2 /// </summary> private static WellKnownType GetTupleType(int arity) { if (arity > ValueTupleRestPosition) { throw ExceptionUtilities.Unreachable; } return tupleTypes[arity - 1]; } private static readonly WellKnownType[] tupleTypes = { WellKnownType.System_ValueTuple_T1, WellKnownType.System_ValueTuple_T2, WellKnownType.System_ValueTuple_T3, WellKnownType.System_ValueTuple_T4, WellKnownType.System_ValueTuple_T5, WellKnownType.System_ValueTuple_T6, WellKnownType.System_ValueTuple_T7, WellKnownType.System_ValueTuple_TRest }; /// <summary> /// Find the constructor for a well-known ValueTuple type of a given arity. /// /// For example, for arity=2: /// returns WellKnownMember.System_ValueTuple_T2__ctor /// /// For arity=12: /// return System_ValueTuple_TRest__ctor /// </summary> internal static WellKnownMember GetTupleCtor(int arity) { if (arity > 8) { throw ExceptionUtilities.Unreachable; } return tupleCtors[arity - 1]; } private static readonly WellKnownMember[] tupleCtors = { WellKnownMember.System_ValueTuple_T1__ctor, WellKnownMember.System_ValueTuple_T2__ctor, WellKnownMember.System_ValueTuple_T3__ctor, WellKnownMember.System_ValueTuple_T4__ctor, WellKnownMember.System_ValueTuple_T5__ctor, WellKnownMember.System_ValueTuple_T6__ctor, WellKnownMember.System_ValueTuple_T7__ctor, WellKnownMember.System_ValueTuple_TRest__ctor }; /// <summary> /// Find the well-known members to the ValueTuple type of a given arity and position. /// For example, for arity=3 and position=1: /// returns WellKnownMember.System_ValueTuple_T3__Item1 /// </summary> internal static WellKnownMember GetTupleTypeMember(int arity, int position) { return tupleMembers[arity - 1][position - 1]; } private static readonly WellKnownMember[][] tupleMembers = new[]{ new[]{ WellKnownMember.System_ValueTuple_T1__Item1 }, new[]{ WellKnownMember.System_ValueTuple_T2__Item1, WellKnownMember.System_ValueTuple_T2__Item2 }, new[]{ WellKnownMember.System_ValueTuple_T3__Item1, WellKnownMember.System_ValueTuple_T3__Item2, WellKnownMember.System_ValueTuple_T3__Item3 }, new[]{ WellKnownMember.System_ValueTuple_T4__Item1, WellKnownMember.System_ValueTuple_T4__Item2, WellKnownMember.System_ValueTuple_T4__Item3, WellKnownMember.System_ValueTuple_T4__Item4 }, new[]{ WellKnownMember.System_ValueTuple_T5__Item1, WellKnownMember.System_ValueTuple_T5__Item2, WellKnownMember.System_ValueTuple_T5__Item3, WellKnownMember.System_ValueTuple_T5__Item4, WellKnownMember.System_ValueTuple_T5__Item5 }, new[]{ WellKnownMember.System_ValueTuple_T6__Item1, WellKnownMember.System_ValueTuple_T6__Item2, WellKnownMember.System_ValueTuple_T6__Item3, WellKnownMember.System_ValueTuple_T6__Item4, WellKnownMember.System_ValueTuple_T6__Item5, WellKnownMember.System_ValueTuple_T6__Item6 }, new[]{ WellKnownMember.System_ValueTuple_T7__Item1, WellKnownMember.System_ValueTuple_T7__Item2, WellKnownMember.System_ValueTuple_T7__Item3, WellKnownMember.System_ValueTuple_T7__Item4, WellKnownMember.System_ValueTuple_T7__Item5, WellKnownMember.System_ValueTuple_T7__Item6, WellKnownMember.System_ValueTuple_T7__Item7 }, new[]{ WellKnownMember.System_ValueTuple_TRest__Item1, WellKnownMember.System_ValueTuple_TRest__Item2, WellKnownMember.System_ValueTuple_TRest__Item3, WellKnownMember.System_ValueTuple_TRest__Item4, WellKnownMember.System_ValueTuple_TRest__Item5, WellKnownMember.System_ValueTuple_TRest__Item6, WellKnownMember.System_ValueTuple_TRest__Item7, WellKnownMember.System_ValueTuple_TRest__Rest } }; /// <summary> /// Returns "Item1" for position=1 /// Returns "Item12" for position=12 /// </summary> internal static string TupleMemberName(int position) { return "Item" + position; } /// <summary> /// Checks whether the field name is reserved and tells us which position it's reserved for. /// /// For example: /// Returns 3 for "Item3". /// Returns 0 for "Rest", "ToString" and other members of System.ValueTuple. /// Returns -1 for names that aren't reserved. /// </summary> internal static int IsTupleElementNameReserved(string name) { if (isElementNameForbidden(name)) { return 0; } return matchesCanonicalElementName(name); static bool isElementNameForbidden(string name) { switch (name) { case "CompareTo": case WellKnownMemberNames.DeconstructMethodName: case "Equals": case "GetHashCode": case "Rest": case "ToString": return true; default: return false; } } // Returns 3 for "Item3". // Returns -1 otherwise. static int matchesCanonicalElementName(string name) { if (name.StartsWith("Item", StringComparison.Ordinal)) { string tail = name.Substring(4); if (int.TryParse(tail, out int number)) { if (number > 0 && string.Equals(name, TupleMemberName(number), StringComparison.Ordinal)) { return number; } } } return -1; } } /// <summary> /// Lookup well-known member declaration in provided type and reports diagnostics. /// </summary> internal static Symbol? GetWellKnownMemberInType(NamedTypeSymbol type, WellKnownMember relativeMember, BindingDiagnosticBag diagnostics, SyntaxNode? syntax) { Symbol? member = GetWellKnownMemberInType(type, relativeMember); if (member is null) { MemberDescriptor relativeDescriptor = WellKnownMembers.GetDescriptor(relativeMember); Binder.Error(diagnostics, ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, syntax, relativeDescriptor.Name, type, type.ContainingAssembly); } else { UseSiteInfo<AssemblySymbol> useSiteInfo = member.GetUseSiteInfo(); if (useSiteInfo.DiagnosticInfo?.Severity != DiagnosticSeverity.Error) { useSiteInfo = useSiteInfo.AdjustDiagnosticInfo(null); } diagnostics.Add(useSiteInfo, syntax?.GetLocation() ?? Location.None); } return member; // Lookup well-known member declaration in provided type. // // If a well-known member of a generic type instantiation is needed use this method to get the corresponding generic definition and // <see cref="MethodSymbol.AsMember"/> to construct an instantiation. // // <param name="type">Type that we'll try to find member in.</param> // <param name="relativeMember">A reference to a well-known member type descriptor. Note however that the type in that descriptor is ignored here.</param> static Symbol? GetWellKnownMemberInType(NamedTypeSymbol type, WellKnownMember relativeMember) { Debug.Assert(relativeMember >= WellKnownMember.System_ValueTuple_T1__Item1 && relativeMember <= WellKnownMember.System_ValueTuple_TRest__ctor); Debug.Assert(type.IsDefinition); MemberDescriptor relativeDescriptor = WellKnownMembers.GetDescriptor(relativeMember); var members = type.GetMembers(relativeDescriptor.Name); return CSharpCompilation.GetRuntimeMember(members, relativeDescriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); // force lookup of public members only } } public sealed override bool IsTupleType => IsTupleTypeOfCardinality(tupleCardinality: out _); internal TupleExtraData? TupleData { get { if (!IsTupleType) { return null; } if (_lazyTupleData is null) { Interlocked.CompareExchange(ref _lazyTupleData, new TupleExtraData(this), null); } return _lazyTupleData; } } public sealed override ImmutableArray<string?> TupleElementNames => _lazyTupleData is null ? default : _lazyTupleData.ElementNames; private ImmutableArray<bool> TupleErrorPositions => _lazyTupleData is null ? default : _lazyTupleData.ErrorPositions; private ImmutableArray<Location?> TupleElementLocations => _lazyTupleData is null ? default : _lazyTupleData.ElementLocations; public sealed override ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => IsTupleType ? TupleData!.TupleElementTypesWithAnnotations(this) : default; public sealed override ImmutableArray<FieldSymbol> TupleElements => IsTupleType ? TupleData!.TupleElements(this) : default; /// <summary> /// For tuple fields that aren't TupleElementFieldSymbol or TupleErrorFieldSymbol, we cache their tuple element index. /// This supports <see cref="FieldSymbol.TupleElementIndex"/>. /// For those fields, we map from their definition to an index. /// </summary> public SmallDictionary<FieldSymbol, int>? TupleFieldDefinitionsToIndexMap { get { if (!IsTupleType) { return null; } if (!IsDefinition) { return this.OriginalDefinition.TupleFieldDefinitionsToIndexMap; } return TupleData!.GetFieldDefinitionsToIndexMap(this); } } public virtual void InitializeTupleFieldDefinitionsToIndexMap() { Debug.Assert(this.IsTupleType); Debug.Assert(this.IsDefinition); // we only store a map for definitions _ = this.GetMembers(); } public TMember? GetTupleMemberSymbolForUnderlyingMember<TMember>(TMember? underlyingMemberOpt) where TMember : Symbol { return IsTupleType ? TupleData!.GetTupleMemberSymbolForUnderlyingMember(underlyingMemberOpt) : null; } protected ArrayBuilder<Symbol> AddOrWrapTupleMembers(ImmutableArray<Symbol> currentMembers) { Debug.Assert(IsTupleType); Debug.Assert(currentMembers.All(m => !(m is TupleVirtualElementFieldSymbol))); var elementTypes = TupleElementTypesWithAnnotations; var elementsMatchedByFields = ArrayBuilder<bool>.GetInstance(elementTypes.Length, fillWithValue: false); var members = ArrayBuilder<Symbol>.GetInstance(currentMembers.Length); var nonFieldMembers = ArrayBuilder<Symbol>.GetInstance(); // For tuple fields that aren't TupleElementFieldSymbol or TupleErrorFieldSymbol, we cache/map their tuple element index // corresponding to their definition. We only need to do that for the definition of ValueTuple types. var fieldDefinitionsToIndexMap = IsDefinition ? new SmallDictionary<FieldSymbol, int>(ReferenceEqualityComparer.Instance) : null; NamedTypeSymbol currentValueTuple = this; int currentNestingLevel = 0; var currentFieldsForElements = ArrayBuilder<FieldSymbol?>.GetInstance(currentValueTuple.Arity); // Lookup field definitions that we are interested in collectTargetTupleFields(currentValueTuple.Arity, getOriginalFields(currentMembers), currentFieldsForElements); var elementNames = TupleElementNames; var elementLocations = TupleData!.ElementLocations; while (true) { foreach (Symbol member in currentMembers) { switch (member.Kind) { case SymbolKind.Field: var field = (FieldSymbol)member; if (field is TupleVirtualElementFieldSymbol) { // In a long tuple situation where the nested tuple has names, we don't care about those names. // We will re-add all necessary virtual element field symbols below. continue; } var underlyingField = field is TupleElementFieldSymbol tupleElement ? tupleElement.UnderlyingField.OriginalDefinition : field.OriginalDefinition; int tupleFieldIndex = currentFieldsForElements.IndexOf(underlyingField, ReferenceEqualityComparer.Instance); if (underlyingField is TupleErrorFieldSymbol) { // We will re-add all necessary error field symbols below. continue; } else if (tupleFieldIndex >= 0) { // adjust tuple index for nesting if (currentNestingLevel != 0) { tupleFieldIndex += (ValueTupleRestPosition - 1) * currentNestingLevel; } var providedName = elementNames.IsDefault ? null : elementNames[tupleFieldIndex]; ImmutableArray<Location> locations = getElementLocations(in elementLocations, tupleFieldIndex); var defaultName = TupleMemberName(tupleFieldIndex + 1); // if provided name does not match the default one, // then default element is declared implicitly var defaultImplicitlyDeclared = providedName != defaultName; // Add a field with default name. It should be present regardless. FieldSymbol defaultTupleField; var fieldSymbol = underlyingField.AsMember(currentValueTuple); if (currentNestingLevel != 0) { // This is a matching field, but it is in the extension tuple // Make it virtual since we are not at the top level defaultTupleField = new TupleVirtualElementFieldSymbol(this, fieldSymbol, defaultName, tupleFieldIndex, locations, cannotUse: false, isImplicitlyDeclared: defaultImplicitlyDeclared, correspondingDefaultFieldOpt: null); } else { Debug.Assert(fieldSymbol.Name == defaultName, "top level underlying field must match default name"); if (IsDefinition) { defaultTupleField = field; fieldDefinitionsToIndexMap!.Add(field, tupleFieldIndex); } else { // Add the underlying/real field as an element (wrapping mainly to capture location). It should have the default name. defaultTupleField = new TupleElementFieldSymbol(this, fieldSymbol, tupleFieldIndex, locations, isImplicitlyDeclared: defaultImplicitlyDeclared); } } members.Add(defaultTupleField); if (defaultImplicitlyDeclared && !string.IsNullOrEmpty(providedName)) { var errorPositions = TupleErrorPositions; var isError = errorPositions.IsDefault ? false : errorPositions[tupleFieldIndex]; // The name given doesn't match the default name Item8, etc. // Add a virtual field with the given name members.Add(new TupleVirtualElementFieldSymbol(this, fieldSymbol, providedName, tupleFieldIndex, locations, cannotUse: isError, isImplicitlyDeclared: false, correspondingDefaultFieldOpt: defaultTupleField)); } elementsMatchedByFields[tupleFieldIndex] = true; // mark as handled } else if (currentNestingLevel == 0) { // No need to wrap other real fields members.Add(field); } break; case SymbolKind.NamedType: // We are dropping nested types, if any. Pending real need. break; case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: if (currentNestingLevel == 0) { nonFieldMembers.Add(member); } break; default: if (currentNestingLevel == 0) { throw ExceptionUtilities.UnexpectedValue(member.Kind); } break; } } if (currentValueTuple.Arity != ValueTupleRestPosition) { break; } var oldUnderlying = currentValueTuple; currentValueTuple = (NamedTypeSymbol)oldUnderlying.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestIndex].Type; currentNestingLevel++; if (currentValueTuple.Arity != ValueTupleRestPosition) { // refresh members and target fields currentMembers = currentValueTuple.GetMembers(); currentFieldsForElements.Clear(); collectTargetTupleFields(currentValueTuple.Arity, getOriginalFields(currentMembers), currentFieldsForElements); } else { Debug.Assert((object)oldUnderlying.OriginalDefinition == currentValueTuple.OriginalDefinition); } } currentFieldsForElements.Free(); // At the end, add unmatched fields as error symbols for (int i = 0; i < elementsMatchedByFields.Count; i++) { if (!elementsMatchedByFields[i]) { // We couldn't find a backing field for this element. It will be an error to access it. int fieldRemainder; // one-based int fieldChainLength = NumberOfValueTuples(i + 1, out fieldRemainder); NamedTypeSymbol container = getNestedTupleUnderlyingType(this, fieldChainLength - 1).OriginalDefinition; var diagnosticInfo = container.IsErrorType() ? null : new CSDiagnosticInfo(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, TupleMemberName(fieldRemainder), container, container.ContainingAssembly); var providedName = elementNames.IsDefault ? null : elementNames[i]; var location = elementLocations.IsDefault ? null : elementLocations[i]; var defaultName = TupleMemberName(i + 1); // if provided name does not match the default one, // then default element is declared implicitly var defaultImplicitlyDeclared = providedName != defaultName; // Add a field with default name. It should be present regardless. TupleErrorFieldSymbol defaultTupleField = new TupleErrorFieldSymbol(this, defaultName, i, defaultImplicitlyDeclared ? null : location, elementTypes[i], diagnosticInfo, defaultImplicitlyDeclared, correspondingDefaultFieldOpt: null); members.Add(defaultTupleField); if (defaultImplicitlyDeclared && !String.IsNullOrEmpty(providedName)) { // Add friendly named element field. members.Add(new TupleErrorFieldSymbol(this, providedName, i, location, elementTypes[i], diagnosticInfo, isImplicitlyDeclared: false, correspondingDefaultFieldOpt: defaultTupleField)); } } } elementsMatchedByFields.Free(); members.AddRange(nonFieldMembers); nonFieldMembers.Free(); if (fieldDefinitionsToIndexMap is object) { this.TupleData!.SetFieldDefinitionsToIndexMap(fieldDefinitionsToIndexMap); } return members; // Returns the nested type at a certain depth. // // For depth=0, just return the tuple type as-is. // For depth=1, returns the nested tuple type at position 8. static NamedTypeSymbol getNestedTupleUnderlyingType(NamedTypeSymbol topLevelUnderlyingType, int depth) { NamedTypeSymbol found = topLevelUnderlyingType; for (int i = 0; i < depth; i++) { found = (NamedTypeSymbol)found.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type; } return found; } static void collectTargetTupleFields(int arity, ImmutableArray<Symbol> members, ArrayBuilder<FieldSymbol?> fieldsForElements) { int fieldsPerType = Math.Min(arity, ValueTupleRestPosition - 1); for (int i = 0; i < fieldsPerType; i++) { WellKnownMember wellKnownTupleField = GetTupleTypeMember(arity, i + 1); fieldsForElements.Add((FieldSymbol?)GetWellKnownMemberInType(members, wellKnownTupleField)); } } static Symbol? GetWellKnownMemberInType(ImmutableArray<Symbol> members, WellKnownMember relativeMember) { Debug.Assert(relativeMember >= WellKnownMember.System_ValueTuple_T1__Item1 && relativeMember <= WellKnownMember.System_ValueTuple_TRest__ctor); MemberDescriptor relativeDescriptor = WellKnownMembers.GetDescriptor(relativeMember); return CSharpCompilation.GetRuntimeMember(members, relativeDescriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); // force lookup of public members only } static ImmutableArray<Symbol> getOriginalFields(ImmutableArray<Symbol> members) { var fields = ArrayBuilder<Symbol>.GetInstance(); foreach (var member in members) { if (member is TupleVirtualElementFieldSymbol) { continue; } else if (member is TupleElementFieldSymbol tupleField) { fields.Add(tupleField.UnderlyingField.OriginalDefinition); } else if (member is FieldSymbol field) { fields.Add(field.OriginalDefinition); } } Debug.Assert(fields.All(f => f is object)); return fields.ToImmutableAndFree(); } static ImmutableArray<Location> getElementLocations(in ImmutableArray<Location?> elementLocations, int tupleFieldIndex) { if (elementLocations.IsDefault) { return ImmutableArray<Location>.Empty; } var elementLocation = elementLocations[tupleFieldIndex]; return elementLocation == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(elementLocation); } } private TypeSymbol MergeTupleNames(NamedTypeSymbol other, NamedTypeSymbol mergedType) { // Merge tuple element names, if any ImmutableArray<string?> names1 = TupleElementNames; ImmutableArray<string?> names2 = other.TupleElementNames; ImmutableArray<string?> mergedNames; if (names1.IsDefault || names2.IsDefault) { mergedNames = default; } else { Debug.Assert(names1.Length == names2.Length); mergedNames = names1.ZipAsArray(names2, (n1, n2) => string.CompareOrdinal(n1, n2) == 0 ? n1 : null)!; if (mergedNames.All(n => n is null)) { mergedNames = default; } } bool namesUnchanged = mergedNames.IsDefault ? TupleElementNames.IsDefault : mergedNames.SequenceEqual(TupleElementNames); return (namesUnchanged && this.Equals(mergedType, TypeCompareKind.ConsiderEverything)) ? this : CreateTuple(mergedType, mergedNames, this.TupleErrorPositions, this.TupleElementLocations, this.Locations); } /// <summary> /// The main purpose of this type is to store element names and also cache some information related to tuples. /// </summary> internal sealed class TupleExtraData { /// <summary> /// Element names, if provided. /// </summary> internal ImmutableArray<string?> ElementNames { get; } /// <summary> /// Declaration locations for individual elements, if provided. /// Declaration location for this tuple type symbol /// </summary> internal ImmutableArray<Location?> ElementLocations { get; } /// <summary> /// Which element names were inferred and therefore cannot be used. /// If none of the element names were inferred, or inferred names can be used (no tracking necessary), leave as default. /// This information is ignored in type equality and comparison. /// </summary> internal ImmutableArray<bool> ErrorPositions { get; } internal ImmutableArray<Location> Locations { get; } /// <summary> /// Element types. /// </summary> private ImmutableArray<TypeWithAnnotations> _lazyElementTypes; private ImmutableArray<FieldSymbol> _lazyDefaultElementFields; /// <summary> /// For tuple fields that aren't TupleElementFieldSymbol or TupleErrorFieldSymbol, we cache their tuple element index. /// This supports <see cref="FieldSymbol.TupleElementIndex"/>. /// For those fields, we map from their definition to an index. /// </summary> private SmallDictionary<FieldSymbol, int>? _lazyFieldDefinitionsToIndexMap; private SmallDictionary<Symbol, Symbol>? _lazyUnderlyingDefinitionToMemberMap; /// <summary> /// The same named type, but without element names. /// </summary> internal NamedTypeSymbol TupleUnderlyingType { get; } internal TupleExtraData(NamedTypeSymbol underlyingType) { RoslynDebug.Assert(underlyingType is object); Debug.Assert(underlyingType.IsTupleType); Debug.Assert(underlyingType.TupleElementNames.IsDefault); TupleUnderlyingType = underlyingType; Locations = ImmutableArray<Location>.Empty; } internal TupleExtraData(NamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<bool> errorPositions, ImmutableArray<Location> locations) : this(underlyingType) { ElementNames = elementNames; ElementLocations = elementLocations; ErrorPositions = errorPositions; Locations = locations.NullToEmpty(); } internal bool EqualsIgnoringTupleUnderlyingType(TupleExtraData? other) { if (other is null && this.ElementNames.IsDefault && this.ElementLocations.IsDefault && this.ErrorPositions.IsDefault) { return true; } return other is object && areEqual(this.ElementNames, other.ElementNames) && areEqual(this.ElementLocations, other.ElementLocations) && areEqual(this.ErrorPositions, other.ErrorPositions); static bool areEqual<T>(ImmutableArray<T> one, ImmutableArray<T> other) { if (one.IsDefault && other.IsDefault) { return true; } if (one.IsDefault != other.IsDefault) { return false; } return one.SequenceEqual(other); } } public ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations(NamedTypeSymbol tuple) { Debug.Assert(tuple.Equals(TupleUnderlyingType, TypeCompareKind.IgnoreTupleNames)); if (_lazyElementTypes.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyElementTypes, collectTupleElementTypesWithAnnotations(tuple)); } return _lazyElementTypes; static ImmutableArray<TypeWithAnnotations> collectTupleElementTypesWithAnnotations(NamedTypeSymbol tuple) { ImmutableArray<TypeWithAnnotations> elementTypes; if (tuple.Arity == ValueTupleRestPosition) { // Ensure all Rest extensions are tuples var extensionTupleElementTypes = tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type.TupleElementTypesWithAnnotations; var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(ValueTupleRestPosition - 1 + extensionTupleElementTypes.Length); typesBuilder.AddRange(tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, ValueTupleRestPosition - 1); typesBuilder.AddRange(extensionTupleElementTypes); elementTypes = typesBuilder.ToImmutableAndFree(); } else { elementTypes = tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; } return elementTypes; } } public ImmutableArray<FieldSymbol> TupleElements(NamedTypeSymbol tuple) { Debug.Assert(tuple.Equals(TupleUnderlyingType, TypeCompareKind.IgnoreTupleNames)); if (_lazyDefaultElementFields.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyDefaultElementFields, collectTupleElementFields(tuple)); } return _lazyDefaultElementFields; ImmutableArray<FieldSymbol> collectTupleElementFields(NamedTypeSymbol tuple) { var builder = ArrayBuilder<FieldSymbol>.GetInstance(TupleElementTypesWithAnnotations(tuple).Length, fillWithValue: null!); foreach (var member in tuple.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var candidate = (FieldSymbol)member; var index = candidate.TupleElementIndex; if (index >= 0) { if (builder[index]?.IsDefaultTupleElement != false) { builder[index] = candidate; } else { // there is a better field in the slot // that can only happen if the candidate is default. Debug.Assert(candidate.IsDefaultTupleElement); } } } Debug.Assert(builder.All(f => f is object)); return builder.ToImmutableAndFree(); } } internal SmallDictionary<FieldSymbol, int> GetFieldDefinitionsToIndexMap(NamedTypeSymbol tuple) { Debug.Assert(tuple.IsTupleType); Debug.Assert(tuple.IsDefinition); // we only store a map for definitions if (_lazyFieldDefinitionsToIndexMap is null) { tuple.InitializeTupleFieldDefinitionsToIndexMap(); } Debug.Assert(_lazyFieldDefinitionsToIndexMap is object); return _lazyFieldDefinitionsToIndexMap; } internal void SetFieldDefinitionsToIndexMap(SmallDictionary<FieldSymbol, int> map) { Debug.Assert(map.Keys.All(k => k.IsDefinition)); Debug.Assert(map.Values.All(v => v >= 0)); Interlocked.CompareExchange(ref _lazyFieldDefinitionsToIndexMap, map, null); } internal SmallDictionary<Symbol, Symbol> UnderlyingDefinitionToMemberMap { get { return _lazyUnderlyingDefinitionToMemberMap ??= computeDefinitionToMemberMap(); SmallDictionary<Symbol, Symbol> computeDefinitionToMemberMap() { var map = new SmallDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); var members = TupleUnderlyingType.GetMembers(); // Go in reverse because we want members with default name, which precede the ones with // friendly names, to be in the map. for (int i = members.Length - 1; i >= 0; i--) { var member = members[i]; switch (member.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.NamedType: map.Add(member.OriginalDefinition, member); break; case SymbolKind.Field: var tupleUnderlyingField = ((FieldSymbol)member).TupleUnderlyingField; if (tupleUnderlyingField is object) { map[tupleUnderlyingField.OriginalDefinition] = member; } break; case SymbolKind.Event: var underlyingEvent = (EventSymbol)member; var underlyingAssociatedField = underlyingEvent.AssociatedField; // The field is not part of the members list if (underlyingAssociatedField is object) { Debug.Assert((object)underlyingAssociatedField.ContainingSymbol == TupleUnderlyingType); Debug.Assert(TupleUnderlyingType.GetMembers(underlyingAssociatedField.Name).IndexOf(underlyingAssociatedField) < 0); map.Add(underlyingAssociatedField.OriginalDefinition, underlyingAssociatedField); } map.Add(underlyingEvent.OriginalDefinition, member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } return map; } } } public TMember? GetTupleMemberSymbolForUnderlyingMember<TMember>(TMember? underlyingMemberOpt) where TMember : Symbol { if (underlyingMemberOpt is null) { return null; } Symbol underlyingMemberDefinition = underlyingMemberOpt.OriginalDefinition; if (underlyingMemberDefinition is TupleElementFieldSymbol tupleField) { underlyingMemberDefinition = tupleField.UnderlyingField; } if (TypeSymbol.Equals(underlyingMemberDefinition.ContainingType, TupleUnderlyingType.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if (UnderlyingDefinitionToMemberMap.TryGetValue(underlyingMemberDefinition, out Symbol? result)) { return (TMember)result; } } 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract partial class NamedTypeSymbol { internal const int ValueTupleRestPosition = 8; // The Rest field is in 8th position internal const int ValueTupleRestIndex = ValueTupleRestPosition - 1; internal const string ValueTupleTypeName = "ValueTuple"; internal const string ValueTupleRestFieldName = "Rest"; private TupleExtraData? _lazyTupleData; /// <summary> /// Helps create a tuple type from source. /// </summary> internal static NamedTypeSymbol CreateTuple( Location? locationOpt, ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations, ImmutableArray<Location?> elementLocations, ImmutableArray<string?> elementNames, CSharpCompilation compilation, bool shouldCheckConstraints, bool includeNullability, ImmutableArray<bool> errorPositions, CSharpSyntaxNode? syntax = null, BindingDiagnosticBag? diagnostics = null) { Debug.Assert(!shouldCheckConstraints || syntax is object); Debug.Assert(elementNames.IsDefault || elementTypesWithAnnotations.Length == elementNames.Length); Debug.Assert(!includeNullability || shouldCheckConstraints); int numElements = elementTypesWithAnnotations.Length; if (numElements <= 1) { throw ExceptionUtilities.Unreachable; } NamedTypeSymbol underlyingType = getTupleUnderlyingType(elementTypesWithAnnotations, syntax, compilation, diagnostics); if (numElements >= ValueTupleRestPosition && diagnostics != null && !underlyingType.IsErrorType()) { WellKnownMember wellKnownTupleRest = GetTupleTypeMember(ValueTupleRestPosition, ValueTupleRestPosition); _ = GetWellKnownMemberInType(underlyingType.OriginalDefinition, wellKnownTupleRest, diagnostics, syntax); } if (diagnostics?.DiagnosticBag is object && ((SourceModuleSymbol)compilation.SourceModule).AnyReferencedAssembliesAreLinked) { // Complain about unembeddable types from linked assemblies. Emit.NoPia.EmbeddedTypesManager.IsValidEmbeddableType(underlyingType, syntax, diagnostics.DiagnosticBag); } var locations = locationOpt is null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(locationOpt); var constructedType = CreateTuple(underlyingType, elementNames, errorPositions, elementLocations, locations); if (shouldCheckConstraints && diagnostics != null) { Debug.Assert(syntax is object); constructedType.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, compilation.Conversions, includeNullability, syntax.Location, diagnostics), syntax, elementLocations, nullabilityDiagnosticsOpt: includeNullability ? diagnostics : null); } return constructedType; // Produces the underlying ValueTuple corresponding to this list of element types. // Pass a null diagnostic bag and syntax node if you don't care about diagnostics. static NamedTypeSymbol getTupleUnderlyingType(ImmutableArray<TypeWithAnnotations> elementTypes, CSharpSyntaxNode? syntax, CSharpCompilation compilation, BindingDiagnosticBag? diagnostics) { int numElements = elementTypes.Length; int remainder; int chainLength = NumberOfValueTuples(numElements, out remainder); NamedTypeSymbol firstTupleType = compilation.GetWellKnownType(GetTupleType(remainder)); if (diagnostics is object && syntax is object) { ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, firstTupleType); } NamedTypeSymbol? chainedTupleType = null; if (chainLength > 1) { chainedTupleType = compilation.GetWellKnownType(GetTupleType(ValueTupleRestPosition)); if (diagnostics is object && syntax is object) { ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, chainedTupleType); } } return ConstructTupleUnderlyingType(firstTupleType, chainedTupleType, elementTypes); } } public static NamedTypeSymbol CreateTuple( NamedTypeSymbol tupleCompatibleType, ImmutableArray<string?> elementNames = default, ImmutableArray<bool> errorPositions = default, ImmutableArray<Location?> elementLocations = default, ImmutableArray<Location> locations = default) { Debug.Assert(tupleCompatibleType.IsTupleType); return tupleCompatibleType.WithElementNames(elementNames, elementLocations, errorPositions, locations); } internal NamedTypeSymbol WithTupleDataFrom(NamedTypeSymbol original) { if (!IsTupleType || (original._lazyTupleData == null && this._lazyTupleData == null) || TupleData!.EqualsIgnoringTupleUnderlyingType(original.TupleData)) { return this; } return WithElementNames(original.TupleElementNames, original.TupleElementLocations, original.TupleErrorPositions, original.Locations); } internal NamedTypeSymbol? TupleUnderlyingType => this._lazyTupleData != null ? this.TupleData!.TupleUnderlyingType : (this.IsTupleType ? this : null); /// <summary> /// Copy this tuple, but modify it to use the new element types. /// </summary> internal NamedTypeSymbol WithElementTypes(ImmutableArray<TypeWithAnnotations> newElementTypes) { Debug.Assert(TupleElementTypesWithAnnotations.Length == newElementTypes.Length); Debug.Assert(newElementTypes.All(t => t.HasType)); NamedTypeSymbol firstTupleType; NamedTypeSymbol? chainedTupleType; if (Arity < NamedTypeSymbol.ValueTupleRestPosition) { firstTupleType = OriginalDefinition; chainedTupleType = null; } else { chainedTupleType = OriginalDefinition; var underlyingType = this; do { underlyingType = ((NamedTypeSymbol)underlyingType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestIndex].Type); } while (underlyingType.Arity >= NamedTypeSymbol.ValueTupleRestPosition); firstTupleType = underlyingType.OriginalDefinition; } return CreateTuple( ConstructTupleUnderlyingType(firstTupleType, chainedTupleType, newElementTypes), elementNames: TupleElementNames, elementLocations: TupleElementLocations, errorPositions: TupleErrorPositions, locations: Locations); } /// <summary> /// Copy this tuple, but modify it to use the new element names. /// Also applies new location of the whole tuple as well as each element. /// Drops the inferred positions. /// </summary> internal NamedTypeSymbol WithElementNames(ImmutableArray<string?> newElementNames, ImmutableArray<Location?> newElementLocations, ImmutableArray<bool> errorPositions, ImmutableArray<Location> locations) { Debug.Assert(IsTupleType); Debug.Assert(newElementNames.IsDefault || this.TupleElementTypesWithAnnotations.Length == newElementNames.Length); return WithTupleData(new TupleExtraData(this.TupleUnderlyingType!, newElementNames, newElementLocations, errorPositions, locations)); } private NamedTypeSymbol WithTupleData(TupleExtraData newData) { Debug.Assert(IsTupleType); if (newData.EqualsIgnoringTupleUnderlyingType(TupleData)) { return this; } if (this.IsDefinition) { if (newData.ElementNames.IsDefault) { // We don't want to modify the definition unless we're adding names return this; } // This is for the rare case of making a tuple with names inside the definition of a ValueTuple type // We don't want to call Construct here, as it has a shortcut that would return `this`, thus causing a loop return this.ConstructCore(this.GetTypeParametersAsTypeArguments(), unbound: false).WithTupleData(newData); } return WithTupleDataCore(newData); } protected abstract NamedTypeSymbol WithTupleDataCore(TupleExtraData newData); /// <summary> /// Decompose the underlying tuple type into its links and store them into the underlyingTupleTypeChain. /// /// For instance, ValueTuple&lt;..., ValueTuple&lt; int >> (the underlying type for an 8-tuple) /// will be decomposed into two links: the first one is the entire thing, and the second one is the ValueTuple&lt; int > /// </summary> internal static void GetUnderlyingTypeChain(NamedTypeSymbol underlyingTupleType, ArrayBuilder<NamedTypeSymbol> underlyingTupleTypeChain) { NamedTypeSymbol currentType = underlyingTupleType; while (true) { underlyingTupleTypeChain.Add(currentType); if (currentType.Arity == NamedTypeSymbol.ValueTupleRestPosition) { currentType = (NamedTypeSymbol)currentType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestPosition - 1].Type; } else { break; } } } /// <summary> /// Returns the number of nestings required to represent numElements as nested ValueTuples. /// For example, for 8 elements, you need 2 ValueTuples and the remainder (ie the size of the last nested ValueTuple) is 1. /// </summary> private static int NumberOfValueTuples(int numElements, out int remainder) { remainder = (numElements - 1) % (ValueTupleRestPosition - 1) + 1; return (numElements - 1) / (ValueTupleRestPosition - 1) + 1; } private static NamedTypeSymbol ConstructTupleUnderlyingType(NamedTypeSymbol firstTupleType, NamedTypeSymbol? chainedTupleTypeOpt, ImmutableArray<TypeWithAnnotations> elementTypes) { Debug.Assert(chainedTupleTypeOpt is null == elementTypes.Length < ValueTupleRestPosition); int numElements = elementTypes.Length; int remainder; int chainLength = NumberOfValueTuples(numElements, out remainder); NamedTypeSymbol currentSymbol = firstTupleType.Construct(ImmutableArray.Create(elementTypes, (chainLength - 1) * (ValueTupleRestPosition - 1), remainder)); int loop = chainLength - 1; while (loop > 0) { var chainedTypes = ImmutableArray.Create(elementTypes, (loop - 1) * (ValueTupleRestPosition - 1), ValueTupleRestPosition - 1).Add(TypeWithAnnotations.Create(currentSymbol)); currentSymbol = chainedTupleTypeOpt!.Construct(chainedTypes); loop--; } return currentSymbol; } private static void ReportUseSiteAndObsoleteDiagnostics(CSharpSyntaxNode? syntax, BindingDiagnosticBag diagnostics, NamedTypeSymbol firstTupleType) { Binder.ReportUseSite(firstTupleType, diagnostics, syntax); Binder.ReportDiagnosticsIfObsoleteInternal(diagnostics, firstTupleType, syntax, firstTupleType.ContainingType, BinderFlags.None); } /// <summary> /// For tuples with no natural type, we still need to verify that an underlying type of proper arity exists, and report if otherwise. /// </summary> internal static void VerifyTupleTypePresent(int cardinality, CSharpSyntaxNode? syntax, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(diagnostics is object && syntax is object); int remainder; int chainLength = NumberOfValueTuples(cardinality, out remainder); NamedTypeSymbol firstTupleType = compilation.GetWellKnownType(GetTupleType(remainder)); ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, firstTupleType); if (chainLength > 1) { NamedTypeSymbol chainedTupleType = compilation.GetWellKnownType(GetTupleType(ValueTupleRestPosition)); ReportUseSiteAndObsoleteDiagnostics(syntax, diagnostics, chainedTupleType); } } internal static void ReportTupleNamesMismatchesIfAny(TypeSymbol destination, BoundTupleLiteral literal, BindingDiagnosticBag diagnostics) { var sourceNames = literal.ArgumentNamesOpt; if (sourceNames.IsDefault) { return; } ImmutableArray<bool> inferredNames = literal.InferredNamesOpt; bool noInferredNames = inferredNames.IsDefault; ImmutableArray<string> destinationNames = destination.TupleElementNames; int sourceLength = sourceNames.Length; bool allMissing = destinationNames.IsDefault; Debug.Assert(allMissing || destinationNames.Length == sourceLength); for (int i = 0; i < sourceLength; i++) { var sourceName = sourceNames[i]; var wasInferred = noInferredNames ? false : inferredNames[i]; if (sourceName != null && !wasInferred && (allMissing || string.CompareOrdinal(destinationNames[i], sourceName) != 0)) { diagnostics.Add(ErrorCode.WRN_TupleLiteralNameMismatch, literal.Arguments[i].Syntax.Parent!.Location, sourceName, destination); } } } /// <summary> /// Find the well-known ValueTuple type of a given arity. /// For example, for arity=2: /// returns WellKnownType.System_ValueTuple_T2 /// </summary> private static WellKnownType GetTupleType(int arity) { if (arity > ValueTupleRestPosition) { throw ExceptionUtilities.Unreachable; } return tupleTypes[arity - 1]; } private static readonly WellKnownType[] tupleTypes = { WellKnownType.System_ValueTuple_T1, WellKnownType.System_ValueTuple_T2, WellKnownType.System_ValueTuple_T3, WellKnownType.System_ValueTuple_T4, WellKnownType.System_ValueTuple_T5, WellKnownType.System_ValueTuple_T6, WellKnownType.System_ValueTuple_T7, WellKnownType.System_ValueTuple_TRest }; /// <summary> /// Find the constructor for a well-known ValueTuple type of a given arity. /// /// For example, for arity=2: /// returns WellKnownMember.System_ValueTuple_T2__ctor /// /// For arity=12: /// return System_ValueTuple_TRest__ctor /// </summary> internal static WellKnownMember GetTupleCtor(int arity) { if (arity > 8) { throw ExceptionUtilities.Unreachable; } return tupleCtors[arity - 1]; } private static readonly WellKnownMember[] tupleCtors = { WellKnownMember.System_ValueTuple_T1__ctor, WellKnownMember.System_ValueTuple_T2__ctor, WellKnownMember.System_ValueTuple_T3__ctor, WellKnownMember.System_ValueTuple_T4__ctor, WellKnownMember.System_ValueTuple_T5__ctor, WellKnownMember.System_ValueTuple_T6__ctor, WellKnownMember.System_ValueTuple_T7__ctor, WellKnownMember.System_ValueTuple_TRest__ctor }; /// <summary> /// Find the well-known members to the ValueTuple type of a given arity and position. /// For example, for arity=3 and position=1: /// returns WellKnownMember.System_ValueTuple_T3__Item1 /// </summary> internal static WellKnownMember GetTupleTypeMember(int arity, int position) { return tupleMembers[arity - 1][position - 1]; } private static readonly WellKnownMember[][] tupleMembers = new[]{ new[]{ WellKnownMember.System_ValueTuple_T1__Item1 }, new[]{ WellKnownMember.System_ValueTuple_T2__Item1, WellKnownMember.System_ValueTuple_T2__Item2 }, new[]{ WellKnownMember.System_ValueTuple_T3__Item1, WellKnownMember.System_ValueTuple_T3__Item2, WellKnownMember.System_ValueTuple_T3__Item3 }, new[]{ WellKnownMember.System_ValueTuple_T4__Item1, WellKnownMember.System_ValueTuple_T4__Item2, WellKnownMember.System_ValueTuple_T4__Item3, WellKnownMember.System_ValueTuple_T4__Item4 }, new[]{ WellKnownMember.System_ValueTuple_T5__Item1, WellKnownMember.System_ValueTuple_T5__Item2, WellKnownMember.System_ValueTuple_T5__Item3, WellKnownMember.System_ValueTuple_T5__Item4, WellKnownMember.System_ValueTuple_T5__Item5 }, new[]{ WellKnownMember.System_ValueTuple_T6__Item1, WellKnownMember.System_ValueTuple_T6__Item2, WellKnownMember.System_ValueTuple_T6__Item3, WellKnownMember.System_ValueTuple_T6__Item4, WellKnownMember.System_ValueTuple_T6__Item5, WellKnownMember.System_ValueTuple_T6__Item6 }, new[]{ WellKnownMember.System_ValueTuple_T7__Item1, WellKnownMember.System_ValueTuple_T7__Item2, WellKnownMember.System_ValueTuple_T7__Item3, WellKnownMember.System_ValueTuple_T7__Item4, WellKnownMember.System_ValueTuple_T7__Item5, WellKnownMember.System_ValueTuple_T7__Item6, WellKnownMember.System_ValueTuple_T7__Item7 }, new[]{ WellKnownMember.System_ValueTuple_TRest__Item1, WellKnownMember.System_ValueTuple_TRest__Item2, WellKnownMember.System_ValueTuple_TRest__Item3, WellKnownMember.System_ValueTuple_TRest__Item4, WellKnownMember.System_ValueTuple_TRest__Item5, WellKnownMember.System_ValueTuple_TRest__Item6, WellKnownMember.System_ValueTuple_TRest__Item7, WellKnownMember.System_ValueTuple_TRest__Rest } }; /// <summary> /// Returns "Item1" for position=1 /// Returns "Item12" for position=12 /// </summary> internal static string TupleMemberName(int position) { return "Item" + position; } /// <summary> /// Checks whether the field name is reserved and tells us which position it's reserved for. /// /// For example: /// Returns 3 for "Item3". /// Returns 0 for "Rest", "ToString" and other members of System.ValueTuple. /// Returns -1 for names that aren't reserved. /// </summary> internal static int IsTupleElementNameReserved(string name) { if (isElementNameForbidden(name)) { return 0; } return matchesCanonicalElementName(name); static bool isElementNameForbidden(string name) { switch (name) { case "CompareTo": case WellKnownMemberNames.DeconstructMethodName: case "Equals": case "GetHashCode": case "Rest": case "ToString": return true; default: return false; } } // Returns 3 for "Item3". // Returns -1 otherwise. static int matchesCanonicalElementName(string name) { if (name.StartsWith("Item", StringComparison.Ordinal)) { string tail = name.Substring(4); if (int.TryParse(tail, out int number)) { if (number > 0 && string.Equals(name, TupleMemberName(number), StringComparison.Ordinal)) { return number; } } } return -1; } } /// <summary> /// Lookup well-known member declaration in provided type and reports diagnostics. /// </summary> internal static Symbol? GetWellKnownMemberInType(NamedTypeSymbol type, WellKnownMember relativeMember, BindingDiagnosticBag diagnostics, SyntaxNode? syntax) { Symbol? member = GetWellKnownMemberInType(type, relativeMember); if (member is null) { MemberDescriptor relativeDescriptor = WellKnownMembers.GetDescriptor(relativeMember); Binder.Error(diagnostics, ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, syntax, relativeDescriptor.Name, type, type.ContainingAssembly); } else { UseSiteInfo<AssemblySymbol> useSiteInfo = member.GetUseSiteInfo(); if (useSiteInfo.DiagnosticInfo?.Severity != DiagnosticSeverity.Error) { useSiteInfo = useSiteInfo.AdjustDiagnosticInfo(null); } diagnostics.Add(useSiteInfo, syntax?.GetLocation() ?? Location.None); } return member; // Lookup well-known member declaration in provided type. // // If a well-known member of a generic type instantiation is needed use this method to get the corresponding generic definition and // <see cref="MethodSymbol.AsMember"/> to construct an instantiation. // // <param name="type">Type that we'll try to find member in.</param> // <param name="relativeMember">A reference to a well-known member type descriptor. Note however that the type in that descriptor is ignored here.</param> static Symbol? GetWellKnownMemberInType(NamedTypeSymbol type, WellKnownMember relativeMember) { Debug.Assert(relativeMember >= WellKnownMember.System_ValueTuple_T1__Item1 && relativeMember <= WellKnownMember.System_ValueTuple_TRest__ctor); Debug.Assert(type.IsDefinition); MemberDescriptor relativeDescriptor = WellKnownMembers.GetDescriptor(relativeMember); var members = type.GetMembers(relativeDescriptor.Name); return CSharpCompilation.GetRuntimeMember(members, relativeDescriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); // force lookup of public members only } } public sealed override bool IsTupleType => IsTupleTypeOfCardinality(tupleCardinality: out _); internal TupleExtraData? TupleData { get { if (!IsTupleType) { return null; } if (_lazyTupleData is null) { Interlocked.CompareExchange(ref _lazyTupleData, new TupleExtraData(this), null); } return _lazyTupleData; } } public sealed override ImmutableArray<string?> TupleElementNames => _lazyTupleData is null ? default : _lazyTupleData.ElementNames; private ImmutableArray<bool> TupleErrorPositions => _lazyTupleData is null ? default : _lazyTupleData.ErrorPositions; private ImmutableArray<Location?> TupleElementLocations => _lazyTupleData is null ? default : _lazyTupleData.ElementLocations; public sealed override ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => IsTupleType ? TupleData!.TupleElementTypesWithAnnotations(this) : default; public sealed override ImmutableArray<FieldSymbol> TupleElements => IsTupleType ? TupleData!.TupleElements(this) : default; /// <summary> /// For tuple fields that aren't TupleElementFieldSymbol or TupleErrorFieldSymbol, we cache their tuple element index. /// This supports <see cref="FieldSymbol.TupleElementIndex"/>. /// For those fields, we map from their definition to an index. /// </summary> public SmallDictionary<FieldSymbol, int>? TupleFieldDefinitionsToIndexMap { get { if (!IsTupleType) { return null; } if (!IsDefinition) { return this.OriginalDefinition.TupleFieldDefinitionsToIndexMap; } return TupleData!.GetFieldDefinitionsToIndexMap(this); } } public virtual void InitializeTupleFieldDefinitionsToIndexMap() { Debug.Assert(this.IsTupleType); Debug.Assert(this.IsDefinition); // we only store a map for definitions _ = this.GetMembers(); } public TMember? GetTupleMemberSymbolForUnderlyingMember<TMember>(TMember? underlyingMemberOpt) where TMember : Symbol { return IsTupleType ? TupleData!.GetTupleMemberSymbolForUnderlyingMember(underlyingMemberOpt) : null; } protected ArrayBuilder<Symbol> MakeSynthesizedTupleMembers(ImmutableArray<Symbol> currentMembers, HashSet<Symbol>? replacedFields = null) { Debug.Assert(IsTupleType); Debug.Assert(currentMembers.All(m => !(m is TupleVirtualElementFieldSymbol))); var elementTypes = TupleElementTypesWithAnnotations; var elementsMatchedByFields = ArrayBuilder<bool>.GetInstance(elementTypes.Length, fillWithValue: false); var members = ArrayBuilder<Symbol>.GetInstance(currentMembers.Length); // For tuple fields that aren't TupleElementFieldSymbol or TupleErrorFieldSymbol, we cache/map their tuple element index // corresponding to their definition. We only need to do that for the definition of ValueTuple types. var fieldDefinitionsToIndexMap = IsDefinition ? new SmallDictionary<FieldSymbol, int>(ReferenceEqualityComparer.Instance) : null; NamedTypeSymbol currentValueTuple = this; int currentNestingLevel = 0; var currentFieldsForElements = ArrayBuilder<FieldSymbol?>.GetInstance(currentValueTuple.Arity); // Lookup field definitions that we are interested in collectTargetTupleFields(currentValueTuple.Arity, getOriginalFields(currentMembers), currentFieldsForElements); var elementNames = TupleElementNames; var elementLocations = TupleData!.ElementLocations; while (true) { foreach (Symbol member in currentMembers) { switch (member.Kind) { case SymbolKind.Field: var field = (FieldSymbol)member; if (field is TupleVirtualElementFieldSymbol) { // In a long tuple situation where the nested tuple has names, we don't care about those names. // We will re-add all necessary virtual element field symbols below. replacedFields?.Add(field); continue; } var underlyingField = field is TupleElementFieldSymbol tupleElement ? tupleElement.UnderlyingField.OriginalDefinition : field.OriginalDefinition; int tupleFieldIndex = currentFieldsForElements.IndexOf(underlyingField, ReferenceEqualityComparer.Instance); if (underlyingField is TupleErrorFieldSymbol) { // We will re-add all necessary error field symbols below. replacedFields?.Add(field); continue; } else if (tupleFieldIndex >= 0) { // adjust tuple index for nesting if (currentNestingLevel != 0) { tupleFieldIndex += (ValueTupleRestPosition - 1) * currentNestingLevel; } else { replacedFields?.Add(field); } var providedName = elementNames.IsDefault ? null : elementNames[tupleFieldIndex]; ImmutableArray<Location> locations = getElementLocations(in elementLocations, tupleFieldIndex); var defaultName = TupleMemberName(tupleFieldIndex + 1); // if provided name does not match the default one, // then default element is declared implicitly var defaultImplicitlyDeclared = providedName != defaultName; // Add a field with default name. It should be present regardless. FieldSymbol defaultTupleField; var fieldSymbol = underlyingField.AsMember(currentValueTuple); if (currentNestingLevel != 0) { // This is a matching field, but it is in the extension tuple // Make it virtual since we are not at the top level defaultTupleField = new TupleVirtualElementFieldSymbol(this, fieldSymbol, defaultName, tupleFieldIndex, locations, cannotUse: false, isImplicitlyDeclared: defaultImplicitlyDeclared, correspondingDefaultFieldOpt: null); members.Add(defaultTupleField); } else { Debug.Assert(fieldSymbol.Name == defaultName, "top level underlying field must match default name"); if (IsDefinition) { defaultTupleField = field; fieldDefinitionsToIndexMap!.Add(field, tupleFieldIndex); } else { // Add the underlying/real field as an element (wrapping mainly to capture location). It should have the default name. defaultTupleField = new TupleElementFieldSymbol(this, fieldSymbol, tupleFieldIndex, locations, isImplicitlyDeclared: defaultImplicitlyDeclared); members.Add(defaultTupleField); } } if (defaultImplicitlyDeclared && !string.IsNullOrEmpty(providedName)) { var errorPositions = TupleErrorPositions; var isError = errorPositions.IsDefault ? false : errorPositions[tupleFieldIndex]; // The name given doesn't match the default name Item8, etc. // Add a virtual field with the given name members.Add(new TupleVirtualElementFieldSymbol(this, fieldSymbol, providedName, tupleFieldIndex, locations, cannotUse: isError, isImplicitlyDeclared: false, correspondingDefaultFieldOpt: defaultTupleField)); } elementsMatchedByFields[tupleFieldIndex] = true; // mark as handled } // No need to wrap other real fields break; case SymbolKind.NamedType: case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: break; default: if (currentNestingLevel == 0) { throw ExceptionUtilities.UnexpectedValue(member.Kind); } break; } } if (currentValueTuple.Arity != ValueTupleRestPosition) { break; } var oldUnderlying = currentValueTuple; currentValueTuple = (NamedTypeSymbol)oldUnderlying.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestIndex].Type; currentNestingLevel++; if (currentValueTuple.Arity != ValueTupleRestPosition) { // refresh members and target fields currentMembers = currentValueTuple.GetMembers(); currentFieldsForElements.Clear(); collectTargetTupleFields(currentValueTuple.Arity, getOriginalFields(currentMembers), currentFieldsForElements); } else { Debug.Assert((object)oldUnderlying.OriginalDefinition == currentValueTuple.OriginalDefinition); } } currentFieldsForElements.Free(); // At the end, add unmatched fields as error symbols for (int i = 0; i < elementsMatchedByFields.Count; i++) { if (!elementsMatchedByFields[i]) { // We couldn't find a backing field for this element. It will be an error to access it. int fieldRemainder; // one-based int fieldChainLength = NumberOfValueTuples(i + 1, out fieldRemainder); NamedTypeSymbol container = getNestedTupleUnderlyingType(this, fieldChainLength - 1).OriginalDefinition; var diagnosticInfo = container.IsErrorType() ? null : new CSDiagnosticInfo(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, TupleMemberName(fieldRemainder), container, container.ContainingAssembly); var providedName = elementNames.IsDefault ? null : elementNames[i]; var location = elementLocations.IsDefault ? null : elementLocations[i]; var defaultName = TupleMemberName(i + 1); // if provided name does not match the default one, // then default element is declared implicitly var defaultImplicitlyDeclared = providedName != defaultName; // Add a field with default name. It should be present regardless. TupleErrorFieldSymbol defaultTupleField = new TupleErrorFieldSymbol(this, defaultName, i, defaultImplicitlyDeclared ? null : location, elementTypes[i], diagnosticInfo, defaultImplicitlyDeclared, correspondingDefaultFieldOpt: null); members.Add(defaultTupleField); if (defaultImplicitlyDeclared && !String.IsNullOrEmpty(providedName)) { // Add friendly named element field. members.Add(new TupleErrorFieldSymbol(this, providedName, i, location, elementTypes[i], diagnosticInfo, isImplicitlyDeclared: false, correspondingDefaultFieldOpt: defaultTupleField)); } } } elementsMatchedByFields.Free(); if (fieldDefinitionsToIndexMap is object) { this.TupleData!.SetFieldDefinitionsToIndexMap(fieldDefinitionsToIndexMap); } return members; // Returns the nested type at a certain depth. // // For depth=0, just return the tuple type as-is. // For depth=1, returns the nested tuple type at position 8. static NamedTypeSymbol getNestedTupleUnderlyingType(NamedTypeSymbol topLevelUnderlyingType, int depth) { NamedTypeSymbol found = topLevelUnderlyingType; for (int i = 0; i < depth; i++) { found = (NamedTypeSymbol)found.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type; } return found; } static void collectTargetTupleFields(int arity, ImmutableArray<Symbol> members, ArrayBuilder<FieldSymbol?> fieldsForElements) { int fieldsPerType = Math.Min(arity, ValueTupleRestPosition - 1); for (int i = 0; i < fieldsPerType; i++) { WellKnownMember wellKnownTupleField = GetTupleTypeMember(arity, i + 1); fieldsForElements.Add((FieldSymbol?)GetWellKnownMemberInType(members, wellKnownTupleField)); } } static Symbol? GetWellKnownMemberInType(ImmutableArray<Symbol> members, WellKnownMember relativeMember) { Debug.Assert(relativeMember >= WellKnownMember.System_ValueTuple_T1__Item1 && relativeMember <= WellKnownMember.System_ValueTuple_TRest__ctor); MemberDescriptor relativeDescriptor = WellKnownMembers.GetDescriptor(relativeMember); return CSharpCompilation.GetRuntimeMember(members, relativeDescriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); // force lookup of public members only } static ImmutableArray<Symbol> getOriginalFields(ImmutableArray<Symbol> members) { var fields = ArrayBuilder<Symbol>.GetInstance(); foreach (var member in members) { if (member is TupleVirtualElementFieldSymbol) { continue; } else if (member is TupleElementFieldSymbol tupleField) { fields.Add(tupleField.UnderlyingField.OriginalDefinition); } else if (member is FieldSymbol field) { fields.Add(field.OriginalDefinition); } } Debug.Assert(fields.All(f => f is object)); return fields.ToImmutableAndFree(); } static ImmutableArray<Location> getElementLocations(in ImmutableArray<Location?> elementLocations, int tupleFieldIndex) { if (elementLocations.IsDefault) { return ImmutableArray<Location>.Empty; } var elementLocation = elementLocations[tupleFieldIndex]; return elementLocation == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(elementLocation); } } private TypeSymbol MergeTupleNames(NamedTypeSymbol other, NamedTypeSymbol mergedType) { // Merge tuple element names, if any ImmutableArray<string?> names1 = TupleElementNames; ImmutableArray<string?> names2 = other.TupleElementNames; ImmutableArray<string?> mergedNames; if (names1.IsDefault || names2.IsDefault) { mergedNames = default; } else { Debug.Assert(names1.Length == names2.Length); mergedNames = names1.ZipAsArray(names2, (n1, n2) => string.CompareOrdinal(n1, n2) == 0 ? n1 : null)!; if (mergedNames.All(n => n is null)) { mergedNames = default; } } bool namesUnchanged = mergedNames.IsDefault ? TupleElementNames.IsDefault : mergedNames.SequenceEqual(TupleElementNames); return (namesUnchanged && this.Equals(mergedType, TypeCompareKind.ConsiderEverything)) ? this : CreateTuple(mergedType, mergedNames, this.TupleErrorPositions, this.TupleElementLocations, this.Locations); } /// <summary> /// The main purpose of this type is to store element names and also cache some information related to tuples. /// </summary> internal sealed class TupleExtraData { /// <summary> /// Element names, if provided. /// </summary> internal ImmutableArray<string?> ElementNames { get; } /// <summary> /// Declaration locations for individual elements, if provided. /// Declaration location for this tuple type symbol /// </summary> internal ImmutableArray<Location?> ElementLocations { get; } /// <summary> /// Which element names were inferred and therefore cannot be used. /// If none of the element names were inferred, or inferred names can be used (no tracking necessary), leave as default. /// This information is ignored in type equality and comparison. /// </summary> internal ImmutableArray<bool> ErrorPositions { get; } internal ImmutableArray<Location> Locations { get; } /// <summary> /// Element types. /// </summary> private ImmutableArray<TypeWithAnnotations> _lazyElementTypes; private ImmutableArray<FieldSymbol> _lazyDefaultElementFields; /// <summary> /// For tuple fields that aren't TupleElementFieldSymbol or TupleErrorFieldSymbol, we cache their tuple element index. /// This supports <see cref="FieldSymbol.TupleElementIndex"/>. /// For those fields, we map from their definition to an index. /// </summary> private SmallDictionary<FieldSymbol, int>? _lazyFieldDefinitionsToIndexMap; private SmallDictionary<Symbol, Symbol>? _lazyUnderlyingDefinitionToMemberMap; /// <summary> /// The same named type, but without element names. /// </summary> internal NamedTypeSymbol TupleUnderlyingType { get; } internal TupleExtraData(NamedTypeSymbol underlyingType) { RoslynDebug.Assert(underlyingType is object); Debug.Assert(underlyingType.IsTupleType); Debug.Assert(underlyingType.TupleElementNames.IsDefault); TupleUnderlyingType = underlyingType; Locations = ImmutableArray<Location>.Empty; } internal TupleExtraData(NamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<bool> errorPositions, ImmutableArray<Location> locations) : this(underlyingType) { ElementNames = elementNames; ElementLocations = elementLocations; ErrorPositions = errorPositions; Locations = locations.NullToEmpty(); } internal bool EqualsIgnoringTupleUnderlyingType(TupleExtraData? other) { if (other is null && this.ElementNames.IsDefault && this.ElementLocations.IsDefault && this.ErrorPositions.IsDefault) { return true; } return other is object && areEqual(this.ElementNames, other.ElementNames) && areEqual(this.ElementLocations, other.ElementLocations) && areEqual(this.ErrorPositions, other.ErrorPositions); static bool areEqual<T>(ImmutableArray<T> one, ImmutableArray<T> other) { if (one.IsDefault && other.IsDefault) { return true; } if (one.IsDefault != other.IsDefault) { return false; } return one.SequenceEqual(other); } } public ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations(NamedTypeSymbol tuple) { Debug.Assert(tuple.Equals(TupleUnderlyingType, TypeCompareKind.IgnoreTupleNames)); if (_lazyElementTypes.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyElementTypes, collectTupleElementTypesWithAnnotations(tuple)); } return _lazyElementTypes; static ImmutableArray<TypeWithAnnotations> collectTupleElementTypesWithAnnotations(NamedTypeSymbol tuple) { ImmutableArray<TypeWithAnnotations> elementTypes; if (tuple.Arity == ValueTupleRestPosition) { // Ensure all Rest extensions are tuples var extensionTupleElementTypes = tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type.TupleElementTypesWithAnnotations; var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(ValueTupleRestPosition - 1 + extensionTupleElementTypes.Length); typesBuilder.AddRange(tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, ValueTupleRestPosition - 1); typesBuilder.AddRange(extensionTupleElementTypes); elementTypes = typesBuilder.ToImmutableAndFree(); } else { elementTypes = tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; } return elementTypes; } } public ImmutableArray<FieldSymbol> TupleElements(NamedTypeSymbol tuple) { Debug.Assert(tuple.Equals(TupleUnderlyingType, TypeCompareKind.IgnoreTupleNames)); if (_lazyDefaultElementFields.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyDefaultElementFields, collectTupleElementFields(tuple)); } return _lazyDefaultElementFields; ImmutableArray<FieldSymbol> collectTupleElementFields(NamedTypeSymbol tuple) { var builder = ArrayBuilder<FieldSymbol>.GetInstance(TupleElementTypesWithAnnotations(tuple).Length, fillWithValue: null!); foreach (var member in tuple.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var candidate = (FieldSymbol)member; var index = candidate.TupleElementIndex; if (index >= 0) { if (builder[index]?.IsDefaultTupleElement != false) { builder[index] = candidate; } else { // there is a better field in the slot // that can only happen if the candidate is default. Debug.Assert(candidate.IsDefaultTupleElement); } } } Debug.Assert(builder.All(f => f is object)); return builder.ToImmutableAndFree(); } } internal SmallDictionary<FieldSymbol, int> GetFieldDefinitionsToIndexMap(NamedTypeSymbol tuple) { Debug.Assert(tuple.IsTupleType); Debug.Assert(tuple.IsDefinition); // we only store a map for definitions if (_lazyFieldDefinitionsToIndexMap is null) { tuple.InitializeTupleFieldDefinitionsToIndexMap(); } Debug.Assert(_lazyFieldDefinitionsToIndexMap is object); return _lazyFieldDefinitionsToIndexMap; } internal void SetFieldDefinitionsToIndexMap(SmallDictionary<FieldSymbol, int> map) { Debug.Assert(map.Keys.All(k => k.IsDefinition)); Debug.Assert(map.Values.All(v => v >= 0)); Interlocked.CompareExchange(ref _lazyFieldDefinitionsToIndexMap, map, null); } internal SmallDictionary<Symbol, Symbol> UnderlyingDefinitionToMemberMap { get { return _lazyUnderlyingDefinitionToMemberMap ??= computeDefinitionToMemberMap(); SmallDictionary<Symbol, Symbol> computeDefinitionToMemberMap() { var map = new SmallDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); var members = TupleUnderlyingType.GetMembers(); // Go in reverse because we want members with default name, which precede the ones with // friendly names, to be in the map. for (int i = members.Length - 1; i >= 0; i--) { var member = members[i]; switch (member.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.NamedType: map.Add(member.OriginalDefinition, member); break; case SymbolKind.Field: var tupleUnderlyingField = ((FieldSymbol)member).TupleUnderlyingField; if (tupleUnderlyingField is object) { map[tupleUnderlyingField.OriginalDefinition] = member; } break; case SymbolKind.Event: var underlyingEvent = (EventSymbol)member; var underlyingAssociatedField = underlyingEvent.AssociatedField; // The field is not part of the members list if (underlyingAssociatedField is object) { Debug.Assert((object)underlyingAssociatedField.ContainingSymbol == TupleUnderlyingType); Debug.Assert(TupleUnderlyingType.GetMembers(underlyingAssociatedField.Name).IndexOf(underlyingAssociatedField) < 0); map.Add(underlyingAssociatedField.OriginalDefinition, underlyingAssociatedField); } map.Add(underlyingEvent.OriginalDefinition, member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } return map; } } } public TMember? GetTupleMemberSymbolForUnderlyingMember<TMember>(TMember? underlyingMemberOpt) where TMember : Symbol { if (underlyingMemberOpt is null) { return null; } Symbol underlyingMemberDefinition = underlyingMemberOpt.OriginalDefinition; if (underlyingMemberDefinition is TupleElementFieldSymbol tupleField) { underlyingMemberDefinition = tupleField.UnderlyingField; } if (TypeSymbol.Equals(underlyingMemberDefinition.ContainingType, TupleUnderlyingType.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if (UnderlyingDefinitionToMemberMap.TryGetValue(underlyingMemberDefinition, out Symbol? result)) { return (TMember)result; } } return null; } } } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTupleTest.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.Globalization; using System.Linq; using System.Reflection.Metadata; using System.Text; 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.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static TestResources.NetFX.ValueTuple; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.Tuples)] public class CodeGenTupleTests : CSharpTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; private static readonly string trivial2uple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } "; private static readonly string trivial3uple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 item1, T2 item2, T3 item3) { this.Item1 = item1; this.Item2 = item2; this.Item3 = item3; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + "", "" + Item3?.ToString() + '}'; } } } "; private static readonly string trivialRemainingTuples = @" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { this.Item1 = item1; } public override string ToString() { return '{' + Item1?.ToString() + '}'; } } public struct ValueTuple<T1, T2, T3, T4> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; } } public struct ValueTuple<T1, T2, T3, T4, T5> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override string ToString() { return base.ToString(); } } } "; [Fact] public void BadValueTupleByItself() { var source = @" namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics( // (7,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(7, 20), // (8,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(8, 16), // (8,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(8, 16), // (11,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = item2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(11, 18) ); } [Fact] public void ValueTupleWithDifferentNamesInOperator() { var source = @" namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static bool operator +((T1 a, T2 b) t) => throw null; public static bool operator true((T1 a, T2 b) t) => throw null; public static bool operator false((T1 a, T2 b) t) => throw null; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); } [Fact] public void MergeNamesFromTypelessTuple() { var src = @" class C { T M<T>(T x, T y) => throw null; void M2() { var t = M((a: 1, b: ""hello""), (a: default, b: null)); t.a.ToString(); t.b.ToString(); var t2 = M((a: 1, b: ""hello""), (a: default, z: null)); // 1 t2.a.ToString(); t2.b.ToString(); var t3 = M((1, ""hello""), (a: default, b: null)); // 2, 3 t3.a.ToString(); // 4 t3.b.ToString(); // 5 } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,53): warning CS8123: The tuple element name 'z' is ignored because a different name or no name is specified by the target type '(int a, string b)'. // var t2 = M((a: 1, b: "hello"), (a: default, z: null)); // 1 Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "z: null").WithArguments("z", "(int a, string b)").WithLocation(11, 53), // (15,35): warning CS8123: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(int, string)'. // var t3 = M((1, "hello"), (a: default, b: null)); // 2, 3 Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: default").WithArguments("a", "(int, string)").WithLocation(15, 35), // (15,47): warning CS8123: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(int, string)'. // var t3 = M((1, "hello"), (a: default, b: null)); // 2, 3 Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: null").WithArguments("b", "(int, string)").WithLocation(15, 47), // (16,12): error CS1061: '(int, string)' does not contain a definition for 'a' and no accessible extension method 'a' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // t3.a.ToString(); // 4 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, string)", "a").WithLocation(16, 12), // (17,12): error CS1061: '(int, string)' does not contain a definition for 'b' and no accessible extension method 'b' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // t3.b.ToString(); // 5 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b").WithArguments("(int, string)", "b").WithLocation(17, 12) ); } [Fact] public void InferenceWithTupleNamesInNullableContext() { var src = @" #nullable enable public class C<T> { void M(C<(int a, string b)> list) { _ = list.Select(i => i.a); } } public static class Extensions { public static T2 Select<T1, T2>(this C<T1> list, System.Func<T1, T2> f) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void InterfaceImplAttributesAreNotSharedAcrossTypeRefs() { var src1 = @" public interface I1<T> {} public interface I2 : I1<(int a, int b)> {} public interface I3 : I1<(int c, int d)> {}"; var src2 = @" class C1 : I2, I1<(int a, int b)> {} class C2 : I3, I1<(int c, int d)> {}"; var comp1 = CreateCompilation(src1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(src2, references: new[] { comp1.ToMetadataReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(src2, references: new[] { comp1.EmitToImageReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void ConstraintAttributesAreNotSharedAcrossTypeRefs() { var src1 = @" using System.Collections.Generic; public abstract class C1 { public abstract void M<T>(T t) where T : IEnumerable<(int a, int b)>; } public abstract class C2 { public abstract void M<T>(T t) where T : IEnumerable<(int c, int d)>; }"; var src2 = @" class C3 : C1 { public override void M<U>(U u) { int x; foreach (var kvp in u) { x = kvp.a + kvp.b; } } } class C4 : C2 { public override void M<U>(U u) { int x; foreach (var kvp in u) { x = kvp.c + kvp.d; } } }"; var comp1 = CreateCompilationWithMscorlib40(src1, references: s_valueTupleRefs); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40(src2, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef, comp1.ToMetadataReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilationWithMscorlib40(src2, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef, comp1.EmitToImageReference() }); comp3.VerifyDiagnostics(); } [Fact] public void InterfaceAttributes() { var comp = CreateCompilation(@" using System; using System.Collections; using System.Collections.Generic; interface ITest<T> { T Get(); } public class C : ITest<(int key, int val)> { public (int key, int val) Get() => (0, 0); } public class Base<T> : ITest<T> { public T Get() => default(T); } public class C2 : Base<(int x, int y)> { } public class C3 : IEnumerable<(int key, int val)> { private readonly (int, int)[] _backing; public C3((int, int)[] backing) { _backing = backing; } private class Inner : IEnumerator<(int key, int val)>, IEnumerator { private int index = -1; private readonly (int, int)[] _backing; public Inner((int, int)[] backing) { _backing = backing; } public (int key, int val) Current => _backing[index]; object IEnumerator.Current => Current; public void Dispose() { } public bool MoveNext() => ++index < _backing.Length; public void Reset() { throw new NotSupportedException(); } } IEnumerator<(int key, int val)> IEnumerable<(int key, int val)>.GetEnumerator() => new Inner(_backing); IEnumerator IEnumerable.GetEnumerator() => new Inner(_backing); } public class C4 : C3 { public C4((int, int)[] backing) : base(backing) { } } "); CompileAndVerify(comp, symbolValidator: m => { var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.Interfaces().Length); NamedTypeSymbol iface = c.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); TypeSymbol typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.False(((NamedTypeSymbol)typeArg).IsSerializable); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); var c2 = m.GlobalNamespace.GetTypeMember("C2"); var @base = c2.BaseType(); Assert.Equal("Base", @base.Name); Assert.Equal(1, @base.Interfaces().Length); iface = @base.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "x", "y" }, typeArg.TupleElementNames); var c3 = m.GlobalNamespace.GetTypeMember("C3"); Assert.Equal(2, c3.Interfaces().Length); iface = c3.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); var d = m.GlobalNamespace.GetTypeMember("C3"); Assert.Equal(2, d.Interfaces().Length); iface = d.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); }); CompileAndVerify(@" using System; class D { public static void Main(string[] args) { var c = new C(); var temp = c.Get(); Console.WriteLine(temp); Console.WriteLine(""key: "" + temp.key); Console.WriteLine(""val: "" + temp.val); var c2 = new C2(); var temp2 = c2.Get(); Console.WriteLine(temp); Console.WriteLine(""x: "" + temp2.x); Console.WriteLine(""y: "" + temp2.y); var backing = new[] { (1, 1), (2, 2), (3, 3) }; var c3 = new C3(backing); foreach (var kvp in c3) { Console.WriteLine($""(key: {kvp.key}, val: {kvp.val})""); } var c4 = new C4(backing); foreach (var kvp in c4) { Console.WriteLine($""(key: {kvp.key}, val: {kvp.val})""); } } }", references: new[] { comp.EmitToImageReference() }, expectedOutput: @"(0, 0) key: 0 val: 0 (0, 0) x: 0 y: 0 (key: 1, val: 1) (key: 2, val: 2) (key: 3, val: 3) (key: 1, val: 1) (key: 2, val: 2) (key: 3, val: 3)"); } [Fact] public void GenericConstraintAttributes() { var comp = CreateCompilation(@" using System; using System.Collections; using System.Collections.Generic; public interface ITest<T> { T Get { get; } } public class Test : ITest<(int key, int val)> { public (int key, int val) Get => (0, 0); } public class Base<T> : ITest<T> { public T Get { get; } protected Base(T t) { Get = t; } } public class C<T> where T : ITest<(int key, int val)> { public T Get { get; } public C(T t) { Get = t; } } public class C2<T> where T : Base<(int key, int val)> { public T Get { get; } public C2(T t) { Get = t; } } public sealed class Test2 : Base<(int key, int val)> { public Test2() : base((-1, -2)) {} } public class C3<T> where T : IEnumerable<(int key, int val)> { public T Get { get; } public C3(T t) { Get = t; } } public struct TestEnumerable : IEnumerable<(int key, int val)> { private readonly (int, int)[] _backing; public TestEnumerable((int, int)[] backing) { _backing = backing; } private class Inner : IEnumerator<(int key, int val)>, IEnumerator { private int index = -1; private readonly (int, int)[] _backing; public Inner((int, int)[] backing) { _backing = backing; } public (int key, int val) Current => _backing[index]; object IEnumerator.Current => Current; public void Dispose() { } public bool MoveNext() => ++index < _backing.Length; public void Reset() { throw new NotSupportedException(); } } IEnumerator<(int key, int val)> IEnumerable<(int key, int val)>.GetEnumerator() => new Inner(_backing); IEnumerator IEnumerable.GetEnumerator() => new Inner(_backing); } "); CompileAndVerify(comp, symbolValidator: m => { var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.TypeParameters.Length); var param = c.TypeParameters[0]; Assert.Equal(1, param.ConstraintTypes().Length); var constraint = Assert.IsAssignableFrom<NamedTypeSymbol>(param.ConstraintTypes()[0]); Assert.True(constraint.IsGenericType); Assert.Equal(1, constraint.TypeArguments().Length); TypeSymbol typeArg = constraint.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.False(typeArg.TupleElementNames.IsDefault); Assert.Equal(2, typeArg.TupleElementNames.Length); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); var c2 = m.GlobalNamespace.GetTypeMember("C2"); Assert.Equal(1, c2.TypeParameters.Length); param = c2.TypeParameters[0]; Assert.Equal(1, param.ConstraintTypes().Length); constraint = Assert.IsAssignableFrom<NamedTypeSymbol>(param.ConstraintTypes()[0]); Assert.True(constraint.IsGenericType); Assert.Equal(1, constraint.TypeArguments().Length); typeArg = constraint.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.False(typeArg.TupleElementNames.IsDefault); Assert.Equal(2, typeArg.TupleElementNames.Length); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); }); CompileAndVerify(@" using System; class D { public static void Main(string[] args) { var c = new C<Test>(new Test()); var temp = c.Get.Get; Console.WriteLine(temp); Console.WriteLine(""key: "" + temp.key); Console.WriteLine(""val: "" + temp.val); var c2 = new C2<Test2>(new Test2()); var temp2 = c2.Get.Get; Console.WriteLine(temp2); Console.WriteLine(""key: "" + temp2.key); Console.WriteLine(""val: "" + temp2.val); var backing = new[] { (1, 2), (3, 4), (5, 6) }; var c3 = new C3<TestEnumerable>(new TestEnumerable(backing)); foreach (var kvp in c3.Get) { Console.WriteLine($""key: {kvp.key}, val: {kvp.val}""); } var c4 = new C<Test2>(new Test2()); var temp4 = c4.Get.Get; Console.WriteLine(temp4); Console.WriteLine(""key: "" + temp4.key); Console.WriteLine(""val: "" + temp4.val); } }", references: new[] { comp.EmitToImageReference() }, expectedOutput: @"(0, 0) key: 0 val: 0 (-1, -2) key: -1 val: -2 key: 1, val: 2 key: 3, val: 4 key: 5, val: 6 (-1, -2) key: -1 val: -2 "); } [Fact] public void BadTupleNameMetadata() { var comp = CreateCompilationWithILAndMscorlib40("", @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooFewNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooManyNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooFewNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooFewNamesMethod .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooManyNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooManyNamesMethod } // end of class C ", references: s_valueTupleRefs); var c = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var validField = c.GetMember<FieldSymbol>("ValidField"); Assert.False(validField.Type.IsErrorType()); Assert.True(validField.Type.IsTupleType); Assert.True(validField.Type.TupleElementNames.IsDefault); var validFieldWithAttribute = c.GetMember<FieldSymbol>("ValidFieldWithAttribute"); Assert.True(validFieldWithAttribute.Type.IsErrorType()); Assert.False(validFieldWithAttribute.Type.IsTupleType); Assert.IsType<UnsupportedMetadataTypeSymbol>(validFieldWithAttribute.Type); var tooFewNames = c.GetMember<FieldSymbol>("TooFewNames"); Assert.True(tooFewNames.Type.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooFewNames.Type); Assert.False(((NamedTypeSymbol)tooFewNames.Type).IsSerializable); var tooManyNames = c.GetMember<FieldSymbol>("TooManyNames"); Assert.True(tooManyNames.Type.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooManyNames.Type); var tooFewNamesMethod = c.GetMember<MethodSymbol>("TooFewNamesMethod"); Assert.True(tooFewNamesMethod.ReturnType.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooFewNamesMethod.ReturnType); var tooManyNamesMethod = c.GetMember<MethodSymbol>("TooManyNamesMethod"); Assert.True(tooManyNamesMethod.ReturnType.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooManyNamesMethod.ReturnType); } [Fact] public void MetadataForPartiallyNamedTuples() { var comp = CreateCompilationWithILAndMscorlib40("", @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // In source, all or no names must be specified for a tuple .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> PartialNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](""e1"", null)} = ( 01 00 02 00 00 00 02 65 31 FF ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> AllNullNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](null, null)} = ( 01 00 02 00 00 00 ff ff 00 00 ) .method public hidebysig instance void PartialNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, ""e1"", null)} = ( 01 00 03 00 00 00 FF 02 65 31 FF ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::PartialNamesMethod .method public hidebysig instance void AllNullNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, null, null)} = ( 01 00 03 00 00 00 ff ff ff 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::AllNullNamesMethod } // end of class C ", targetFramework: TargetFramework.Mscorlib40, references: s_valueTupleRefs); var c = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var validField = c.GetMember<FieldSymbol>("ValidField"); Assert.False(validField.Type.IsErrorType()); Assert.True(validField.Type.IsTupleType); Assert.True(validField.Type.TupleElementNames.IsDefault); var validFieldWithAttribute = c.GetMember<FieldSymbol>("ValidFieldWithAttribute"); Assert.True(validFieldWithAttribute.Type.IsErrorType()); Assert.False(validFieldWithAttribute.Type.IsTupleType); Assert.IsType<UnsupportedMetadataTypeSymbol>(validFieldWithAttribute.Type); var partialNames = c.GetMember<FieldSymbol>("PartialNames"); Assert.False(partialNames.Type.IsErrorType()); Assert.True(partialNames.Type.IsTupleType); Assert.Equal("(System.Int32 e1, System.Int32)", partialNames.TypeWithAnnotations.ToTestDisplayString()); var allNullNames = c.GetMember<FieldSymbol>("AllNullNames"); Assert.False(allNullNames.Type.IsErrorType()); Assert.True(allNullNames.Type.IsTupleType); Assert.Equal("(System.Int32, System.Int32)", allNullNames.TypeWithAnnotations.ToTestDisplayString()); var partialNamesMethod = c.GetMember<MethodSymbol>("PartialNamesMethod"); var partialParamType = partialNamesMethod.Parameters.Single().TypeWithAnnotations; Assert.False(partialParamType.Type.IsErrorType()); Assert.True(partialParamType.Type.IsTupleType); Assert.Equal("System.ValueTuple<(System.Int32 e1, System.Int32)>", partialParamType.ToTestDisplayString()); var allNullNamesMethod = c.GetMember<MethodSymbol>("AllNullNamesMethod"); var allNullParamType = allNullNamesMethod.Parameters.Single().TypeWithAnnotations; Assert.False(allNullParamType.Type.IsErrorType()); Assert.True(allNullParamType.Type.IsTupleType); Assert.Equal("System.ValueTuple<(System.Int32, System.Int32)>", allNullParamType.ToTestDisplayString()); } [Fact] public void NestedTuplesNoAttribute() { var comp = CreateCompilationWithILAndMscorlib40("", @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base`1<T> extends [mscorlib]System.Object { } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> Field1 .field public class Base`1<class [System.ValueTuple]System.ValueTuple`1< class [System.ValueTuple]System.ValueTuple`2<int32, int32>>> Field2; } // end of class C ", references: s_valueTupleRefs); var c = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var base1 = comp.GlobalNamespace.GetTypeMember("Base"); Assert.NotNull(base1); var field1 = c.GetMember<FieldSymbol>("Field1"); Assert.False(field1.Type.IsErrorType()); Assert.True(field1.Type.IsTupleType); Assert.True(field1.Type.TupleElementNames.IsDefault); NamedTypeSymbol field2Type = (NamedTypeSymbol)c.GetMember<FieldSymbol>("Field2").Type; Assert.Equal(base1, field2Type.OriginalDefinition); Assert.True(field2Type.IsGenericType); var first = field2Type.TypeArguments()[0]; Assert.True(first.IsTupleType); Assert.Equal(1, first.TupleElementTypesWithAnnotations.Length); Assert.True(first.TupleElementNames.IsDefault); var second = first.TupleElementTypesWithAnnotations[0].Type; Assert.True(second.IsTupleType); Assert.True(second.TupleElementNames.IsDefault); Assert.Equal(2, second.TupleElementTypesWithAnnotations.Length); Assert.All(second.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); } [Fact] public void SimpleTuple() { var source = @" class C { static void Main() { var x = (1, 2); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "{1, 2}"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: constrained. ""System.ValueTuple<int, int>"" IL_0011: callvirt ""string object.ToString()"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: ret }"); } [Fact] public void SimpleTupleNew() { var source = @" class C { static void Main() { var x = new (int, int)(1, 2); System.Console.WriteLine(x.ToString()); x = new (int, int)(); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int, int)(1, 2); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(6, 21), // (9,17): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // x = new (int, int)(); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(9, 17) ); } [Fact] public void SimpleTupleNew1() { var source = @" class C { static void Main() { dynamic arg = 2; var x = new (int, int)(1, arg); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int, int)(1, arg); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(7, 21) ); } [Fact] public void SimpleTupleNew2() { var source = @" class C { static void Main() { var x = new (int a, int b)(1, 2); System.Console.WriteLine(x.a.ToString()); var x1 = new (int a, int b)(1, 2) { a = 3, Item2 = 4}; System.Console.WriteLine(x1.a.ToString()); var x2 = new (int a, (int b, int c) d)(1, new (int, int)(2, 3)) { a = 5, d = {b = 6, c = 7}}; System.Console.WriteLine(x2.a.ToString()); System.Console.WriteLine(x2.d.b.ToString()); System.Console.WriteLine(x2.d.c.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int a, int b)(1, 2); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, int b)").WithLocation(6, 21), // (9,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x1 = new (int a, int b)(1, 2) { a = 3, Item2 = 4}; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, int b)").WithLocation(9, 22), // (12,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x2 = new (int a, (int b, int c) d)(1, new (int, int)(2, 3)) { a = 5, d = {b = 6, c = 7}}; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, (int b, int c) d)").WithLocation(12, 22), // (12,55): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x2 = new (int a, (int b, int c) d)(1, new (int, int)(2, 3)) { a = 5, d = {b = 6, c = 7}}; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(12, 55) ); } [WorkItem(10874, "https://github.com/dotnet/roslyn/issues/10874")] [Fact] public void SimpleTupleNew3() { var source = @" class C { static void Main() { var x0 = new (int a, int b)(1, 2, 3); System.Console.WriteLine(x0.ToString()); var x1 = new (int, int)(1, 2, 3); System.Console.WriteLine(x1.ToString()); var x2 = new (int, int)(1, ""2""); System.Console.WriteLine(x2.ToString()); var x3 = new (int, int)(1); System.Console.WriteLine(x3.ToString()); var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; System.Console.WriteLine(x3.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x0 = new (int a, int b)(1, 2, 3); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, int b)").WithLocation(6, 22), // (9,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x1 = new (int, int)(1, 2, 3); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(9, 22), // (12,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x2 = new (int, int)(1, "2"); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(12, 22), // (15,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x3 = new (int, int)(1); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(15, 22), // (18,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(18, 22), // (18,40): error CS0117: '(int, int)' does not contain a definition for 'a' // var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; Diagnostic(ErrorCode.ERR_NoSuchMember, "a").WithArguments("(int, int)", "a").WithLocation(18, 40), // (18,47): error CS0117: '(int, int)' does not contain a definition for 'Item3' // var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; Diagnostic(ErrorCode.ERR_NoSuchMember, "Item3").WithArguments("(int, int)", "Item3").WithLocation(18, 47) ); } [Fact] public void SimpleTuple2() { var source = @" class C { static void Main() { var s = Single((a:1, b:2)); System.Console.WriteLine(s[0].b.ToString()); } static T[] Single<T>(T x) { return new T[]{x}; } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: call ""System.ValueTuple<int, int>[] C.Single<System.ValueTuple<int, int>>(System.ValueTuple<int, int>)"" IL_000c: ldc.i4.0 IL_000d: ldelema ""System.ValueTuple<int, int>"" IL_0012: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0017: call ""string int.ToString()"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret }"); } [Fact] public void SimpleTupleTargetTyped() { var source = @" class C { static void Main() { (object, object) x = (null, null); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "{, }"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple<object, object> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldnull IL_0004: call ""System.ValueTuple<object, object>..ctor(object, object)"" IL_0009: ldloca.s V_0 IL_000b: constrained. ""System.ValueTuple<object, object>"" IL_0011: callvirt ""string object.ToString()"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: ret }"); } [Fact] public void SimpleTupleNested() { var source = @" class C { static void Main() { var x = (1, (2, (3, 4)).ToString()); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "{1, {2, {3, 4}}}"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 5 .locals init (System.ValueTuple<int, string> V_0, //x System.ValueTuple<int, System.ValueTuple<int, int>> V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: ldc.i4.4 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: newobj ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: constrained. ""System.ValueTuple<int, System.ValueTuple<int, int>>"" IL_0019: callvirt ""string object.ToString()"" IL_001e: call ""System.ValueTuple<int, string>..ctor(int, string)"" IL_0023: ldloca.s V_0 IL_0025: constrained. ""System.ValueTuple<int, string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret }"); } [Fact] public void TupleUnderlyingItemAccess() { var source = @" class C { static void Main() { var x = (1, 2); System.Console.WriteLine(x.Item2.ToString()); x.Item1 = 40; System.Console.WriteLine(x.Item1 + x.Item2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0010: call ""string int.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0023: ldloc.0 IL_0024: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0029: ldloc.0 IL_002a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002f: add IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret } "); } [Fact] public void TupleUnderlyingItemAccess01() { var source = @" class C { static void Main() { var x = (a: 1, b: 2); System.Console.WriteLine(x.Item2.ToString()); x.Item1 = 40; System.Console.WriteLine(x.Item1 + x.Item2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0010: call ""string int.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0023: ldloc.0 IL_0024: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0029: ldloc.0 IL_002a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002f: add IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret } "); } [Fact] public void TupleItemAccess() { var source = @" class C { static void Main() { var x = (a: 1, b: 2); System.Console.WriteLine(x.b.ToString()); x.a = 40; System.Console.WriteLine(x.a + x.b); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0010: call ""string int.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0023: ldloc.0 IL_0024: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0029: ldloc.0 IL_002a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002f: add IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret } "); } [Fact] public void TupleItemAccess01() { var source = @" class C { static void Main() { var x = (a: 1, b: (c: 2, d: 3)); System.Console.WriteLine(x.b.c.ToString()); x.b.d = 39; System.Console.WriteLine(x.a + x.b.c + x.b.d); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 87 (0x57) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_000f: ldloca.s V_0 IL_0011: ldflda ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0016: ldflda ""int System.ValueTuple<int, int>.Item1"" IL_001b: call ""string int.ToString()"" IL_0020: call ""void System.Console.WriteLine(string)"" IL_0025: ldloca.s V_0 IL_0027: ldflda ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_002c: ldc.i4.s 39 IL_002e: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0033: ldloc.0 IL_0034: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0039: ldloc.0 IL_003a: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_003f: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0044: add IL_0045: ldloc.0 IL_0046: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_004b: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0050: add IL_0051: call ""void System.Console.WriteLine(int)"" IL_0056: ret } "); } [Fact] public void TupleTypeDeclaration() { var source = @" class C { static void Main() { (int, string, int) x = (1, ""hello"", 2); System.Console.WriteLine(x.ToString()); } } " + trivial3uple; var comp = CompileAndVerify(source, expectedOutput: @"{1, hello, 2}"); } [Fact] [WorkItem(11281, "https://github.com/dotnet/roslyn/issues/11281")] public void TupleTypeMismatch_01() { var source = @" class C { static void Main() { (int, string) x = (1, ""hello"", 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (6,27): error CS0029: Cannot implicitly convert type '(int, string, int)' to '(int, string)' // (int, string) x = (1, "hello", 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(1, ""hello"", 2)").WithArguments("(int, string, int)", "(int, string)").WithLocation(6, 27)); } [Fact] [WorkItem(11282, "https://github.com/dotnet/roslyn/issues/11282")] public void TupleTypeMismatch_02() { var source = @" class C { static void Main() { (int, string) x = (1, null, 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (6,27): error CS8135: Tuple with 3 elements cannot be converted to type '(int, string)'. // (int, string) x = (1, null, 2); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(1, null, 2)").WithArguments("3", "(int, string)").WithLocation(6, 27) ); } [Fact] [WorkItem(11283, "https://github.com/dotnet/roslyn/issues/11283")] public void LongTupleTypeMismatch() { var source = @" class C { static void Main() { (int, int, int, int, int, int, int, int) x = (""Alice"", 2, 3, 4, 5, 6, 7, 8); (int, int, int, int, int, int, int, int) y = (1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }).VerifyDiagnostics( // (6,55): error CS0029: Cannot implicitly convert type 'string' to 'int' // (int, int, int, int, int, int, int, int) x = ("Alice", 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Alice""").WithArguments("string", "int").WithLocation(6, 55), // (7,54): error CS0029: Cannot implicitly convert type '(int, int, int, int, int, int, int, int, int)' to '(int, int, int, int, int, int, int, int)' // (int, int, int, int, int, int, int, int) y = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("(int, int, int, int, int, int, int, int, int)", "(int, int, int, int, int, int, int, int)").WithLocation(7, 54) ); } [Fact] public void TupleTypeWithLateDiscoveredName() { var source = @" class C { static void Main() { (int, string a) x = (1, ""hello"", c: 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type '(int, string, int c)' to '(int, string a)' // (int, string a) x = (1, "hello", c: 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(1, ""hello"", c: 2)").WithArguments("(int, string, int c)", "(int, string a)").WithLocation(6, 29) ); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""hello"", c: 2)", node.ToString()); Assert.Equal("(System.Int32, System.String, System.Int32 c)", model.GetTypeInfo(node).Type.ToTestDisplayString()); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = model.GetDeclaredSymbol(x).GetSymbol<SourceLocalSymbol>().Type; Assert.Equal("(System.Int32, System.String a)", xSymbol.ToTestDisplayString()); Assert.True(xSymbol.IsTupleType); Assert.Equal(new[] { "System.Int32", "System.String" }, xSymbol.TupleElementTypesWithAnnotations.SelectAsArray(t => t.ToTestDisplayString())); Assert.Equal(new[] { null, "a" }, xSymbol.TupleElementNames); } [Fact] public void TupleTypeDeclarationWithNames() { var source = @" class C { static void Main() { (int a, string b) x = (1, ""hello""); System.Console.WriteLine(x.a.ToString()); System.Console.WriteLine(x.b.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 hello"); } [Fact] public void TupleTypeWithOnlySomeNames() { var source = @" class C { static void Main() { (int, string a, int Item3) x = (1, ""hello"", 3); System.Console.WriteLine(x.Item1 + "" "" + x.Item2 + "" "" + x.a + "" "" + x.Item3); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 hello hello 3"); } [Fact] public void TupleTypeWithOnlySomeNamesInMetadata() { var source1 = @" public class C { public static (int, string b, int Item3) M() { return (1, ""hello"", 3); } } "; var source2 = @" class D { public static void Main() { var t = C.M(); System.Console.WriteLine(t.Item1 + "" "" + t.Item2 + "" "" + t.b + "" "" + t.Item3); } } "; var comp1 = CreateCompilationWithMscorlib40(source2 + source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, expectedOutput: "1 hello hello 3"); var compLib = CreateCompilationWithMscorlib40(source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseDll); compLib.VerifyDiagnostics(); var compLibCompilationRef = compLib.ToMetadataReference(); var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, compLibCompilationRef }, options: TestOptions.ReleaseExe); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, expectedOutput: "1 hello hello 3"); var comp3 = CreateCompilationWithMscorlib40(source2, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, compLib.EmitToImageReference() }, options: TestOptions.ReleaseExe); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, expectedOutput: "1 hello hello 3"); } [Fact] public void TupleLiteralWithOnlySomeNames() { var source = @" class C { static void Main() { (int, string, int) x = (1, b: ""hello"", Item3: 3); System.Console.WriteLine(x.Item1 + "" "" + x.Item2 + "" "" + x.Item3); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 hello 3"); } [Fact] public void TupleDictionary01() { var source = @" using System.Collections.Generic; class C { static void Main() { var k = (1, 2); var v = (a: 1, b: (c: 2, d: (e: 3, f: 4))); var d = Test(k, v); System.Console.WriteLine(d[(1, 2)].b.d.Item2); } static Dictionary<K, V> Test<K, V>(K key, V value) { var d = new Dictionary<K, V>(); d[key] = value; return d; } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"4"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 67 (0x43) .maxstack 6 .locals init (System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>> V_0) //v IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.1 IL_000a: ldc.i4.2 IL_000b: ldc.i4.3 IL_000c: ldc.i4.4 IL_000d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0012: newobj ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0017: call ""System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>..ctor(int, System.ValueTuple<int, System.ValueTuple<int, int>>)"" IL_001c: ldloc.0 IL_001d: call ""System.Collections.Generic.Dictionary<System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>> C.Test<System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>>(System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>)"" IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0029: callvirt ""System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>> System.Collections.Generic.Dictionary<System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>>.this[System.ValueTuple<int, int>].get"" IL_002e: ldfld ""System.ValueTuple<int, System.ValueTuple<int, int>> System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>.Item2"" IL_0033: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0038: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: ret } "); } [Fact] public void TupleLambdaCapture01() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: a, f2: a); Func<T> f = () => x.f2; return f(); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<T, T> C.<>c__DisplayClass1_0<T>.x"" IL_0006: ldfld ""T System.ValueTuple<T, T>.Item2"" IL_000b: ret } "); } [Fact] public void TupleLambdaCapture02() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static string Test<T>(T a) { var x = (f1: a, f2: a); Func<string> f = () => x.ToString(); return f(); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"{42, 42}"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<T, T> C.<>c__DisplayClass1_0<T>.x"" IL_0006: constrained. ""System.ValueTuple<T, T>"" IL_000c: callvirt ""string object.ToString()"" IL_0011: ret } "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33615")] public void TupleLambdaCapture03() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: a, f2: a); Func<T> f = () => x.Test(a); return f(); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var comp = CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib46Extended, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""(T f1, T f2) C.<>c__DisplayClass1_0<T>.x"" IL_0006: ldarg.0 IL_0007: ldfld ""T C.<>c__DisplayClass1_0<T>.a"" IL_000c: call ""T System.ValueTuple<T, T>.Test<T>(T)"" IL_0011: ret } "); } [Fact] public void TupleLambdaCapture04() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: 1, f2: 2); Func<T> f = () => x.Test(a); return f(); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var comp = CompileAndVerify(source, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<int, int> C.<>c__DisplayClass1_0<T>.x"" IL_0006: ldarg.0 IL_0007: ldfld ""T C.<>c__DisplayClass1_0<T>.a"" IL_000c: call ""T System.ValueTuple<int, int>.Test<T>(T)"" IL_0011: ret } "); } [Fact] public void TupleLambdaCapture05() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: a, f2: a); Func<T> f = () => x.P1; return f(); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public T1 P1 { get { return Item1; } } } } "; var comp = CompileAndVerify(source, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<T, T> C.<>c__DisplayClass1_0<T>.x"" IL_0006: call ""T System.ValueTuple<T, T>.P1.get"" IL_000b: ret } "); } [Fact] public void TupleLambdaCapture06() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Action<int> d1 = (int i1) => System.Console.WriteLine(i1); v1.Test(v1, d1); Test(v1); } static void Test<T1, T2>((T1, T2) v1) { System.Action f = () => { System.Action<T1> d1 = (T1 i1) => System.Console.WriteLine(i1); System.Action<T2> d2 = (T2 i2) => System.Console.WriteLine(i2); v1.E1 += d1; v1.RaiseE1(); v1.E1 -= d1; v1.RaiseE1(); v1.E2 += d2; v1.RaiseE2(); v1.E2 -= d2; v1.RaiseE2(); }; f(); } static (int, long) M1() { return (1, 11); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this._e2 = null; } public event System.Action<T1> E1; private System.Action<T2> _e2; public event System.Action<T2> E2 { add { _e2 += value; } remove { _e2 -= value; } } public void RaiseE1() { System.Console.WriteLine(""-""); if (E1 == null) { System.Console.WriteLine(""null""); } else { E1(Item1); } System.Console.WriteLine(""-""); } public void RaiseE2() { System.Console.WriteLine(""--""); if (_e2 == null) { System.Console.WriteLine(""null""); } else { _e2(Item2); } System.Console.WriteLine(""--""); } public void Test<S1, S2>((S1, S2) val, System.Action<S1> d) { System.Action f= () => { val.E1 += d; System.Console.WriteLine(val.E1); val.E1(val.Item1); val.E1 -= d; System.Console.WriteLine(val.E1 == null); }; f(); } } } " + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"System.Action`1[System.Int32] 1 True - 1 - - null - -- 11 -- -- null --"); } [Fact] public void TupleAsyncCapture01() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.f1; } } " + trivial2uple + tupleattributes_cs; var verifier = CompileAndVerify(source, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 207 (0xcf) .maxstack 3 .locals init (int V_0, T V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""T C.<Test>d__1<T>.a"" IL_0011: ldarg.0 IL_0012: ldfld ""T C.<Test>d__1<T>.a"" IL_0017: newobj ""System.ValueTuple<T, T>..ctor(T, T)"" IL_001c: stfld ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_0056: leave.s IL_00ce IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005e: stloc.2 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0074: ldloca.s V_2 IL_0076: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_007b: ldarg.0 IL_007c: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0081: ldfld ""T System.ValueTuple<T, T>.Item1"" IL_0086: stloc.1 IL_0087: leave.s IL_00ae } catch System.Exception { IL_0089: stloc.s V_4 IL_008b: ldarg.0 IL_008c: ldc.i4.s -2 IL_008e: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0093: ldarg.0 IL_0094: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0099: initobj ""System.ValueTuple<T, T>"" IL_009f: ldarg.0 IL_00a0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00a5: ldloc.s V_4 IL_00a7: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetException(System.Exception)"" IL_00ac: leave.s IL_00ce } IL_00ae: ldarg.0 IL_00af: ldc.i4.s -2 IL_00b1: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00b6: ldarg.0 IL_00b7: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_00bc: initobj ""System.ValueTuple<T, T>"" IL_00c2: ldarg.0 IL_00c3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00c8: ldloc.1 IL_00c9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetResult(T)"" IL_00ce: ret } "); } [Fact] public void TupleAsyncCapture02() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<string> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.ToString(); } } " + trivial2uple + tupleattributes_cs; var verifier = CompileAndVerify(source, expectedOutput: @"{42, 42}", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 213 (0xd5) .maxstack 3 .locals init (int V_0, string V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""T C.<Test>d__1<T>.a"" IL_0011: ldarg.0 IL_0012: ldfld ""T C.<Test>d__1<T>.a"" IL_0017: newobj ""System.ValueTuple<T, T>..ctor(T, T)"" IL_001c: stfld ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string> C.<Test>d__1<T>.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_0056: leave.s IL_00d4 IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005e: stloc.2 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0074: ldloca.s V_2 IL_0076: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_007b: ldarg.0 IL_007c: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0081: constrained. ""System.ValueTuple<T, T>"" IL_0087: callvirt ""string object.ToString()"" IL_008c: stloc.1 IL_008d: leave.s IL_00b4 } catch System.Exception { IL_008f: stloc.s V_4 IL_0091: ldarg.0 IL_0092: ldc.i4.s -2 IL_0094: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0099: ldarg.0 IL_009a: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_009f: initobj ""System.ValueTuple<T, T>"" IL_00a5: ldarg.0 IL_00a6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string> C.<Test>d__1<T>.<>t__builder"" IL_00ab: ldloc.s V_4 IL_00ad: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string>.SetException(System.Exception)"" IL_00b2: leave.s IL_00d4 } IL_00b4: ldarg.0 IL_00b5: ldc.i4.s -2 IL_00b7: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00bc: ldarg.0 IL_00bd: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_00c2: initobj ""System.ValueTuple<T, T>"" IL_00c8: ldarg.0 IL_00c9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string> C.<Test>d__1<T>.<>t__builder"" IL_00ce: ldloc.1 IL_00cf: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string>.SetResult(string)"" IL_00d4: ret } "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33615")] public void TupleAsyncCapture03() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.Test(a); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var verifier = CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib46Extended, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 189 (0xbd) .maxstack 3 .locals init (int V_0, T V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""T C.<Test>d__1<T>.a"" IL_0011: ldarg.0 IL_0012: ldfld ""T C.<Test>d__1<T>.a"" IL_0017: newobj ""System.ValueTuple<T, T>..ctor(T, T)"" IL_001c: stfld ""(T f1, T f2) C.<Test>d__1<T>.<x>5__2"" IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_0056: leave.s IL_00bc IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005e: stloc.2 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0074: ldloca.s V_2 IL_0076: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_007b: ldarg.0 IL_007c: ldflda ""(T f1, T f2) C.<Test>d__1<T>.<x>5__2"" IL_0081: ldarg.0 IL_0082: ldfld ""T C.<Test>d__1<T>.a"" IL_0087: call ""T System.ValueTuple<T, T>.Test<T>(T)"" IL_008c: stloc.1 IL_008d: leave.s IL_00a8 } catch System.Exception { IL_008f: stloc.s V_4 IL_0091: ldarg.0 IL_0092: ldc.i4.s -2 IL_0094: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0099: ldarg.0 IL_009a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_009f: ldloc.s V_4 IL_00a1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetException(System.Exception)"" IL_00a6: leave.s IL_00bc } IL_00a8: ldarg.0 IL_00a9: ldc.i4.s -2 IL_00ab: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00b0: ldarg.0 IL_00b1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00b6: ldloc.1 IL_00b7: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetResult(T)"" IL_00bc: ret } "); } [Fact] public void TupleAsyncCapture04() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: 1, f2: 2); await Task.Yield(); return x.Test(a); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 179 (0xb3) .maxstack 3 .locals init (int V_0, T V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004e IL_000a: ldarg.0 IL_000b: ldc.i4.1 IL_000c: ldc.i4.2 IL_000d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0012: stfld ""System.ValueTuple<int, int> C.<Test>d__1<T>.<x>5__2"" IL_0017: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_001c: stloc.3 IL_001d: ldloca.s V_3 IL_001f: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0024: stloc.2 IL_0025: ldloca.s V_2 IL_0027: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_002c: brtrue.s IL_006a IL_002e: ldarg.0 IL_002f: ldc.i4.0 IL_0030: dup IL_0031: stloc.0 IL_0032: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0037: ldarg.0 IL_0038: ldloc.2 IL_0039: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_003e: ldarg.0 IL_003f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_0044: ldloca.s V_2 IL_0046: ldarg.0 IL_0047: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_004c: leave.s IL_00b2 IL_004e: ldarg.0 IL_004f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0054: stloc.2 IL_0055: ldarg.0 IL_0056: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0061: ldarg.0 IL_0062: ldc.i4.m1 IL_0063: dup IL_0064: stloc.0 IL_0065: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_006a: ldloca.s V_2 IL_006c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0071: ldarg.0 IL_0072: ldflda ""System.ValueTuple<int, int> C.<Test>d__1<T>.<x>5__2"" IL_0077: ldarg.0 IL_0078: ldfld ""T C.<Test>d__1<T>.a"" IL_007d: call ""T System.ValueTuple<int, int>.Test<T>(T)"" IL_0082: stloc.1 IL_0083: leave.s IL_009e } catch System.Exception { IL_0085: stloc.s V_4 IL_0087: ldarg.0 IL_0088: ldc.i4.s -2 IL_008a: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_008f: ldarg.0 IL_0090: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_0095: ldloc.s V_4 IL_0097: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetException(System.Exception)"" IL_009c: leave.s IL_00b2 } IL_009e: ldarg.0 IL_009f: ldc.i4.s -2 IL_00a1: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00a6: ldarg.0 IL_00a7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00ac: ldloc.1 IL_00ad: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetResult(T)"" IL_00b2: ret } "); } [Fact] public void TupleAsyncCapture05() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.P1; } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public T1 P1 { get { return Item1; } } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); } [Fact] public void TupleAsyncCapture06() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { var v1 = M1(); System.Action<int> d1 = (int i1) => System.Console.WriteLine(i1); v1.Test(v1, d1).Wait(); Test(v1).Wait(); } static async Task Test<T1, T2>((T1, T2) v1) { System.Action<T1> d1 = (T1 i1) => System.Console.WriteLine(i1); System.Action<T2> d2 = (T2 i2) => System.Console.WriteLine(i2); await Task.Yield(); v1.E1 += d1; v1.RaiseE1(); v1.E1 -= d1; v1.RaiseE1(); v1.E2 += d2; v1.RaiseE2(); v1.E2 -= d2; v1.RaiseE2(); } static (int, long) M1() { return (1, 11); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this._e2 = null; } public event System.Action<T1> E1; private System.Action<T2> _e2; public event System.Action<T2> E2 { add { _e2 += value; } remove { _e2 -= value; } } public void RaiseE1() { System.Console.WriteLine(""-""); if (E1 == null) { System.Console.WriteLine(""null""); } else { E1(Item1); } System.Console.WriteLine(""-""); } public void RaiseE2() { System.Console.WriteLine(""--""); if (_e2 == null) { System.Console.WriteLine(""null""); } else { _e2(Item2); } System.Console.WriteLine(""--""); } public async Task Test<S1, S2>((S1, S2) val, System.Action<S1> d) { d = d; await Task.Yield(); val.E1 += d; System.Console.WriteLine(val.E1); val.E1(val.Item1); val.E1 -= d; System.Console.WriteLine(val.E1 == null); } } } " + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"System.Action`1[System.Int32] 1 True - 1 - - null - -- 11 -- -- null --"); } [Fact] public void LongTupleWithSubstitution() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: 1, f2: 2, f3: 3, f4: 4, f5: 5, f6: 6, f7: 7, f8: a); await Task.Yield(); return x.f8; } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; CompileAndVerify(source, expectedOutput: @"42", targetFramework: TargetFramework.Mscorlib46, options: TestOptions.ReleaseExe); } [Fact] public void TupleUsageWithoutTupleLibrary() { var source = @" class C { static void Main() { (int, string) x = (1, ""hello""); } } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, string) x = (1, "hello"); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, string)").WithArguments("System.ValueTuple`2").WithLocation(6, 9), // (6,27): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, string) x = (1, "hello"); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, @"(1, ""hello"")").WithArguments("System.ValueTuple`2").WithLocation(6, 27) ); } [Fact] public void TupleUsageWithMissingTupleMembers() { var source = @" namespace System { public struct ValueTuple<T1, T2> { } } class C { static void Main() { (int, int) x = (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (11,20): warning CS0219: The variable 'x' is assigned but its value is never used // (int, int) x = (1, 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 20), // (11,24): error CS8128: Member '.ctor' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int, int) x = (1, 2); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "(1, 2)").WithArguments(".ctor", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 24) ); } [Fact] public void TupleWithDuplicateNames() { var source = @" class C { static void Main() { (int a, string a) x = (b: 1, b: ""hello"", b: 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, b: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "a").WithLocation(6, 24), // (6,38): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, b: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "b").WithLocation(6, 38), // (6,50): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, b: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "b").WithLocation(6, 50) ); } [Fact] public void TupleWithDuplicateReservedNames() { var source = @" class C { static void Main() { (int Item1, string Item1) x = (Item1: 1, Item1: ""hello""); (int Item2, string Item2) y = (Item2: 1, Item2: ""hello""); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,28): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // (int Item1, string Item1) x = (Item1: 1, Item1: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(6, 28), // (6,50): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // (int Item1, string Item1) x = (Item1: 1, Item1: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(6, 50), // (7,14): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item2, string Item2) y = (Item2: 1, Item2: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(7, 14), // (7,40): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item2, string Item2) y = (Item2: 1, Item2: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(7, 40) ); } [Fact] public void TupleWithNonReservedNames() { var source = @" class C { static void Main() { (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,37): error CS8125: Tuple member name 'Item10' is only allowed at position 10. // (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item10").WithArguments("Item10", "10").WithLocation(6, 37), // (6,61): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(6, 61), // (6,71): error CS8125: Tuple member name 'Item10' is only allowed at position 10. // (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item10").WithArguments("Item10", "10").WithLocation(6, 71) ); } [Fact] public void DefaultValueForTuple() { var source = @" class C { static void Main() { (int a, string b) x = (1, ""hello""); x = default((int, string)); System.Console.WriteLine(x.a); System.Console.WriteLine(x.b ?? ""null""); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"0 null"); } [Fact] public void TupleWithDuplicateMemberNames() { var source = @" class C { static void Main() { (int a, string a) x = (b: 1, c: ""hello"", b: 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, c: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "a").WithLocation(6, 24), // (6,50): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, c: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "b").WithLocation(6, 50) ); } [Fact] public void TupleWithReservedMemberNames() { var source = @" class C { static void Main() { (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: ""bad"", Item4: ""bad"", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: ""bad""); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,28): error CS8125: Tuple member name 'Item3' is only allowed at position 3. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item3").WithArguments("Item3", "3").WithLocation(6, 28), // (6,42): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(6, 42), // (6,100): error CS8126: Tuple member name 'Rest' is disallowed at any position. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Rest").WithArguments("Rest").WithLocation(6, 100), // (6,111): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(6, 111), // (6,125): error CS8125: Tuple member name 'Item4' is only allowed at position 4. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item4").WithArguments("Item4", "4").WithLocation(6, 125), // (6,189): error CS8126: Tuple member name 'Rest' is disallowed at any position. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Rest").WithArguments("Rest").WithLocation(6, 189) ); } [Fact] public void TupleWithExistingUnderlyingMemberNames() { var source = @" class C { static void Main() { var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8126: Tuple member name 'CompareTo' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "CompareTo").WithArguments("CompareTo").WithLocation(6, 18), // (6,43): error CS8126: Tuple member name 'Deconstruct' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Deconstruct").WithArguments("Deconstruct").WithLocation(6, 43), // (6,59): error CS8126: Tuple member name 'Equals' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Equals").WithArguments("Equals").WithLocation(6, 59), // (6,70): error CS8126: Tuple member name 'GetHashCode' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "GetHashCode").WithArguments("GetHashCode").WithLocation(6, 70), // (6,86): error CS8126: Tuple member name 'Rest' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Rest").WithArguments("Rest").WithLocation(6, 86), // (6,95): error CS8126: Tuple member name 'ToString' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "ToString").WithArguments("ToString").WithLocation(6, 95) ); } [Fact] public void TupleWithExistingInaccessibleUnderlyingMemberNames() { var source = @" class C { static void Main() { var x = (CombineHashCodes: 1, Create: 2, GetHashCodeCore: 3, Size: 4, ToStringEnd: 5); System.Console.WriteLine(x.CombineHashCodes + "" "" + x.Create + "" "" + x.GetHashCodeCore + "" "" + x.Size + "" "" + x.ToStringEnd); } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(DesktopOnly))] public void LongTupleDeclaration() { var source = @" class C { static void Main() { (int, int, int, int, int, int, int, string, int, int, int, int) x = (1, 2, 3, 4, 5, 6, 7, ""Alice"", 2, 3, 4, 5); System.Console.WriteLine($""{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} {x.Item9} {x.Item10} {x.Item11} {x.Item12}""); } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " + "System.String, System.Int32, System.Int32, System.Int32, System.Int32) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void LongTupleDeclarationWithNames() { var source = @" class C { static void Main() { (int a, int b, int c, int d, int e, int f, int g, string h, int i, int j, int k, int l) x = (1, 2, 3, 4, 5, 6, 7, ""Alice"", 2, 3, 4, 5); System.Console.WriteLine($""{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, " + "System.String h, System.Int32 i, System.Int32 j, System.Int32 k, System.Int32 l) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] // The used assemblies test hook is blocked by https://github.com/dotnet/roslyn/issues/39976 [WorkItem(39976, "https://github.com/dotnet/roslyn/issues/39976")] public void HugeTupleCreationParses() { StringBuilder b = new StringBuilder(); b.Append("("); for (int i = 0; i < 3000; i++) { b.Append("1, "); } b.Append("1)"); var source = @" class C { static void Main() { var x = " + b.ToString() + @"; } } "; CreateCompilation(source); } [ConditionalFact(typeof(NoIOperationValidation))] public void HugeTupleDeclarationParses() { StringBuilder b = new StringBuilder(); b.Append("("); for (int i = 0; i < 3000; i++) { b.Append("int, "); } b.Append("int)"); var source = @" class C { static void Main() { " + b.ToString() + @" x; } } "; CreateCompilation(source); } [Fact] public void GenericTupleWithoutTupleLibrary_01() { var source = @" class C { static void Main() { var x = M<int, bool>(); System.Console.WriteLine($""{x.first} {x.second}""); } static (T1 first, T2 second) M<T1, T2>() { return (default(T1), default(T2)); } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (10,12): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // static (T1 first, T2 second) M<T1, T2>() Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(T1 first, T2 second)").WithArguments("System.ValueTuple`2").WithLocation(10, 12), // (12,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (default(T1), default(T2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(default(T1), default(T2))").WithArguments("System.ValueTuple`2").WithLocation(12, 16) ); var c = comp.GetTypeByMetadataName("C"); var mTuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M").ReturnType; Assert.True(mTuple.IsTupleType); Assert.Equal(TypeKind.Error, mTuple.TupleUnderlyingType.TypeKind); Assert.Equal(SymbolKind.ErrorType, mTuple.TupleUnderlyingType.Kind); Assert.IsAssignableFrom<ErrorTypeSymbol>(mTuple.TupleUnderlyingType); Assert.Equal(TypeKind.Error, mTuple.TypeKind); AssertTupleTypeEquality(mTuple); Assert.False(mTuple.IsImplicitlyDeclared); Assert.Equal("Predefined type 'System.ValueTuple`2' is not defined or imported", mTuple.GetUseSiteDiagnostic().GetMessage(CultureInfo.InvariantCulture)); Assert.Null(mTuple.BaseType()); Assert.False(mTuple.TupleData.UnderlyingDefinitionToMemberMap.Any()); var mFirst = (FieldSymbol)mTuple.GetMembers("first").Single(); Assert.IsType<TupleErrorFieldSymbol>(mFirst); Assert.Equal("first", mFirst.Name); Assert.Same(mFirst, mFirst.OriginalDefinition); Assert.True(mFirst.Equals(mFirst)); Assert.Null(mFirst.TupleUnderlyingField); Assert.Null(mFirst.AssociatedSymbol); Assert.Same(mTuple, mFirst.ContainingSymbol); Assert.True(mFirst.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(mFirst.GetAttributes().IsEmpty); Assert.Null(mFirst.GetUseSiteDiagnostic()); Assert.False(mFirst.Locations.IsEmpty); Assert.Equal("T1 first", mFirst.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.False(mFirst.IsImplicitlyDeclared); Assert.Null(mFirst.TypeLayoutOffset); var mItem1 = (FieldSymbol)mTuple.GetMembers("Item1").Single(); Assert.IsType<TupleErrorFieldSymbol>(mItem1); Assert.Equal("Item1", mItem1.Name); Assert.Same(mItem1, mItem1.OriginalDefinition); Assert.True(mItem1.Equals(mItem1)); Assert.Null(mItem1.TupleUnderlyingField); Assert.Null(mItem1.AssociatedSymbol); Assert.Same(mTuple, mItem1.ContainingSymbol); Assert.True(mItem1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(mItem1.GetAttributes().IsEmpty); Assert.Null(mItem1.GetUseSiteDiagnostic()); Assert.True(mItem1.Locations.IsEmpty); Assert.True(mItem1.IsImplicitlyDeclared); Assert.Null(mItem1.TypeLayoutOffset); } [Fact] [WorkItem(11287, "https://github.com/dotnet/roslyn/issues/11287")] public void GenericTupleWithoutTupleLibrary_02() { var source = @" class C { static void Main() { } static (T1, T2, T3, T4, T5, T6, T7, T8, T9) M<T1, T2, T3, T4, T5, T6, T7, T8, T9>() { throw new System.NotSupportedException(); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (8,12): error CS8179: Predefined type 'System.ValueTuple`8' is not defined or imported // static (T1, T2, T3, T4, T5, T6, T7, T8, T9) M<T1, T2, T3, T4, T5, T6, T7, T8, T9>() Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(T1, T2, T3, T4, T5, T6, T7, T8, T9)").WithArguments("System.ValueTuple`8").WithLocation(8, 12) ); } [Fact] public void GenericTuple() { var source = @" class C { static void Main() { var x = M<int, bool>(); System.Console.WriteLine($""{x.first} {x.second}""); } static (T1 first, T2 second) M<T1, T2>() { return (default(T1), default(T2)); } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 False"); } [Fact] public void LongTupleCreation() { var source = @" class C { static void Main() { var x = (1, 2, 3, 4, 5, 6, 7, ""Alice"", 2, 3, 4, 5, 6, 7, ""Bob"", 2, 3); System.Console.WriteLine($""{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} {x.Item9} {x.Item10} {x.Item11} {x.Item12} {x.Item13} {x.Item14} {x.Item15} {x.Item16} {x.Item17}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " + "System.String, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " + "System.String, System.Int32, System.Int32)", model.GetTypeInfo(node).Type.ToTestDisplayString()); }; var verifier = CompileAndVerifyWithMscorlib40(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3", references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void TupleInLambda() { var source = @" class C { static void Main() { System.Action<(int, string)> f = ((int, string) x) => System.Console.WriteLine($""{x.Item1} {x.Item2}""); f((42, ""Alice"")); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void TupleWithNamesInLambda() { var source = @" class C { static void Main() { int a, b = 0; System.Action<(int, string)> f = ((int a, string b) x) => System.Console.WriteLine($""{x.a} {x.b}""); f((c: 42, d: ""Alice"")); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void TupleInProperty() { var source = @" class C { static (int a, string b) P { get; set; } static void Main() { P = (42, ""Alice""); System.Console.WriteLine($""{P.a} {P.b}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void ExtensionMethodOnTuple() { var source = @" static class C { static void Extension(this (int a, string b) x) { System.Console.WriteLine($""{x.a} {x.b}""); } static void Main() { (42, ""Alice"").Extension(); } } "; CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib45, references: new[] { Net451.System, Net451.SystemCore, Net451.SystemRuntime, ValueTupleRef }, expectedOutput: @"42 Alice"); } [Fact] public void TupleInOptionalParam() { var source = @" class C { void M(int x, (int a, string b) y = (42, ""Alice"")) { } } "; CreateCompilation(source).VerifyDiagnostics( // (4,41): error CS1736: Default parameter value for 'y' must be a compile-time constant // void M(int x, (int a, string b) y = (42, "Alice")) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"(42, ""Alice"")").WithArguments("y").WithLocation(4, 41)); } [Fact] public void TupleDefaultInOptionalParam() { var source = @" class C { public static void Main() { M(); } static void M((int a, string b) x = default((int, string))) { System.Console.WriteLine($""{x.a} {x.b}""); } } "; CompileAndVerify(source, expectedOutput: @"0 "); } [Fact] public void TupleAsNamedParam() { var source = @" class C { static void Main() { M(y : (42, ""Alice""), x : 1); } static void M(int x, (int a, string b) y) { System.Console.WriteLine($""{y.a} {y.Item2}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void LongTupleCreationWithNames() { var source = @" class C { static void Main() { var x = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: ""Alice"", i: 2, j: 3, k: 4, l: 5, m: 6, n: 7, o: ""Bob"", p: 2, q: 3); System.Console.WriteLine($""{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l} {x.m} {x.n} {x.o} {x.p} {x.q}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); var type = (INamedTypeSymbol)model.GetTypeInfo(node).Type; Assert.Equal("(System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, " + "System.String h, System.Int32 i, System.Int32 j, System.Int32 k, System.Int32 l, System.Int32 m, System.Int32 n, " + "System.String o, System.Int32 p, System.Int32 q)", type.ToTestDisplayString()); foreach (var item in type.TupleElements) { Assert.True(item.IsExplicitlyNamedTupleElement); Assert.False(item.CorrespondingTupleField.IsExplicitlyNamedTupleElement); } }; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void TupleCreationWithInferredNamesWithCSharp7() { var source = @" class C { int e = 5; int f = 6; C instance = null; void M() { int a = 1; int b = 3; int Item4 = 4; int g = 7; int Rest = 9; (int x, int, int b, int, int, int, int f, int, int, int) y = (a, (a), b: 2, b, Item4, instance.e, this.f, g, g, Rest); var z = (x: b, b); System.Console.Write(y); System.Console.Write(z); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var yTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); var yType = (INamedTypeSymbol)model.GetTypeInfo(yTuple).Type; Assert.Equal("(System.Int32 a, System.Int32, System.Int32 b, System.Int32, System.Int32, System.Int32 e, System.Int32 f, System.Int32, System.Int32, System.Int32)", yType.ToTestDisplayString()); Assert.Equal("a", yType.TupleElements[0].Name); Assert.True(yType.TupleElements[0].IsExplicitlyNamedTupleElement); Assert.False(yType.TupleElements[0].CorrespondingTupleField.IsExplicitlyNamedTupleElement); Assert.Equal("Item2", yType.TupleElements[1].Name); Assert.False(yType.TupleElements[1].IsExplicitlyNamedTupleElement); Assert.Same(yType.TupleElements[1], yType.TupleElements[1].CorrespondingTupleField); Assert.Equal("b", yType.TupleElements[2].Name); Assert.True(yType.TupleElements[2].IsExplicitlyNamedTupleElement); Assert.False(yType.TupleElements[2].CorrespondingTupleField.IsExplicitlyNamedTupleElement); var zTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(System.Int32 x, System.Int32 b)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void MissingMemberAccessWithCSharp7() { var source = @" class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); System.Console.Write(GetTuple().a); } (int, int) GetTuple() { return (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (8,32): error CS8305: Tuple element name 'a' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "a").WithArguments("a", "7.1").WithLocation(8, 32), // (9,41): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(GetTuple().a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(9, 41) ); } [Fact] public void UseSiteDiagnosticOnTupleField() { var missing_cs = @"public class Missing { }"; var lib_cs = @" public class C { public static (Missing, int) GetTuple() { throw null; } } "; var source_cs = @" class D { void M() { System.Console.Write(C.GetTuple().Item1); } }"; var missingComp = CreateCompilation(missing_cs, assemblyName: "UseSiteDiagnosticOnTupleField_missingComp"); missingComp.VerifyDiagnostics(); var libComp = CreateCompilationWithMscorlib40(lib_cs, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, missingComp.ToMetadataReference() }); libComp.VerifyDiagnostics(); var comp7 = CreateCompilationWithMscorlib40(source_cs, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular); comp7.VerifyDiagnostics( // (6,30): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C.GetTuple").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,43): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Item1").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); var comp7_1 = CreateCompilationWithMscorlib40(source_cs, assemblyName: "UseSiteDiagnosticOnTupleField_comp7_1", references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular7_1); comp7_1.VerifyDiagnostics( // (6,30): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C.GetTuple").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,43): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Item1").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); } [Fact] public void UseSiteDiagnosticOnTupleField2() { var source_cs = @" public class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); } } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } "; var comp7 = CreateCompilation(source_cs, parseOptions: TestOptions.Regular, assemblyName: "UseSiteDiagnosticOnTupleField2_comp7"); comp7.VerifyDiagnostics( // (8,32): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'UseSiteDiagnosticOnTupleField2_comp7, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "UseSiteDiagnosticOnTupleField2_comp7, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 32) ); var comp7_1 = CreateCompilation(source_cs, parseOptions: TestOptions.Regular7_1, assemblyName: "UseSiteDiagnosticOnTupleField2_comp7_1"); comp7_1.VerifyDiagnostics( // (8,32): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'UseSiteDiagnosticOnTupleField2_comp7_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "UseSiteDiagnosticOnTupleField2_comp7_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 32) ); } [Fact] public void MissingMemberAccessWithExtensionWithCSharp7() { var source = @" class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); System.Console.Write(t.a()); System.Console.Write(GetTuple().a); } (int, int) GetTuple() { return (1, 2); } } public static class Extensions { public static string a(this (int, int) self) { return ""hello""; } } "; var comp = CreateCompilationWithMscorlib45(source, references: new[] { Net451.System, Net451.SystemCore, Net451.SystemRuntime, ValueTupleRef }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (8,32): error CS8305: Tuple element name 'a' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "a").WithArguments("a", "7.1").WithLocation(8, 32), // (10,30): error CS1503: Argument 1: cannot convert from 'method group' to 'string' // System.Console.Write(GetTuple().a); Diagnostic(ErrorCode.ERR_BadArgType, "GetTuple().a").WithArguments("1", "method group", "string") ); } [Fact] public void MissingMemberAccessWithCSharp7_1() { var source = @" class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); System.Console.Write(t.b); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (9,32): error CS1061: '(int a, int)' does not contain a definition for 'b' and no extension method 'b' accepting a first argument of type '(int a, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(t.b); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b").WithArguments("(int a, int)", "b").WithLocation(9, 32) ); } [Fact] public void TupleCreationWithInferredNames() { var source = @" class C { int e = 5; int f = 6; C instance = null; string M() { int a = 1; int b = 3; int Item4 = 4; int g = 7; int Rest = 9; (int x, int, int b, int, int, int, int f, int, int, int) y = (a, (a), b: 2, b, Item4, instance.e, this.f, g, g, Rest); var z = (x: b, b); System.Console.Write(y); System.Console.Write(z); return null; } int P { set { var t = (M(), value); System.Console.Write(t.value); } } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var yTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(System.Int32 a, System.Int32, System.Int32 b, System.Int32, System.Int32, System.Int32 e, System.Int32 f, System.Int32, System.Int32, System.Int32)", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()); var zTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(System.Int32 x, System.Int32 b)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()); var tTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("(System.String, System.Int32 value)", model.GetTypeInfo(tTuple).Type.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void TupleCreationWithInferredNames2() { var source = @" class C { private int e = 5; } class C2 { C instance = null; C2 instance2 = null; int M() { var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); System.Console.Write(y); return 42; } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); compilation.VerifyDiagnostics( // (12,27): error CS0122: 'C.e' is inaccessible due to its protection level // var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); Diagnostic(ErrorCode.ERR_BadAccess, ".e").WithArguments("C.e").WithLocation(12, 27), // (12,41): error CS0122: 'C.e' is inaccessible due to its protection level // var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); Diagnostic(ErrorCode.ERR_BadAccess, "e").WithArguments("C.e").WithLocation(12, 41), // (12,76): error CS0122: 'C.e' is inaccessible due to its protection level // var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); Diagnostic(ErrorCode.ERR_BadAccess, "e").WithArguments("C.e").WithLocation(12, 76), // (4,17): warning CS0414: The field 'C.e' is assigned but its value is never used // private int e = 5; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("C.e") ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); // The type for int? was not picked up // Follow-up issue: https://github.com/dotnet/roslyn/issues/19144 var yTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(? e, (System.Int32 e, System.Int32, System.Int32, System.Int32))", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()); } [Fact] public void InferredNamesInLinq() { var source = @" using System.Collections.Generic; using System.Linq; class C { int f1 = 0; int f2 = 1; static void M(IEnumerable<C> list) { var result = list.Select(c => (c.f1, c.f2)).Where(t => t.f2 == 1); // t and result have names f1 and f2 System.Console.Write(result.Count()); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var result = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "result").Single(); var resultSymbol = model.GetDeclaredSymbol(result); Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 f1, System.Int32 f2)> result", resultSymbol.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void InferredNamesInTernary() { var source = @" class C { static void Main() { var i = 1; var flag = false; var t = flag ? (i, 2) : (i, 3); System.Console.Write(t.i); } } "; var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), targetFramework: TargetFramework.Mscorlib46Extended, expectedOutput: "1"); verifier.VerifyDiagnostics(); } [Fact] public void InferredNames_ExtensionNowFailsInCSharp7ButNotCSharp7_1() { var source = @" using System; class C { static void Main() { Action M = () => Console.Write(""lambda""); (1, M).M(); } } static class Extension { public static void M(this (int, Action) t) => Console.Write(""extension""); } "; // When C# 7.0 shipped, no tuple element would be found/inferred, so the extension method was called. // The C# 7.1 compiler disallows that, even when LanguageVersion is 7.0 var comp7 = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp7.VerifyDiagnostics( // (8,16): error CS8305: Tuple element name 'M' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // (1, M).M(); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "M").WithArguments("M", "7.1") ); var verifier7_1 = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), expectedOutput: "lambda"); verifier7_1.VerifyDiagnostics(); } [WorkItem(21518, "https://github.com/dotnet/roslyn/issues/21518")] [Fact] public void InferredName_Conversion() { var source = @"class C { static void F((object, object) t) { } static void G(object o) { var t = (1, o); F(t); } }"; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef }); comp.VerifyEmitDiagnostics(); } [Fact] public void LongTupleWithArgumentEvaluation() { var source = @" class C { static void Main() { var x = (a: PrintAndReturn(1), b: 2, c: 3, d: PrintAndReturn(4), e: 5, f: 6, g: PrintAndReturn(7), h: PrintAndReturn(""Alice""), i: 2, j: 3, k: 4, l: 5, m: 6, n: PrintAndReturn(7), o: PrintAndReturn(""Bob""), p: 2, q: PrintAndReturn(3)); x.ToString(); } static T PrintAndReturn<T>(T i) { System.Console.Write(i + "" ""); return i; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 4 7 Alice 7 Bob 3"); verifier.VerifyDiagnostics(); } [Fact] public void LongTupleGettingRest() { var source = @" class C { static void Main() { var x = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: ""Alice"", i: 1); System.Console.WriteLine($""{x.Rest.Item1} {x.Rest.Item2}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<MemberAccessExpressionSyntax>().Where(n => n.ToString() == "x.Rest").First(); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(node).Type.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, expectedOutput: @"Alice 1", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void MethodReturnsValueTuple() { var source = @" class C { static void Main() { System.Console.WriteLine(M().ToString()); } static (int, string) M() { return (1, ""hello""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"(1, hello)"); } [Fact] public void DistinctTupleTypesInCompilation() { var source1 = @" public class C1 { public static (int a, int b) M() { return (1, 2); } } "; var source2 = @" public class C2 { public static (int c, int d) M() { return (3, 4); } } "; var source = @" class C3 { public static void Main() { System.Console.Write(C1.M().Item1 + "" ""); System.Console.Write(C1.M().a + "" ""); System.Console.Write(C1.M().Item2 + "" ""); System.Console.Write(C1.M().b + "" ""); System.Console.Write(C2.M().Item1 + "" ""); System.Console.Write(C2.M().c + "" ""); System.Console.Write(C2.M().Item2 + "" ""); System.Console.Write(C2.M().d); } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); var comp = CompileAndVerify(source, expectedOutput: @"1 1 2 2 3 3 4 4", references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2), }); } [Fact] public void DistinctTupleTypesInCompilationCanAssign() { var source1 = @" public class C1 { public static (int a, int b) M() { System.Console.WriteLine(""C1.M""); return (1, 2); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public static (int c, int d) M() { System.Console.WriteLine(""C2.M""); return (3, 4); } } " + trivial2uple + tupleattributes_cs; var source = @" class C3 { public static void Main() { var x = C1.M(); x = C2.M(); } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); var comp = CreateCompilation(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, expectedOutput: @" C1.M C2.M "); v.VerifyIL("C3.Main()", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: call ""System.ValueTuple<int, int> C1.M()"" IL_0005: pop IL_0006: call ""System.ValueTuple<int, int> C2.M()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0012: ldloc.0 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_001d: pop IL_001e: ret } "); } [Fact] public void AmbiguousTupleTypesForCreationWithVar() { var source = @" class C3 { public static void Main() { var x = (1, 1); } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); } [Fact] public void AmbiguousTupleTypesForCreation() { var source = @" class C3 { public static void Main() { (int, int) x = (1, 1); } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); comp.VerifyDiagnostics( // (6,9): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9), // (6,24): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 24) ); } [Fact] public void AmbiguousTupleTypesForDeclaration() { var source = @" class C3 { public void M((int, int) x) { } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); comp.VerifyDiagnostics( // (4,19): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public void M((int, int) x) { } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 19) ); } [Fact] public void LocalTupleTypeWinsWhenTupleTypesInCompilation() { var source1 = @" public class C1 { public static (int a, int b) M() { return (1, 2); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public static (int c, int d) M() { return (3, 4); } } " + trivial2uple + tupleattributes_cs; var source = @" class C3 { public static void Main() { System.Console.Write(C1.M().Item1 + "" ""); System.Console.Write(C1.M().a + "" ""); System.Console.Write(C1.M().Item2 + "" ""); System.Console.Write(C1.M().b + "" ""); System.Console.Write(C2.M().Item1 + "" ""); System.Console.Write(C2.M().c + "" ""); System.Console.Write(C2.M().Item2 + "" ""); System.Console.Write(C2.M().d + "" ""); var x = (e: 5, f: 6); System.Console.Write(x.Item1 + "" ""); System.Console.Write(x.e + "" ""); System.Console.Write(x.Item2 + "" ""); System.Console.Write(x.f + "" ""); System.Console.Write(x.GetType().Assembly == typeof(C3).Assembly); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40(source1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40(source2); comp2.VerifyDiagnostics(); var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: @"1 1 2 2 3 3 4 4 5 5 6 6 True", references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); } [Fact] public void UnderlyingTypeMemberWithWrongSignature_1() { string source = @" class C { static void M() { var x = (""Alice"", ""Bob""); System.Console.WriteLine($""{x.Item1}""); } } namespace System { public struct ValueTuple<T1, T2> { public string Item1; // Not T1 public int Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = ""1""; this.Item2 = 2; } (T1, T2) M1() => throw null; (T1 a, T2 b) M2() => throw null; } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (20,18): error CS0229: Ambiguity between '(T1, T2).Item1' and '(T1, T2).Item1' // this.Item1 = "1"; Diagnostic(ErrorCode.ERR_AmbigMember, "Item1").WithArguments("(T1, T2).Item1", "(T1, T2).Item1").WithLocation(20, 18), // (21,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = 2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(21, 18), // (18,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(18, 16), // (18,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(18, 16), // (18,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(18, 16), // (18,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(18, 16), // (7,39): error CS0229: Ambiguity between '(string, string).Item1' and '(string, string).Item1' // System.Console.WriteLine($"{x.Item1}"); Diagnostic(ErrorCode.ERR_AmbigMember, "Item1").WithArguments("(string, string).Item1", "(string, string).Item1").WithLocation(7, 39), // (6,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = ("Alice", "Bob"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13) ); var vt2 = comp.GetTypeByMetadataName("System.ValueTuple`2"); Assert.True(vt2.IsTupleType); Assert.True(vt2.IsDefinition); AssertEx.Equal(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, vt2.TupleElements.ToTestDisplayStrings()); vt2.TupleElements.All(e => verifyTupleErrorField(e)); AssertEx.Equal(new[] { "System.String (T1, T2).Item1", "System.Int32 (T1, T2).Item2", "(T1, T2)..ctor(T1 item1, T2 item2)", "(T1, T2) (T1, T2).M1()", "(T1 a, T2 b) (T1, T2).M2()", "(T1, T2)..ctor()", "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, vt2.GetMembers().ToTestDisplayStrings()); var stringItem1 = vt2.GetMembers("Item1")[0]; Assert.Equal("System.String (T1, T2).Item1", stringItem1.ToTestDisplayString()); Assert.Equal(-1, ((FieldSymbol)stringItem1).TupleElementIndex); var intItem2 = vt2.GetMembers("Item2")[0]; Assert.Equal("System.Int32 (T1, T2).Item2", intItem2.ToTestDisplayString()); Assert.Equal(-1, ((FieldSymbol)intItem2).TupleElementIndex); var unnamedTuple = (NamedTypeSymbol)((MethodSymbol)vt2.GetMember("M1")).ReturnType; Assert.Equal("(T1, T2)", unnamedTuple.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, unnamedTuple.Kind); Assert.True(unnamedTuple.IsDefinition); Assert.True(unnamedTuple.IsTupleType); Assert.Same(vt2, unnamedTuple); Assert.IsType<SourceNamedTypeSymbol>(unnamedTuple); Assert.Same(vt2, unnamedTuple.ConstructedFrom); Assert.Same(unnamedTuple, unnamedTuple.OriginalDefinition); Assert.Same(unnamedTuple, unnamedTuple.TupleUnderlyingType); var namedTuple = (NamedTypeSymbol)((MethodSymbol)vt2.GetMember("M2")).ReturnType; Assert.Equal("(T1 a, T2 b)", namedTuple.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, namedTuple.Kind); Assert.False(namedTuple.IsDefinition); Assert.True(namedTuple.IsTupleType); Assert.IsType<ConstructedNamedTypeSymbol>(namedTuple); Assert.NotSame(vt2, namedTuple); Assert.Same(vt2, namedTuple.ConstructedFrom); Assert.Same(vt2, namedTuple.OriginalDefinition); Assert.False(namedTuple.Equals(namedTuple.TupleUnderlyingType, TypeCompareKind.ConsiderEverything)); Assert.True(namedTuple.Equals(namedTuple.TupleUnderlyingType, TypeCompareKind.IgnoreTupleNames)); bool verifyTupleErrorField(FieldSymbol field) { var errorField = field as TupleErrorFieldSymbol; Assert.NotNull(errorField); Assert.True(errorField.IsDefinition); Assert.True(errorField.TupleElementIndex != -1); return true; } } [Fact] public void UnderlyingTypeMemberWithWrongSignature_2() { string source = @" class C { (string, string) M() { var x = (""Alice"", ""Bob""); System.Console.WriteLine($""{x.Item1}""); return x; } void M2((int a, int b) y) { System.Console.WriteLine($""{y.Item1}""); System.Console.WriteLine($""{y.a}""); System.Console.WriteLine($""{y.Item2}""); System.Console.WriteLine($""{y.b}""); } } namespace System { public struct ValueTuple<T1, T2> { public int Item2; public ValueTuple(T1 item1, T2 item2) { this.Item2 = 2; } } } "; var comp = CreateCompilationWithMscorlib40(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (11,13): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // void M2((int a, int b) y) Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int a, int b)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(11, 13), // (28,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = 2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(28, 18), // (26,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(26, 16), // (26,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(26, 16), // (26,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(26, 16), // (7,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.Item1}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 39), // (13,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{y.Item1}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(13, 39), // (14,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{y.a}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(14, 39), // (15,39): error CS0229: Ambiguity between '(int a, int b).Item2' and '(int a, int b).Item2' // System.Console.WriteLine($"{y.Item2}"); Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(int a, int b).Item2", "(int a, int b).Item2").WithLocation(15, 39), // (16,39): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{y.b}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "b").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(16, 39) ); var mTuple = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").ReturnType; AssertTupleTypeEquality(mTuple); var mItem1 = (FieldSymbol)mTuple.GetMembers("Item1").Single(); Assert.IsType<TupleErrorFieldSymbol>(mItem1); Assert.Same(mItem1, mItem1.OriginalDefinition); Assert.True(mItem1.Equals(mItem1)); Assert.Equal("Item1", mItem1.Name); Assert.Null(mItem1.TupleUnderlyingField); Assert.Null(mItem1.AssociatedSymbol); Assert.Same(mTuple, mItem1.ContainingSymbol); Assert.True(mItem1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(mItem1.GetAttributes().IsEmpty); Assert.Equal("error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.", mItem1.GetUseSiteDiagnostic().ToString(EnsureEnglishUICulture.PreferredOrNull)); Assert.True(mItem1.Locations.IsEmpty); Assert.True(mItem1.DeclaringSyntaxReferences.IsEmpty); Assert.True(mItem1.IsImplicitlyDeclared); Assert.Null(mItem1.TypeLayoutOffset); // Note: fields come first AssertTestDisplayString(mTuple.GetMembers(), "System.Int32 (System.String, System.String).Item2", "System.String (System.String, System.String).Item1", "System.String (System.String, System.String).Item2", "(System.String, System.String)..ctor(System.String item1, System.String item2)", "(System.String, System.String)..ctor()"); var m2Tuple = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M2").Parameters[0].Type; AssertTupleTypeEquality(m2Tuple); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a, System.Int32 b).Item2", "System.Int32 (System.Int32 a, System.Int32 b).Item1", "System.Int32 (System.Int32 a, System.Int32 b).a", "System.Int32 (System.Int32 a, System.Int32 b).Item2", "System.Int32 (System.Int32 a, System.Int32 b).b", "(System.Int32 a, System.Int32 b)..ctor(System.Int32 item1, System.Int32 item2)", "(System.Int32 a, System.Int32 b)..ctor()" ); } [Fact] public void UnderlyingTypeMemberWithWrongSignature_3() { string source = @" class C { static void M() { var x = (a: ""Alice"", b: ""Bob""); System.Console.WriteLine($""{x.a}""); } } namespace System { public struct ValueTuple<T1, T2> { public int Item2; public ValueTuple(T1 item1, T2 item2) { this.Item2 = 2; } } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (7,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.a}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 39), // (17,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(17, 16), // (17,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(17, 16), // (17,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(17, 16), // (19,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = 2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(19, 18) ); } [Fact] public void UnderlyingTypeMemberWithWrongSignature_4() { string source = @" class C { static void M() { var x = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9); System.Console.WriteLine($""{x.a}""); System.Console.WriteLine($""{x.g}""); System.Console.WriteLine($""{x.h}""); System.Console.WriteLine($""{x.i}""); } } namespace System { public struct ValueTuple<T1, T2> { } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public TRest Rest; } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (7,39): error CS8128: Member 'Item1' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.a}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 39), // (8,39): error CS8128: Member 'Item7' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.g}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "g").WithArguments("Item7", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 39), // (9,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.h}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "h").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 39), // (10,39): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.i}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "i").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(10, 39) ); } [Fact] public void ImplementTupleInterface() { string source = @" public interface I { (int, int) M((string, string) a); } class C : I { static void Main() { I i = new C(); var r = i.M((""Alice"", ""Bob"")); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } public (int, int) M((string, string) a) { return (a.Item1.Length, a.Item2.Length); } } "; var comp = CompileAndVerify(source, expectedOutput: @"5 3"); comp.VerifyDiagnostics(); } [Fact] public void ImplementLongTupleInterface() { string source = @" public interface I { (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) a); } class C : I { static void Main() { I i = new C(); var r = i.M((1, 2, 3, 4, 5, 6, 7, 8)); System.Console.WriteLine($""{r.Item1} {r.Item7} {r.Item8}""); } public (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) a) { return a; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 7 8"); comp.VerifyDiagnostics(); } [Fact] public void ImplementTupleInterfaceWithValueTuple() { string source = @" public interface I { (int, int) M((string, string) a); } class C : I { static void Main() { I i = new C(); var r = i.M((""Alice"", ""Bob"")); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) { return (a.Item1.Length, a.Item2.Length); } } "; var comp = CompileAndVerify(source, expectedOutput: @"5 3"); comp.VerifyDiagnostics(); } [Fact] public void ImplementTupleInterfaceWithValueTuple2() { string source = @" public interface I { (int i1, int i2) M((string, string) a); } class C : I { public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) { return (1, 2); } void M(I i, C c) { var result1 = i.M((null, null)); System.Console.Write(result1.i1); var result2 = c.M((null, null)); System.Console.Write(result2.i1); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,38): error CS1061: '(int, int)' does not contain a definition for 'i1' and no extension method 'i1' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result2.i1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "i1").WithArguments("(int, int)", "i1").WithLocation(19, 38) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation1 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("i.M((null, null))", invocation1.ToString()); Assert.Equal("(System.Int32 i1, System.Int32 i2) I.M((System.String, System.String) a)", model.GetSymbolInfo(invocation1.Expression).Symbol.ToTestDisplayString()); var invocation2 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(2); Assert.Equal("c.M((null, null))", invocation2.ToString()); Assert.Equal("(System.Int32, System.Int32) C.M((System.String, System.String) a)", model.GetSymbolInfo(invocation2.Expression).Symbol.ToTestDisplayString()); } [Fact] public void ImplementValueTupleInterfaceWithTuple() { string source = @" public interface I { System.ValueTuple<int, int> M(System.ValueTuple<string, string> a); } class C : I { static void Main() { I i = new C(); var r = i.M((""Alice"", ""Bob"")); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } public (int, int) M((string, string) a) { return new System.ValueTuple<int, int>(a.Item1.Length, a.Item2.Length); } } "; var comp = CompileAndVerify(source, expectedOutput: @"5 3"); comp.VerifyDiagnostics(); } [Fact] public void ImplementInterfaceWithGeneric() { string source = @" public interface I<TB, TA> where TB : TA { (TB, TA, TC) M<TC>((TB, (TA, TC)) arg) where TC : TB; } public class CA { public override string ToString() { return ""CA""; } } public class CB : CA { public override string ToString() { return ""CB""; } } public class CC : CB { public override string ToString() { return ""CC""; } } class C : I<CB, CA> { static void Main() { I<CB, CA> i = new C(); var r = i.M((new CB(), (new CA(), new CC()))); System.Console.WriteLine($""{r.Item1} {r.Item2} {r.Item3}""); } public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) where TC : CB { return (arg.Item1, arg.Item2.Item1, arg.Item2.Item2); } } "; var comp = CompileAndVerify(source, expectedOutput: @"CB CA CC"); comp.VerifyDiagnostics(); } [Fact] public void ImplementInterfaceWithGenericError() { string source = @" public interface I<TB, TA> where TB : TA { (TB, TA, TC) M<TC>((TB, (TA, TC)) arg) where TC : TB; } public class CA { } public class CB : CA { } public class CC : CB { } class C1 : I<CB, CA> { public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) { return (arg.Item1, arg.Item2.Item1, arg.Item2.Item2); } } class C2 : I<CB, CA> { public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) where TC : CB { return (arg.Item2.Item1, arg.Item1, arg.Item2.Item2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,25): error CS0425: The constraints for type parameter 'TC' of method 'C1.M<TC>((CB, (CA, TC)))' must match the constraints for type parameter 'TC' of interface method 'I<CB, CA>.M<TC>((CB, (CA, TC)))'. Consider using an explicit interface implementation instead. // public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("TC", "C1.M<TC>((CB, (CA, TC)))", "TC", "I<CB, CA>.M<TC>((CB, (CA, TC)))").WithLocation(15, 25), // (25,17): error CS0029: Cannot implicitly convert type 'CA' to 'CB' // return (arg.Item2.Item1, arg.Item1, arg.Item2.Item2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "arg.Item2.Item1").WithArguments("CA", "CB").WithLocation(25, 17) ); } [Fact] public void OverrideTupleMethodWithDifferentNames() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int e, int f) M((int g, int h) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,36): error CS8139: 'D.M((int g, int h))': cannot change tuple element names when overriding inherited member 'C.M((int c, int d))' // public override (int e, int f) M((int g, int h) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M((int g, int h))", "C.M((int c, int d))").WithLocation(11, 36) ); } [Fact] public void OverrideTupleMethodWithDifferentNamesInParameterType() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int, int) M((int g, int h) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,32): error CS8139: 'D.M((int g, int h))': cannot change tuple element names when overriding inherited member 'C.M((int c, int d))' // public override (int, int) M((int g, int h) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M((int g, int h))", "C.M((int c, int d))").WithLocation(11, 32) ); } [Fact] public void OverrideTupleMethodWithDifferentNamesInReturnType() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int e, int f) M((int, int) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,36): error CS8139: 'D.M((int, int))': cannot change tuple element names when overriding inherited member 'C.M((int c, int d))' // public override (int e, int f) M((int, int) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M((int, int))", "C.M((int c, int d))").WithLocation(11, 36) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTupleMethodWithNoNames() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int, int) M((int, int) y) { return y; } } class E { void M(D d) { var result = d.M((1, 2)); System.Console.Write(result.a); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (21,37): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(21, 37) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("d.M((1, 2))", invocation.ToString()); Assert.Equal("(System.Int32, System.Int32) D.M((System.Int32, System.Int32) y)", model.GetSymbolInfo(invocation.Expression).Symbol.ToTestDisplayString()); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTupleMethodWithNoNamesWithValueTuple() { string source = @" using System; class C { public virtual (int a, int b) M((int c, int d) x) { throw null; } } class D : C { public override ValueTuple<int, int> M(ValueTuple<int, int> y) { return y; } } class E { void M(D d) { var result = d.M((1, 2)); System.Console.Write(result.a); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,37): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(22, 37) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("d.M((1, 2))", invocation.ToString()); Assert.Equal("(System.Int32, System.Int32) D.M((System.Int32, System.Int32) y)", model.GetSymbolInfo(invocation.Expression).Symbol.ToTestDisplayString()); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTuplePropertyWithNoNames() { string source = @" class C { public virtual (int a, int b) P { get; set; } } class D : C { public override (int, int) P { get; set; } void M(D d) { var result = d.P; var result2 = this.P; var result3 = base.P; System.Console.Write(result.a); System.Console.Write(result2.a); System.Console.Write(result3.a); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,37): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(14, 37), // (15,38): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result2.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(15, 38) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var memberAccess = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ElementAt(0); Assert.Equal("d.P", memberAccess.ToString()); Assert.Equal("(System.Int32, System.Int32) D.P { get; set; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); var memberAccess2 = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ElementAt(1); Assert.Equal("this.P", memberAccess2.ToString()); Assert.Equal("(System.Int32, System.Int32) D.P { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); var memberAccess3 = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ElementAt(2); Assert.Equal("base.P", memberAccess3.ToString()); Assert.Equal("(System.Int32 a, System.Int32 b) C.P { get; set; }", model.GetSymbolInfo(memberAccess3).Symbol.ToTestDisplayString()); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTupleEventWithNoNames() { string source = @" class C { public virtual event System.Func<((int a, int b) c, int d)> E; } class D : C { public override event System.Func<((int, int), int)> E; void M(D d) { var result = d.E(); System.Console.Write(result.c); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,37): error CS1061: '((int, int), int)' does not contain a definition for 'c' and no extension method 'c' accepting a first argument of type '((int, int), int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.c); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c").WithArguments("((int, int), int)", "c").WithLocation(12, 37), // (4,65): warning CS0067: The event 'C.E' is never used // public virtual event System.Func<((int a, int b) c, int d)> E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(4, 65) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("d.E()", invocation.ToString()); Assert.Equal("event System.Func<((System.Int32, System.Int32), System.Int32)> D.E", model.GetSymbolInfo(invocation.Expression).Symbol.ToTestDisplayString()); } [Fact] public void NewTupleMethodWithDifferentNames() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { System.Console.WriteLine(""base""); return x; } } class D : C { static void Main() { D d = new D(); d.M((1, 2)); C c = d; c.M((1, 2)); } public new (int e, int f) M((int g, int h) y) { System.Console.Write(""new ""); return y; } } "; var comp = CompileAndVerify(source, expectedOutput: @"new base"); comp.VerifyDiagnostics(); } [Fact] public void DuplicateTupleMethodsNotAllowed() { string source = @" class C { public (int, int) M((string, string) a) { return new System.ValueTuple<int, int>(a.Item1.Length, a.Item2.Length); } public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) { return (a.Item1.Length, a.Item2.Length); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,40): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types // public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(9, 40) ); } [Fact] public void TupleArrays() { string source = @" public interface I { System.ValueTuple<int, int>[] M((int, int)[] a); } class C : I { static void Main() { I i = new C(); var r = i.M(new [] { new System.ValueTuple<int, int>(1, 2) }); System.Console.WriteLine($""{r[0].Item1} {r[0].Item2}""); } public (int, int)[] M(System.ValueTuple<int, int>[] a) { return new [] { (a[0].Item1, a[0].Item2) }; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 2"); comp.VerifyDiagnostics(); } [Fact] public void TupleRef() { string source = @" class C { static void Main() { var r = (1, 2); M(ref r); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } static void M(ref (int, int) a) { System.Console.WriteLine($""{a.Item1} {a.Item2}""); a = (3, 4); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"1 2 3 4"); comp.VerifyDiagnostics(); } [Fact] public void TupleOut() { string source = @" class C { static void Main() { (int, int) r; M(out r); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } static void M(out (int, int) a) { a = (1, 2); } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 2"); comp.VerifyDiagnostics(); } [Fact] public void TupleTypeArgs() { string source = @" class C { static void Main() { var a = (1, ""Alice""); var r = M<int, string>(a); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } static (T1, T2) M<T1, T2>((T1, T2) a) { return a; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 Alice"); comp.VerifyDiagnostics(); } [Fact] public void NullableTuple() { string source = @" class C { static void Main() { M((1, ""Alice"")); } static void M((int, string)? a) { System.Console.WriteLine($""{a.HasValue} {a.Value.Item1} {a.Value.Item2}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"True 1 Alice"); comp.VerifyDiagnostics(); } [Fact] public void TupleUnsupportedInUsingStatement() { var source = @" using VT2 = (int, int); "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,13): error CS1001: Identifier expected // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 13), // (2,13): error CS1002: ; expected // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_SemicolonExpected, "(").WithLocation(2, 13), // (2,14): error CS1525: Invalid expression term 'int' // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(2, 14), // (2,19): error CS1525: Invalid expression term 'int' // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(2, 19), // (2,1): hidden CS8019: Unnecessary using directive. // using VT2 = (int, int); Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using VT2 = ").WithLocation(2, 1) ); } [Fact] public void TupleWithVar() { var source = @" class C { static void Main() { (int, var) x = (1, 2); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,15): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // (int, var) x = (1, 2); Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 15) ); } [Fact] [WorkItem(12032, "https://github.com/dotnet/roslyn/issues/12032")] public void MissingTypeInAlias() { var source = @" using System; using VT2 = System.ValueTuple<int, int>; // ValueTuple is referenced but does not exist namespace System { public class Bogus { } } namespace TuplesCrash2 { class Program { static void Main(string[] args) { } } } "; var tree = Parse(source); var comp = CreateCompilation(new[] { tree }); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); model.LookupStaticMembers(201); // This position is inside Main method for (int pos = 0; pos < source.Length; pos++) { model.LookupStaticMembers(pos); } // didn't crash } [Fact] [WorkItem(11302, "https://github.com/dotnet/roslyn/issues/11302")] public void MultipleDefinitionsOfValueTuple() { var source1 = @" public static class C1 { public static void M1(this int x, (int, int) y) { System.Console.WriteLine(""C1.M1""); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public static class C2 { public static void M1(this int x, (int, int) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source = @" class C3 { public static void Main() { int x = 0; x.M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }); comp.VerifyDiagnostics( // (7,14): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // x.M1((1, 1)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) ); comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference() }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1.M1"); } [Fact] [WorkItem(12082, "https://github.com/dotnet/roslyn/issues/12082")] public void TupleWithDynamic() { var source = @" class C { static void Main() { (dynamic, dynamic) d1 = (1, 1); // implicit to dynamic System.Console.WriteLine(d1); (dynamic, dynamic) d2 = M(); System.Console.WriteLine(d2); (int, int) t3 = (3, 3); (dynamic, dynamic) d3 = t3; System.Console.WriteLine(d3); (int, int) t4 = (4, 4); (dynamic, dynamic) d4 = ((dynamic, dynamic))t4; // explicit to dynamic System.Console.WriteLine(d4); dynamic d5 = 5; (int, int) t5 = (d5, d5); // implicit from dynamic System.Console.WriteLine(t5); (dynamic, dynamic) d6 = (6, 6); (int, int) t6 = ((int, int))d6; // explicit from dynamic System.Console.WriteLine(t6); (dynamic, dynamic) d7; (int, int) t7 = (7, 7); d7 = t7; System.Console.WriteLine(d7); } static (dynamic, dynamic) M() { return (2, 2); } } "; string expectedOutput = @"(1, 1) (2, 2) (3, 3) (4, 4) (5, 5) (6, 6) (7, 7) "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] [WorkItem(12082, "https://github.com/dotnet/roslyn/issues/12082")] public void TupleWithDynamic2() { var source = @" class C { static void Main() { (dynamic, dynamic) d = (1, 1); (int, int) t = d; } } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (7,24): error CS0266: Cannot implicitly convert type '(dynamic, dynamic)' to '(int, int)'. An explicit conversion exists (are you missing a cast?) // (int, int) t = d; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "d").WithArguments("(dynamic, dynamic)", "(int, int)").WithLocation(7, 24) ); } [Fact] public void TupleWithDynamic3() { var source = @" class C { public static void Main() { dynamic longTuple = (a: 2, b: 2, c: 2, d: 2, e: 2, f: 2, g: 2, h: 2, i: 2); System.Console.Write($""Item1: {longTuple.Item1} Rest: {longTuple.Rest}""); try { System.Console.Write(longTuple.a); System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} try { System.Console.Write(longTuple.i); System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} try { System.Console.Write(longTuple.Item9); System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} } } "; var comp = CompileAndVerify(source, expectedOutput: "Item1: 2 Rest: (2, 2)", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleWithDynamic4() { var source = @" class C { public static void Main() { dynamic x = (1, 2, 3, 4, 5, 6, 7, 8, 9); M(x); } public static void M((int a, int, int, int, int, int, int, int h, int i) t) { System.Console.Write($""a:{t.a}, h:{t.h}, i:{t.i}, Item9:{t.Item9}, Rest:{t.Rest}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "a:1, h:8, i:9, Item9:9, Rest:(8, 9)", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleWithDynamic5() { var source = @" class C { public static void Main() { dynamic d = (1, 2); try { (string, string) t = d; System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} System.Console.Write(""done""); } } "; var comp = CompileAndVerify(source, expectedOutput: "done", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleWithDynamic6() { var source = @" class C { public static void Main() { (int, int) t1 = (1, 1); M(t1, ""int""); (byte, byte) t2 = (2, 2); M(t2, ""byte""); (dynamic, dynamic) t3 = (3, 3); M(t3, ""dynamic""); (string, string) t4 = (""4"", ""4""); M(t4, ""string""); } public static void M((int, int) t, string type) { System.Console.WriteLine($""int overload with value {t} and type {type}""); } public static void M((dynamic, dynamic) t, string type) { System.Console.WriteLine($""dynamic overload with value {t} and type {type}""); } } "; string expectedOutput = @"int overload with value (1, 1) and type int int overload with value (2, 2) and type byte dynamic overload with value (3, 3) and type dynamic dynamic overload with value (4, 4) and type string"; var comp = CompileAndVerify(source, expectedOutput: expectedOutput, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void Tuple2To8Members() { var source = @" class C { static void Main() { System.Console.Write((1, 2).Item1); System.Console.Write((1, 2).Item2); System.Console.Write((3, 4, 5).Item1); System.Console.Write((3, 4, 5).Item2); System.Console.Write((3, 4, 5).Item3); System.Console.Write((6, 7, 8, 9).Item1); System.Console.Write((6, 7, 8, 9).Item2); System.Console.Write((6, 7, 8, 9).Item3); System.Console.Write((6, 7, 8, 9).Item4); System.Console.Write((0, 1, 2, 3, 4).Item1); System.Console.Write((0, 1, 2, 3, 4).Item2); System.Console.Write((0, 1, 2, 3, 4).Item3); System.Console.Write((0, 1, 2, 3, 4).Item4); System.Console.Write((0, 1, 2, 3, 4).Item5); System.Console.Write((5, 6, 7, 8, 9, 0).Item1); System.Console.Write((5, 6, 7, 8, 9, 0).Item2); System.Console.Write((5, 6, 7, 8, 9, 0).Item3); System.Console.Write((5, 6, 7, 8, 9, 0).Item4); System.Console.Write((5, 6, 7, 8, 9, 0).Item5); System.Console.Write((5, 6, 7, 8, 9, 0).Item6); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item1); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item2); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item3); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item4); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item5); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item6); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item7); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item1); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item2); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item3); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item4); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item5); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item6); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item7); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item8); } } "; var comp = CompileAndVerify(source, expectedOutput: "12345678901234567890123456789012345"); } [Fact] public void CreateTupleTypeSymbol_BadArguments() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); Assert.Throws<ArgumentNullException>(() => comp.CreateTupleTypeSymbol(null, default(ImmutableArray<string>))); // if names are provided, you need one for each element var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt2, new[] { "Item1" }.AsImmutable())); Assert.Contains(CodeAnalysisResources.TupleElementNameCountMismatch, e.Message); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt2, elementLocations: new[] { loc1 }.AsImmutable())); Assert.Contains(CodeAnalysisResources.TupleElementLocationCountMismatch, e.Message); } [Fact, WorkItem(36676, "https://github.com/dotnet/roslyn/issues/36676")] public void CreateTupleTypeSymbol_WithValueTuple_TupleZero() { var tupleComp = CreateCompilationWithMscorlib40(@" namespace System { public struct ValueTuple { } }"); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); var vt0 = comp.GetWellKnownType(WellKnownType.System_ValueTuple); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt0, ImmutableArray<string>.Empty); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.Null(tupleWithoutNames.TupleUnderlyingType); Assert.Equal("System.ValueTuple", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Empty(ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, vt0); Assert.False(vt8.IsTupleType); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt8, default)); } [Fact, WorkItem(36676, "https://github.com/dotnet/roslyn/issues/36676")] public void CreateTupleTypeSymbol_WithValueTuple_TupleOne() { var tupleComp = CreateCompilationWithMscorlib40(@" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(intType); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt1, ImmutableArray.Create(new[] { (string)null })); Assert.Same(vt1, ((Symbols.PublicModel.NonErrorNamedTypeSymbol)tupleWithoutNames).UnderlyingNamedTypeSymbol); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32>", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32" }, ElementTypeNames(tupleWithoutNames)); } [Fact] public void CreateTupleTypeSymbol_WithValueTuple() { var tupleComp = CreateCompilationWithMscorlib40(trivial2uple); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create<string>(null, null)); Assert.Same(vt2, ((Symbols.PublicModel.NamedTypeSymbol)tupleWithoutNames).UnderlyingNamedTypeSymbol); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.Null(tupleWithoutNames.TupleUnderlyingType); Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.All(tupleWithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } private static ImmutableArray<string> GetTupleElementNames(INamedTypeSymbol tuple) { var elements = tuple.TupleElements; if (elements.All(e => e.IsImplicitlyDeclared)) { return default(ImmutableArray<string>); } return elements.SelectAsArray(e => e.ProvidedTupleElementNameOrNull()); } [Fact] public void CreateTupleTypeSymbol_Locations() { var tupleComp = CreateCompilation(trivial2uple); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); var intType = comp.GetSpecialType(SpecialType.System_Int32); var stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); var loc2 = Location.Create(tree, new TextSpan(1, 1)); var tuple = comp.CreateTupleTypeSymbol( vt2, ImmutableArray.Create<string>("i1", "i2"), ImmutableArray.Create(loc1, loc2)); Assert.True(tuple.IsTupleType); Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind); Assert.Equal("(System.Int32 i1, System.String i2)", tuple.ToTestDisplayString()); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tuple)); Assert.Equal(SymbolKind.NamedType, tuple.Kind); Assert.Equal(loc1, tuple.GetMembers("i1").Single().Locations.Single()); Assert.Equal(loc2, tuple.GetMembers("i2").Single().Locations.Single()); } [Fact] public void MemberNamesOnValueTupleFromPEWithoutFields() { string trivial2uple_withoutFields = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; public override string ToString() => throw null; } }"; var tupleComp = CreateCompilation(trivial2uple_withoutFields); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.EmitToImageReference() }); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); AssertEx.SetEqual(vt2.MemberNames.ToArray(), new[] { ".ctor", "ToString" }); } [Fact] public void CreateTupleTypeSymbol_NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, default(ImmutableArray<string>)); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.Kind); Assert.Null(tupleWithoutNames.TupleUnderlyingType); Assert.Equal("(System.Int32, System.String)[missing]", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.Kind); Assert.All(tupleWithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tupleWithNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Alice", "Bob")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Alice, System.String Bob)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice", "Bob" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); Assert.All(tupleWithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_WithSomeNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, stringType, intType); var tupleWithSomeNames = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create(null, "Item2", "Charlie")); Assert.True(tupleWithSomeNames.IsTupleType); Assert.Equal("(System.Int32, System.String Item2, System.Int32 Charlie)[missing]", tupleWithSomeNames.ToTestDisplayString()); Assert.Equal(new[] { null, "Item2", "Charlie" }, GetTupleElementNames(tupleWithSomeNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tupleWithSomeNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithSomeNames.Kind); Assert.All(tupleWithSomeNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_WithBadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); var tupleWithNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item2", "Item1")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Item2, System.Int32 Item1)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Item2", "Item1" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.Int32" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); Assert.All(tupleWithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple8NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)); var tuple8WithoutNames = comp.CreateTupleTypeSymbol(vt8, default(ImmutableArray<string>)); Assert.True(tuple8WithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithoutNames.ToTestDisplayString()); Assert.False(vt8.OriginalDefinition.IsTupleType); Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithoutNames)); Assert.All(tuple8WithoutNames.TupleElements.Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple8NoNames_WithValueTupleTypes() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)); var tuple8WithoutNames = comp.CreateTupleTypeSymbol(vt8, elementNames: default); Assert.Same(vt8, ((Symbols.PublicModel.NamedTypeSymbol)tuple8WithoutNames).UnderlyingNamespaceOrTypeSymbol); Assert.True(tuple8WithoutNames.IsTupleType); Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)", tuple8WithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithoutNames)); Assert.All(tuple8WithoutNames.GetMembers().OfType<IFieldSymbol>().Where(f => f.Name != "Rest").Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple8WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)); var tuple8WithNames = comp.CreateTupleTypeSymbol(vt8, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")); Assert.True(tuple8WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8" }, GetTupleElementNames(tuple8WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithNames)); Assert.All(tuple8WithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple9NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)); var tuple9WithoutNames = comp.CreateTupleTypeSymbol(vt9, default(ImmutableArray<string>)); Assert.True(tuple9WithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithoutNames)); Assert.All(tuple9WithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple9WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)); var tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")); Assert.True(tuple9WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9" }, GetTupleElementNames(tuple9WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithNames)); Assert.All(tuple9WithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple9WithDefaultNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var originalVT2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.True(originalVT2.IsDefinition); var vt2 = originalVT2.Construct(intType, intType); Assert.False(vt2.IsDefinition); comp.CreateTupleTypeSymbol(vt2, new[] { "Item1", "Item2" }.AsImmutable()); var vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, vt2); var tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); Assert.True(tuple9WithNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.Int32, System.Int32)[missing]>[missing]", tuple9WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9" }, GetTupleElementNames(tuple9WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.Int32", "System.Int32" }, ElementTypeNames(tuple9WithNames)); Assert.All(tuple9WithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_ElementTypeIsError() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); var vt2WithErrorType = vt2.Construct(intType, ErrorTypeSymbol.UnknownResultType); var tupleWithoutNames = ((Symbols.PublicModel.NamedTypeSymbol)comp.CreateTupleTypeSymbol(vt2WithErrorType, elementNames: default)).UnderlyingNamedTypeSymbol; Assert.Same(vt2WithErrorType, tupleWithoutNames); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); var types = tupleWithoutNames.TupleElements.SelectAsArray(e => e.Type); Assert.Equal(2, types.Length); Assert.Equal(SymbolKind.NamedType, types[0].Kind); Assert.Equal(SymbolKind.ErrorType, types[1].Kind); Assert.All(tupleWithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact, WorkItem(13277, "https://github.com/dotnet/roslyn/issues/13277")] [WorkItem(14365, "https://github.com/dotnet/roslyn/issues/14365")] public void CreateTupleTypeSymbol_UnderlyingTypeIsError() { var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, TestReferences.SymbolsTests.netModule.netModule1 }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.CreateErrorTypeSymbol(null, "ValueTuple", 2).Construct(intType, intType); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(underlyingType: vt2)); var vbComp = CreateVisualBasicCompilation(""); Assert.Throws<ArgumentNullException>(() => comp.CreateErrorTypeSymbol(null, null, 2)); Assert.Throws<ArgumentException>(() => comp.CreateErrorTypeSymbol(null, "a", -1)); Assert.Throws<ArgumentException>(() => comp.CreateErrorTypeSymbol(vbComp.GlobalNamespace, "a", 1)); Assert.Throws<ArgumentNullException>(() => comp.CreateErrorNamespaceSymbol(null, "a")); Assert.Throws<ArgumentNullException>(() => comp.CreateErrorNamespaceSymbol(vbComp.GlobalNamespace, null)); Assert.Throws<ArgumentException>(() => comp.CreateErrorNamespaceSymbol(vbComp.GlobalNamespace, "a")); var ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a"); Assert.Equal("a", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind); Assert.Same(comp.GlobalNamespace, ns.ContainingSymbol); Assert.Same(comp.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly); Assert.Same(comp.GlobalNamespace.ContainingModule, ns.ContainingModule); ns = comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "a"); Assert.Equal("a", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); Assert.Equal(NamespaceKind.Assembly, ns.NamespaceKind); Assert.Same(comp.Assembly.GlobalNamespace, ns.ContainingSymbol); Assert.Same(comp.Assembly.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly); Assert.Same(comp.Assembly.GlobalNamespace.ContainingModule, ns.ContainingModule); ns = comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "a"); Assert.Equal("a", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); Assert.Equal(NamespaceKind.Module, ns.NamespaceKind); Assert.Same(comp.SourceModule.GlobalNamespace, ns.ContainingSymbol); Assert.Same(comp.SourceModule.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly); Assert.Same(comp.SourceModule.GlobalNamespace.ContainingModule, ns.ContainingModule); ns = comp.CreateErrorNamespaceSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a"), "b"); Assert.Equal("a.b", ns.ToTestDisplayString()); ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, ""); Assert.Equal("", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType); Assert.Equal("(System.Int32, System.Int32)[missing]", comp.CreateTupleTypeSymbol(underlyingType: vt2).ToTestDisplayString()); vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType); Assert.Equal("(System.Int32, System.Int32)[missing]", comp.CreateTupleTypeSymbol(underlyingType: vt2).ToTestDisplayString()); vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType); Assert.Equal("(System.Int32, System.Int32)[missing]", comp.CreateTupleTypeSymbol(underlyingType: vt2).ToTestDisplayString()); } [Fact] public void CreateTupleTypeSymbol_BadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); NamedTypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); var vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, intType, intType); // illegal C# identifiers, space and null var tuple2 = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create("123", " ", null)); Assert.Equal(new[] { "123", " ", null }, GetTupleElementNames(tuple2)); // reserved identifiers var tuple3 = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("return", "class")); Assert.Equal(new[] { "return", "class" }, GetTupleElementNames(tuple3)); // not tuple-compatible underlying type var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(intType)); Assert.Contains(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, e.Message); } [Fact] public void CreateTupleTypeSymbol_EmptyNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); NamedTypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); // illegal C# identifiers and blank var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("123", ""))); Assert.Contains(CodeAnalysisResources.TupleElementNameEmpty, e.Message); Assert.Contains("elementNames[1]", e.Message); } [Fact] public void CreateTupleTypeSymbol_VisualBasicElements() { var vbSource = @"Public Class C End Class"; var vbComp = CreateVisualBasicCompilation("VB", vbSource, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbComp.VerifyDiagnostics(); INamedTypeSymbol vbType = (INamedTypeSymbol)vbComp.GlobalNamespace.GetMembers("C").Single(); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vbType, default(ImmutableArray<string>))); Assert.Contains(CSharpResources.NotACSharpSymbol, e.Message); } [Fact] public void CreateAnonymousTypeSymbol_VisualBasicElements() { var vbSource = @"Public Class C End Class"; var vbComp = CreateVisualBasicCompilation("VB", vbSource, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbComp.VerifyDiagnostics(); var vbType = (ITypeSymbol)vbComp.GlobalNamespace.GetMembers("C").Single(); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); var e = Assert.Throws<ArgumentException>(() => comp.CreateAnonymousTypeSymbol(ImmutableArray.Create(vbType), ImmutableArray.Create("m1"))); Assert.Contains(CSharpResources.NotACSharpSymbol, e.Message); } [Fact] public void CreateTupleTypeSymbol2_BadArguments() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); Assert.Throws<ArgumentNullException>(() => comp.CreateTupleTypeSymbol(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<string>))); // 0-tuple and 1-tuple are not supported at this point Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(ImmutableArray<ITypeSymbol>.Empty, default(ImmutableArray<string>))); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(new[] { intType }.AsImmutable(), default(ImmutableArray<string>))); // if names are provided, you need one for each element Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(new[] { intType, intType }.AsImmutable(), new[] { "Item1" }.AsImmutable())); var syntaxTree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(syntaxTree, new TextSpan(0, 1)); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(new[] { intType, intType }.AsImmutable(), elementLocations: ImmutableArray.Create(loc1))); // null types aren't allowed Assert.Throws<ArgumentNullException>(() => comp.CreateTupleTypeSymbol(new[] { intType, null }.AsImmutable(), default(ImmutableArray<string>))); } [Fact] public void CreateTupleTypeSymbol2_WithValueTuple() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create<string>(null, null)); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.True(tupleWithoutNames.GetMembers("Item1").Single().Locations.IsEmpty); } [Fact] public void CreateTupleTypeSymbol_WithLocations() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); var intType = comp.GetSpecialType(SpecialType.System_Int32); var stringType = comp.GetSpecialType(SpecialType.System_String); var syntaxTree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(syntaxTree, new TextSpan(0, 1)); var loc2 = Location.Create(syntaxTree, new TextSpan(1, 1)); var tuple = comp.CreateTupleTypeSymbol( ImmutableArray.Create<TypeSymbol>(intType, stringType), ImmutableArray.Create<string>(null, null), ImmutableArray.Create(loc1, loc2)); Assert.True(tuple.IsTupleType); Assert.Equal("(System.Int32, System.String)", tuple.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tuple)); Assert.Equal(SymbolKind.NamedType, tuple.Kind); Assert.Equal(loc1, tuple.GetMembers("Item1").Single().Locations.Single()); Assert.Equal(loc2, tuple.GetMembers("Item2").Single().Locations.Single()); } private static IEnumerable<string> ElementTypeNames(INamedTypeSymbol tuple) { return tuple.TupleElements.Select(t => t.Type.ToTestDisplayString()); } [Fact] public void CreateTupleTypeSymbol2_NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), default(ImmutableArray<string>)); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal("(System.Int32, System.String)[missing]", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.Kind); } [Fact] public void CreateTupleTypeSymbol2_WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tupleWithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("Alice", "Bob")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Alice, System.String Bob)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice", "Bob" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); } [Fact] public void CreateTupleTypeSymbol2_WithBadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var tupleWithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("Item2", "Item1")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Item2, System.Int32 Item1)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Item2", "Item1" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.Int32" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); } [Fact] public void CreateTupleTypeSymbol2_Tuple8NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple8WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), default(ImmutableArray<string>)); Assert.True(tuple8WithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithoutNames)); } [Fact] public void CreateTupleTypeSymbol2_Tuple8WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple8WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")); Assert.True(tuple8WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8" }, GetTupleElementNames(tuple8WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithNames)); } [Fact] public void CreateTupleTypeSymbol2_Tuple9NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple9WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), default(ImmutableArray<string>)); Assert.True(tuple9WithoutNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithoutNames.ToTestDisplayString()); Assert.False(tuple9WithoutNames.IsDefinition); Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithoutNames)); } [Fact] public void CreateTupleTypeSymbol2_Tuple9WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple9WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")); Assert.True(tuple9WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithNames.ToTestDisplayString()); Assert.False(tuple9WithNames.IsDefinition); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9" }, GetTupleElementNames(tuple9WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithNames)); } [Fact] public void CreateTupleTypeSymbol2_ElementTypeIsError() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, ErrorTypeSymbol.UnknownResultType), default(ImmutableArray<string>)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); var types = tupleWithoutNames.TupleElements.SelectAsArray(e => e.Type); Assert.Equal(2, types.Length); Assert.Equal(SymbolKind.NamedType, types[0].Kind); Assert.Equal(SymbolKind.ErrorType, types[1].Kind); } [Fact] public void CreateTupleTypeSymbol2_BadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); // illegal C# identifiers and blank var tuple2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("123", " ")); Assert.Equal(new[] { "123", " " }, GetTupleElementNames(tuple2)); // reserved identifiers var tuple3 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("return", "class")); Assert.Equal(new[] { "return", "class" }, GetTupleElementNames(tuple3)); } [Fact] public void CreateTupleTypeSymbol2_VisualBasicElements() { var vbSource = @"Public Class C End Class"; var vbComp = CreateVisualBasicCompilation("VB", vbSource, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbComp.VerifyDiagnostics(); ITypeSymbol vbType = (ITypeSymbol)vbComp.GlobalNamespace.GetMembers("C").Single(); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); INamedTypeSymbol intType = comp.GetSpecialType(SpecialType.System_String).GetPublicSymbol(); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, vbType), default(ImmutableArray<string>))); } [Fact] public void CreateTupleTypeSymbol_ComparingSymbols() { var source = @" class C { System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)> F; } "; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IFieldSymbol>("F").Type; var intType = comp.GetSpecialType(SpecialType.System_Int32); var stringType = comp.GetSpecialType(SpecialType.System_String); var twoStrings = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, stringType); var twoStringsWithNames = comp.CreateTupleTypeSymbol(twoStrings, ImmutableArray.Create("a", "b")); var tuple2Underlying = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).Construct(intType, intType, intType, intType, intType, intType, intType, twoStringsWithNames); var tuple2 = comp.CreateTupleTypeSymbol(tuple2Underlying); var tuple3 = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(intType, intType, intType, intType, intType, intType, intType, stringType, stringType), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")); var tuple4 = comp.CreateTupleTypeSymbol(tuple1, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")); Assert.True(tuple1.Equals(tuple2)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(tuple1.Equals(tuple3)); Assert.True(tuple1.Equals(tuple3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(tuple1.Equals(tuple4)); Assert.True(tuple1.Equals(tuple4, TypeCompareKind.IgnoreDynamicAndTupleNames)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_UnderlyingType_DefaultArgs_01() { var source = @"class Program { (int, string) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; Assert.Null(tuple1.TupleUnderlyingType); var underlyingType = tuple1; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] [WorkItem(40105, "https://github.com/dotnet/roslyn/issues/40105")] public void CreateTupleTypeSymbol_UnderlyingType_DefaultArgs_02() { var source = @"class Program { (string, #nullable enable string, string?) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; Assert.Null(tuple1.TupleUnderlyingType); var underlyingType = tuple1; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_ElementTypes_DefaultArgs_01() { var source = @"class Program { (int, string) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] [WorkItem(40105, "https://github.com/dotnet/roslyn/issues/40105")] public void CreateTupleTypeSymbol_ElementTypes_DefaultArgs_02() { var source = @"class Program { (string, #nullable enable string, string?) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_01() { var source = @"class Program { (int, string) F; }"; var comp = CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((FieldSymbol)comp.GetMember("Program.F")).GetPublicSymbol().Type; Assert.Null(tuple1.TupleUnderlyingType); var underlyingType = tuple1; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.True(tuple1.Equals(tuple2)); Assert.False(tuple1.Equals(tuple2, SymbolEqualityComparer.IncludeNullability)); Assert.Equal("(System.Int32, System.String?)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_02() { var source = @"class Program { (object _1, object _2, object _3, object _4, object _5, object _6, object _7, object _8, object _9) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var underlyingType = tuple1.TupleUnderlyingType; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)); Assert.False(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Assert.Equal("(System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?)", tuple2.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_01() { var source = @"class Program { (int, string) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.True(tuple1.Equals(tuple2)); Assert.False(tuple1.Equals(tuple2, SymbolEqualityComparer.IncludeNullability)); Assert.Equal("(System.Int32, System.String?)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_02() { var source = @"class Program { (object _1, object _2, object _3, object _4, object _5, object _6, object _7, object _8, object _9) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)); Assert.False(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Assert.Equal("(System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?)", tuple2.ToTestDisplayString(includeNonNullable: true)); } private static ImmutableArray<CodeAnalysis.NullableAnnotation> CreateAnnotations(CodeAnalysis.NullableAnnotation annotation, int n) => ImmutableArray.CreateRange(Enumerable.Range(0, n).Select(_ => annotation)); private static bool TypeEquals(ITypeSymbol a, ITypeSymbol b, TypeCompareKind compareKind) => a.Equals(b, compareKind); [Fact] public void TupleMethodsOnNonTupleType() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); NamedTypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); Assert.False(stringType.IsTupleType); Assert.True(stringType.TupleElements.IsDefault); Assert.Null(stringType.TupleUnderlyingType); } [Fact] public void TupleTargetTypeAndConvert01() { var source = @" class C { static void Main() { // this works (short, string) x1 = (1, ""hello""); // this does not (short, string) x2 = ((long, string))(1, ""hello""); // this does not (short a, string b) x3 = ((long c, string d))(1, ""hello""); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,30): error CS0266: Cannot implicitly convert type '(long, string)' to '(short, string)'. An explicit conversion exists (are you missing a cast?) // (short, string) x2 = ((long, string))(1, "hello"); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, @"((long, string))(1, ""hello"")").WithArguments("(long, string)", "(short, string)").WithLocation(10, 30), // (13,34): error CS0266: Cannot implicitly convert type '(long c, string d)' to '(short a, string b)'. An explicit conversion exists (are you missing a cast?) // (short a, string b) x3 = ((long c, string d))(1, "hello"); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, @"((long c, string d))(1, ""hello"")").WithArguments("(long c, string d)", "(short a, string b)").WithLocation(13, 34), // (7,25): warning CS0219: The variable 'x1' is assigned but its value is never used // (short, string) x1 = (1, "hello"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(7, 25), // (10,25): warning CS0219: The variable 'x2' is assigned but its value is never used // (short, string) x2 = ((long, string))(1, "hello"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(10, 25), // (13,29): warning CS0219: The variable 'x3' is assigned but its value is never used // (short a, string b) x3 = ((long c, string d))(1, "hello"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(13, 29) ); } [Fact] public void TupleTargetTypeAndConvert02() { var source = @" class C { static void Main() { (short, string) x2 = ((byte, string))(1, ""hello""); System.Console.WriteLine(x2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {1, hello}"); comp.VerifyIL("C.Main()", @" { // Code size 41 (0x29) .maxstack 3 .locals init (System.ValueTuple<byte, string> V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldstr ""hello"" IL_0008: call ""System.ValueTuple<byte, string>..ctor(byte, string)"" IL_000d: ldloc.0 IL_000e: ldfld ""byte System.ValueTuple<byte, string>.Item1"" IL_0013: ldloc.0 IL_0014: ldfld ""string System.ValueTuple<byte, string>.Item2"" IL_0019: newobj ""System.ValueTuple<short, string>..ctor(short, string)"" IL_001e: box ""System.ValueTuple<short, string>"" IL_0023: call ""void System.Console.WriteLine(object)"" IL_0028: ret } "); ; } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail01() { var source = @" class C { static void Main() { (int, int) x; x = (null, null, null); x = (1, 1, 1); x = (1, ""string""); x = (1, 1, garbage); x = (1, 1, ); x = (null, null); x = (1, null); x = (1, (t)=>t); x = null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (12,20): error CS1525: Invalid expression term ')' // x = (1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 20), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = (null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 13), // (9,13): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(int, int)' // x = (1, 1, 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 13), // (10,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // x = (1, "string"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 17), // (11,20): error CS0103: The name 'garbage' does not exist in the current context // x = (1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 20), // (13,14): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 14), // (13,20): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 20), // (14,17): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (1, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 17), // (15,17): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 17), // (16,13): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(int, int)").WithLocation(16, 13) ); } [Fact] public void TupleExplicitConversionFail01() { var source = @" class C { static void Main() { (int, int) x; x = ((int, int))(null, null, null); x = ((int, int))(1, 1, 1); x = ((int, int))(1, ""string""); x = ((int, int))(1, 1, garbage); x = ((int, int))(1, 1, ); x = ((int, int))(null, null); x = ((int, int))(1, null); x = ((int, int))(1, (t)=>t); x = ((int, int))null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (12,32): error CS1525: Invalid expression term ')' // x = ((int, int))(1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 32), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = ((int, int))(null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "((int, int))(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 13), // (9,13): error CS0030: Cannot convert type '(int, int, int)' to '(int, int)' // x = ((int, int))(1, 1, 1); Diagnostic(ErrorCode.ERR_NoExplicitConv, "((int, int))(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 13), // (10,29): error CS0030: Cannot convert type 'string' to 'int' // x = ((int, int))(1, "string"); Diagnostic(ErrorCode.ERR_NoExplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 29), // (11,32): error CS0103: The name 'garbage' does not exist in the current context // x = ((int, int))(1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 32), // (13,26): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((int, int))(null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 26), // (13,32): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((int, int))(null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 32), // (14,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((int, int))(1, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 29), // (15,29): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = ((int, int))(1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 29), // (16,13): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = ((int, int))null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "((int, int))null").WithArguments("(int, int)").WithLocation(16, 13) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail02() { var source = @" class C { static void Main() { System.ValueTuple<int, int> x; x = (null, null, null); x = (1, 1, 1); x = (1, ""string""); x = (1, 1, garbage); x = (1, 1, ); x = (null, null); x = (1, null); x = (1, (t)=>t); x = null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (12,20): error CS1525: Invalid expression term ')' // x = (1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 20), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = (null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 13), // (9,13): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(int, int)' // x = (1, 1, 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 13), // (10,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // x = (1, "string"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 17), // (11,20): error CS0103: The name 'garbage' does not exist in the current context // x = (1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 20), // (13,14): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 14), // (13,20): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 20), // (14,17): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (1, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 17), // (15,17): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 17), // (16,13): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(int, int)").WithLocation(16, 13) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail03() { var source = @" class C { static void Main() { (string, string) x; x = (null, null, null); x = (1, 1, 1); x = (1, ""string""); x = (1, 1, garbage); x = (1, 1, ); x = (null, null); x = (1, null); x = (1, (t)=>t); x = null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (12,20): error CS1525: Invalid expression term ')' // x = (1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 20), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(string, string)'. // x = (null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(string, string)").WithLocation(8, 13), // (9,13): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(string, string)' // x = (1, 1, 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(string, string)").WithLocation(9, 13), // (10,14): error CS0029: Cannot implicitly convert type 'int' to 'string' // x = (1, "string"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(10, 14), // (11,20): error CS0103: The name 'garbage' does not exist in the current context // x = (1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 20), // (14,14): error CS0029: Cannot implicitly convert type 'int' to 'string' // x = (1, null); Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(14, 14), // (15,14): error CS0029: Cannot implicitly convert type 'int' to 'string' // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(15, 14), // (15,17): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "string").WithLocation(15, 17), // (16,13): error CS0037: Cannot convert null to '(string, string)' because it is a non-nullable value type // x = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(string, string)").WithLocation(16, 13) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail04() { var source = @" class C { static void Main() { ((int, int), int) x; x = ((null, null, null), 1); x = ((1, 1, 1), 1); x = ((1, ""string""), 1); x = ((1, 1, garbage), 1); x = ((1, 1, ), 1); x = ((null, null), 1); x = ((1, null), 1); x = ((1, (t)=>t), 1); x = (null, 1); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (12,21): error CS1525: Invalid expression term ')' // x = ((1, 1, ), 1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 21), // (8,14): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = ((null, null, null), 1); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 14), // (9,14): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(int, int)' // x = ((1, 1, 1), 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 14), // (10,18): error CS0029: Cannot implicitly convert type 'string' to 'int' // x = ((1, "string"), 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 18), // (11,21): error CS0103: The name 'garbage' does not exist in the current context // x = ((1, 1, garbage), 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 21), // (13,15): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((null, null), 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 15), // (13,21): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((null, null), 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 21), // (14,18): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((1, null), 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 18), // (15,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = ((1, (t)=>t), 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 18), // (16,14): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = (null, 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(int, int)").WithLocation(16, 14) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail05() { var source = @" class C { static void Main() { (System.ValueTuple<int, int> x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10) x; x = (0,1,2,3,4,5,6,7,8,9,10); x = ((0, 0.0),1,2,3,4,5,6,7,8,9,10); x = ((0, 0),1,2,3,4,5,6,7,8,9,10,11); x = ((0, 0),1,2,3,4,5,6,7,8); x = ((0, 0),1,2,3,4,5,6,7,8,9.1,10); x = ((0, 0),1,2,3,4,5,6,7,8,; x = ((0, 0),1,2,3,4,5,6,7,8,9 x = ((0, 0),1,2,3,4,oops,6,7,oopsss,9,10); x = ((0, 0),1,2,3,4,5,6,7,8,9); x = ((0, 0),1,2,3,4,5,6,7,8,(1,1,1), 10); } } " + trivial2uple + trivialRemainingTuples + tupleattributes_cs; //intentionally not including 3-tuple for usesite errors CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (13,37): error CS1525: Invalid expression term ';' // x = ((0, 0),1,2,3,4,5,6,7,8,; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 37), // (13,37): error CS1026: ) expected // x = ((0, 0),1,2,3,4,5,6,7,8,; Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(13, 37), // (14,38): error CS1026: ) expected // x = ((0, 0),1,2,3,4,5,6,7,8,9 Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(14, 38), // (14,38): error CS1002: ; expected // x = ((0, 0),1,2,3,4,5,6,7,8,9 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(14, 38), // (8,14): error CS0029: Cannot implicitly convert type 'int' to '(int, int)' // x = (0,1,2,3,4,5,6,7,8,9,10); Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "(int, int)").WithLocation(8, 14), // (9,18): error CS0029: Cannot implicitly convert type 'double' to 'int' // x = ((0, 0.0),1,2,3,4,5,6,7,8,9,10); Diagnostic(ErrorCode.ERR_NoImplicitConv, "0.0").WithArguments("double", "int").WithLocation(9, 18), // (10,13): error CS0029: Cannot implicitly convert type '((int, int), int, int, int, int, int, int, int, int, int, int, int)' to '((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)' // x = ((0, 0),1,2,3,4,5,6,7,8,9,10,11); Diagnostic(ErrorCode.ERR_NoImplicitConv, "((0, 0),1,2,3,4,5,6,7,8,9,10,11)").WithArguments("((int, int), int, int, int, int, int, int, int, int, int, int, int)", "((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)").WithLocation(10, 13), // (11,13): error CS0029: Cannot implicitly convert type '((int, int), int, int, int, int, int, int, int, int)' to '((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)' // x = ((0, 0),1,2,3,4,5,6,7,8); Diagnostic(ErrorCode.ERR_NoImplicitConv, "((0, 0),1,2,3,4,5,6,7,8)").WithArguments("((int, int), int, int, int, int, int, int, int, int)", "((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)").WithLocation(11, 13), // (12,37): error CS0029: Cannot implicitly convert type 'double' to 'int' // x = ((0, 0),1,2,3,4,5,6,7,8,9.1,10); Diagnostic(ErrorCode.ERR_NoImplicitConv, "9.1").WithArguments("double", "int").WithLocation(12, 37), // (13,13): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,; Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "((0, 0),1,2,3,4,5,6,7,8,").WithArguments("System.ValueTuple`3").WithLocation(13, 13), // (14,13): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,9 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, @"((0, 0),1,2,3,4,5,6,7,8,9 ").WithArguments("System.ValueTuple`3").WithLocation(14, 13), // (15,29): error CS0103: The name 'oops' does not exist in the current context // x = ((0, 0),1,2,3,4,oops,6,7,oopsss,9,10); Diagnostic(ErrorCode.ERR_NameNotInContext, "oops").WithArguments("oops").WithLocation(15, 29), // (15,38): error CS0103: The name 'oopsss' does not exist in the current context // x = ((0, 0),1,2,3,4,oops,6,7,oopsss,9,10); Diagnostic(ErrorCode.ERR_NameNotInContext, "oopsss").WithArguments("oopsss").WithLocation(15, 38), // (17,13): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "((0, 0),1,2,3,4,5,6,7,8,9)").WithArguments("System.ValueTuple`3").WithLocation(17, 13), // (17,13): error CS0029: Cannot implicitly convert type 'System.ValueTuple<(int, int), int, int, int, int, int, int, (int, int, int)>' to '((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)' // x = ((0, 0),1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_NoImplicitConv, "((0, 0),1,2,3,4,5,6,7,8,9)").WithArguments("System.ValueTuple<(int, int), int, int, int, int, int, int, (int, int, int)>", "((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)").WithLocation(17, 13), // (18,37): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,(1,1,1), 10); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1,1,1)").WithArguments("System.ValueTuple`3").WithLocation(18, 37)); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail06() { var source = @" using System; class C { static void Main() { Func<string> l = ()=>1; // reference (string, Func<string>) x = (null, ()=>1); // actual error, should be the same as above. Func<(string, string)> l1 = ()=>(null, 1.1); // reference (string, Func<(string, string)>) x1 = (null, ()=>(null, 1.1)); // actual error, should be the same as above. } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (8,30): error CS0029: Cannot implicitly convert type 'int' to 'string' // Func<string> l = ()=>1; // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(8, 30), // (8,30): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<string> l = ()=>1; // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(8, 30), // (10,47): error CS0029: Cannot implicitly convert type 'int' to 'string' // (string, Func<string>) x = (null, ()=>1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(10, 47), // (10,47): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<string>) x = (null, ()=>1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(10, 47), // (12,48): error CS0029: Cannot implicitly convert type 'double' to 'string' // Func<(string, string)> l1 = ()=>(null, 1.1); // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(12, 48), // (12,41): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<(string, string)> l1 = ()=>(null, 1.1); // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(12, 41), // (14,65): error CS0029: Cannot implicitly convert type 'double' to 'string' // (string, Func<(string, string)>) x1 = (null, ()=>(null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(14, 65), // (14,58): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<(string, string)>) x1 = (null, ()=>(null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(14, 58) ); } [Fact] public void TupleExplicitConversionFail06() { var source = @" using System; class C { static void Main() { Func<string> l = (Func<string>)(()=>1); // reference (string, Func<string>) x = ((string, Func<string>))(null, () => 1); // actual error, should be the same as above. Func<(string, string)> l1 = (Func<(string, string)>)(()=>(null, 1.1)); // reference (string, Func<(string, string)>) x1 = ((string, Func<(string, string)>))(null, () => (null, 1.1)); // actual error, should be the same as above. } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (8,45): error CS0029: Cannot implicitly convert type 'int' to 'string' // Func<string> l = (Func<string>)(()=>1); // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(8, 45), // (8,45): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<string> l = (Func<string>)(()=>1); // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(8, 45), // (10,73): error CS0029: Cannot implicitly convert type 'int' to 'string' // (string, Func<string>) x = ((string, Func<string>))(null, () => 1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(10, 73), // (10,73): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<string>) x = ((string, Func<string>))(null, () => 1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(10, 73), // (12,73): error CS0029: Cannot implicitly convert type 'double' to 'string' // Func<(string, string)> l1 = (Func<(string, string)>)(()=>(null, 1.1)); // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(12, 73), // (12,66): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<(string, string)> l1 = (Func<(string, string)>)(()=>(null, 1.1)); // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(12, 66), // (14,101): error CS0029: Cannot implicitly convert type 'double' to 'string' // (string, Func<(string, string)>) x1 = ((string, Func<(string, string)>))(null, () => (null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(14, 101), // (14,94): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<(string, string)>) x1 = ((string, Func<(string, string)>))(null, () => (null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(14, 94) ); } [Fact] public void TupleExplicitNullableConversionWithTypelessTuple() { var source = @" class C { static void Main() { var x = ((int, string)?) (1, null); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(1, )"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declaration = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().First(); var value = declaration.Declaration.Variables.First().Initializer.Value; Assert.Equal("((int, string)?) (1, null)", value.ToString()); var castConversion = model.GetConversion(value); Assert.Equal(ConversionKind.Identity, castConversion.Kind); var tuple = ((CastExpressionSyntax)value).Expression; Assert.Equal("(1, null)", tuple.ToString()); var tupleConversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.ExplicitNullable, tupleConversion.Kind); Assert.Equal(1, tupleConversion.UnderlyingConversions.Length); Assert.Equal(ConversionKind.ExplicitTupleLiteral, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void TupleImplicitNullableConversionWithTypelessTuple() { var source = @" class C { static void Main() { (int, string)? x = (1, null); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(1, )"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declaration = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().First(); var value = declaration.Declaration.Variables.First().Initializer.Value; Assert.Equal("(1, null)", value.ToString()); var tupleConversion = model.GetConversion(value); Assert.Equal(ConversionKind.ImplicitNullable, tupleConversion.Kind); Assert.Equal(1, tupleConversion.UnderlyingConversions.Length); Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void TupleImplicitNullableAndCustomConversionsWithTypelessTuple() { var source = @" struct C { static void Main() { C? x = (1, null); System.Console.Write(x); var x2 = (C)(2, null); System.Console.Write(x2); var x3 = (C?)(3, null); System.Console.Write(x3); } public static implicit operator C((int, string) x) { return new C(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "CCC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuples = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); var tuple1 = tuples.ElementAt(0); Assert.Equal("(1, null)", tuple1.ToString()); Assert.Null(model.GetTypeInfo(tuple1).Type); Assert.Equal("C?", model.GetTypeInfo(tuple1).ConvertedType.ToTestDisplayString()); var conversion1 = model.GetConversion(tuple1); Assert.Equal(ConversionKind.ImplicitUserDefined, conversion1.Kind); Assert.True(conversion1.UnderlyingConversions.IsDefault); var tuple2 = tuples.ElementAt(1); Assert.Equal("(2, null)", tuple2.ToString()); Assert.Null(model.GetTypeInfo(tuple2).Type); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple2).ConvertedType.ToTestDisplayString()); var conversion2 = model.GetConversion(tuple2); Assert.Equal(ConversionKind.ImplicitTupleLiteral, conversion2.Kind); Assert.False(conversion2.UnderlyingConversions.IsDefault); var tuple3 = tuples.ElementAt(2); Assert.Equal("(3, null)", tuple3.ToString()); Assert.Null(model.GetTypeInfo(tuple3).Type); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple3).ConvertedType.ToTestDisplayString()); var conversion3 = model.GetConversion(tuple3); Assert.Equal(ConversionKind.ImplicitTupleLiteral, conversion3.Kind); Assert.False(conversion3.UnderlyingConversions.IsDefault); } [Fact] public void TupleImplicitNullableAndCustomConversionsWithTypelessTupleInAsOperator() { var source = @" struct C { static void Main() { var x4 = (1, null) as C; System.Console.Write(x4); var x5 = (2, null) as C?; System.Console.Write(x5); } public static implicit operator C((int, string) x) { return new C(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (6,18): error CS8305: The first operand of an 'as' operator may not be a tuple literal without a natural type. // var x4 = (1, null) as C; Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(1, null) as C").WithLocation(6, 18), // (8,18): error CS8305: The first operand of an 'as' operator may not be a tuple literal without a natural type. // var x5 = (2, null) as C?; Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(2, null) as C?").WithLocation(8, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuples = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); verifyTuple("(1, null)", tuples.ElementAt(0)); verifyTuple("(2, null)", tuples.ElementAt(1)); void verifyTuple(string expected, TupleExpressionSyntax tuple) { Assert.Equal(expected, tuple.ToString()); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Null(model.GetTypeInfo(tuple).ConvertedType); var conversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.Identity, conversion.Kind); Assert.True(conversion.UnderlyingConversions.IsDefault); } } [Fact] public void TupleTargetTypeLambda() { var source = @" using System; class C { static void Test(Func<Func<(short, short)>> d) { Console.WriteLine(""short""); } static void Test(Func<Func<(byte, byte)>> d) { Console.WriteLine(""byte""); } static void Main() { // this works because of identity conversion Test( ()=>()=>((byte, byte))(1,1)) ; // this works because of the betterness of the targets Test(()=>()=>(1,1)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" byte byte "); } [Fact] public void TupleTargetTypeLambda1() { var source = @" using System; class C { static void Test(Func<(Func<short>, int)> d) { Console.WriteLine(""short""); } static void Test(Func<(Func<byte>, int)> d) { Console.WriteLine(""byte""); } static void Main() { // this works Test(()=>(()=>(short)1, 1)); // this works Test(()=>(()=>(byte)1, 1)); // this does not Test(()=>(()=>1, 1)); } } "; CreateCompilation(source).VerifyDiagnostics( // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Test(Func<(Func<short>, int)>)' and 'C.Test(Func<(Func<byte>, int)>)' // Test(()=>(()=>1, 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("C.Test(System.Func<(System.Func<short>, int)>)", "C.Test(System.Func<(System.Func<byte>, int)>)").WithLocation(26, 9) ); } [Fact] public void TargetTypingOverload01() { var source = @" using System; class C { static void Main() { Test((null, null)); Test((1, 1)); Test((()=>7, ()=>8), 2); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x, T y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" second first third 7 "); } [Fact] public void TargetTypingOverload02() { var source = @" using System; class C { static void Main() { Test((()=>7, ()=>8)); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" third 7 "); } [Fact] public void TargetTypingNullable01() { var source = @" using System; class C { static void Main() { var x = M1(); Test(x); } static (int a, double b)? M1() { return (1, 2); } static void Test<T>(T arg) { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(arg); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Nullable`1[System.ValueTuple`2[System.Int32,System.Double]] (1, 2) "); } [Fact] public void TargetTypingOverload01Long() { var source = @" using System; class C { static void Main() { Test((null, null, null, null, null, null, null, null, null, null)); Test((1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); Test((()=>7, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8), 2); } static void Test<T>((T, T, T, T, T, T, T, T, T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object, object, object, object, object, object, object, object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>) x, T y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, expectedOutput: @" second first third 7 "); } [Fact] public void TargetTypingNullable02() { var source = @" using System; class C { static void Main() { var x = M1(); Test(x); } static (int a, string b)? M1() { return (1, null); } static void Test<T>(T arg) { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(arg); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]] (1, ) "); } [Fact] public void TargetTypingNullable02Long() { var source = @" class C { static void Main() { var x = M1(); System.Console.WriteLine(x?.a); System.Console.WriteLine(x?.a8); Test(x); } static (int a, string b, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8)? M1() { return (1, null, 1, 2, 3, 4, 5, 6, 7, 8); } static void Test<T>(T arg) { System.Console.WriteLine(arg); } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 8 (1, , 1, 2, 3, 4, 5, 6, 7, 8) "); } [Fact] public void TargetTypingNullableOverload() { var source = @" class C { static void Main() { Test((null, null, null, null, null, null, null, null, null, null)); Test((""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"")); Test((1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); } static void Test((string, string, string, string, string, string, string, string, string, string) x) { System.Console.WriteLine(""first""); } static void Test((string, string, string, string, string, string, string, string, string, string)? x) { System.Console.WriteLine(""second""); } static void Test((int, int, int, int, int, int, int, int, int, int)? x) { System.Console.WriteLine(""third""); } static void Test((int, int, int, int, int, int, int, int, int, int) x) { System.Console.WriteLine(""fourth""); } } "; var comp = CompileAndVerify(source, expectedOutput: @" first first fourth "); } [Fact] public void TupleConversion01() { var source = @" class C { static void Main() { // error must mention (long c, long d) (int a, int b) x1 = ((long c, long d))(e: 1, f:2); // error must mention (int c, long d) (short a, short b) x2 = ((int c, int d))(e: 1, f:2); // error must mention (int e, string f) (int a, int b) x3 = ((long c, long d))(e: 1, f:""qq""); } } " + trivial2uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (7,48): warning CS8123: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(long c, long d)'. // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 1").WithArguments("e", "(long c, long d)").WithLocation(7, 48), // (7,54): warning CS8123: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(long c, long d)'. // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f:2").WithArguments("f", "(long c, long d)").WithLocation(7, 54), // (7,29): error CS0266: Cannot implicitly convert type '(long c, long d)' to '(int a, int b)'. An explicit conversion exists (are you missing a cast?) // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "((long c, long d))(e: 1, f:2)").WithArguments("(long c, long d)", "(int a, int b)").WithLocation(7, 29), // (9,50): warning CS8123: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(int c, int d)'. // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 1").WithArguments("e", "(int c, int d)").WithLocation(9, 50), // (9,56): warning CS8123: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(int c, int d)'. // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f:2").WithArguments("f", "(int c, int d)").WithLocation(9, 56), // (9,33): error CS0266: Cannot implicitly convert type '(int c, int d)' to '(short a, short b)'. An explicit conversion exists (are you missing a cast?) // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "((int c, int d))(e: 1, f:2)").WithArguments("(int c, int d)", "(short a, short b)").WithLocation(9, 33), // (12,56): error CS0030: Cannot convert type 'string' to 'long' // (int a, int b) x3 = ((long c, long d))(e: 1, f:"qq"); Diagnostic(ErrorCode.ERR_NoExplicitConv, @"""qq""").WithArguments("string", "long").WithLocation(12, 56), // (7,24): warning CS0219: The variable 'x1' is assigned but its value is never used // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(7, 24), // (9,28): warning CS0219: The variable 'x2' is assigned but its value is never used // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(9, 28) ); } [Fact] [WorkItem(11288, "https://github.com/dotnet/roslyn/issues/11288")] public void TupleConversion02() { var source = @" class C { static void Main() { (int a, int b) x4 = ((long c, long d))(1, null, 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (6,29): error CS8135: Tuple with 3 elements cannot be converted to type '(long c, long d)'. // (int a, int b) x4 = ((long c, long d))(1, null, 2); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "((long c, long d))(1, null, 2)").WithArguments("3", "(long c, long d)").WithLocation(6, 29) ); } [Fact] public void TupleConvertedType01() { var source = @" class C { static void Main() { (short a, string b)? x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType01insource() { var source = @" class C { static void Main() { // explicit conversion exists, cast in the code picks that. (short a, string b)? x = ((short c, string d)?)(e: 1, f: ""hello""); short? y = (short?)11; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var l11 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(2); Assert.Equal(@"11", l11.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(l11)); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d)?)(e: 1, f: ""hello"") Assert.Equal("(System.Int16 c, System.String d)?", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType01insourceImplicit() { var source = @" class C { static void Main() { (short a, string b)? x =(1, ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""hello"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); CompileAndVerify(comp); } [Fact] public void TupleConvertedType02() { var source = @" class C { static void Main() { (short a, string b)? x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType02insource00() { var source = @" class C { static void Main() { (short a, string b)? x = ((short c, string d))(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: ""hello"") Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node.Parent).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType02insource01() { var source = @" class C { static void Main() { var x = (e: 1, f: ""hello""); (object a, string b) x1 = ((long c, string d))(x); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<ParenthesizedExpressionSyntax>().Single().Parent; Assert.Equal(@"((long c, string d))(x)", node.ToString()); Assert.Equal("(System.Int64 c, System.String d)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Object a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(node).Kind); node = nodes.OfType<ParenthesizedExpressionSyntax>().Single(); Assert.Equal(@"(x)", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); } [Fact] public void TupleConvertedType02insource02() { var source = @" class C { static void Main() { var x = (e: 1, f: ""hello""); (object a, string b)? x1 = ((long c, string d))(x); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<ParenthesizedExpressionSyntax>().Single().Parent; Assert.Equal(@"((long c, string d))(x)", node.ToString()); Assert.Equal("(System.Int64 c, System.String d)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Object a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); node = nodes.OfType<ParenthesizedExpressionSyntax>().Single(); Assert.Equal(@"(x)", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); } [Fact] public void TupleConvertedType03() { var source = @" class C { static void Main() { (int a, string b)? x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType03insource() { var source = @" class C { static void Main() { (int a, string b)? x = ((int c, string d)?)(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 c, System.String d)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((int c, string d)?)(e: 1, f: ""hello"") Assert.Equal("(System.Int32 c, System.String d)?", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType04() { var source = @" class C { static void Main() { (int a, string b)? x = ((int c, string d))(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); // semantic model returns topmost conversion from the sequence of conversions for // ((int c, string d))(e: 1, f: ""hello"") Assert.Equal("(System.Int32 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node.Parent).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType05() { var source = @" class C { static void Main() { (int a, string b) x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType05insource() { var source = @" class C { static void Main() { (int a, string b) x = ((int c, string d))(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType06() { var source = @" class C { static void Main() { (short a, string b) x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType06insource() { var source = @" class C { static void Main() { (short a, string b) x = ((short c, string d))(e: 1, f: ""hello""); short y = (short)11; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var l11 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(2); Assert.Equal(@"11", l11.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(l11)); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: ""hello"") Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedTypeNull01() { var source = @" class C { static void Main() { (short a, string b) x = (e: 1, f: null); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: null)", node.ToString()); Assert.Null(model.GetTypeInfo(node).Type); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedTypeNull01insource() { var source = @" class C { static void Main() { (short a, string b) x = ((short c, string d))(e: 1, f: null); string y = (string)null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var lnull = nodes.OfType<LiteralExpressionSyntax>().ElementAt(2); Assert.Equal(@"null", lnull.ToString()); Assert.Null(model.GetTypeInfo(lnull).Type); Assert.Null(model.GetTypeInfo(lnull).ConvertedType); Assert.Equal(Conversion.Identity, model.GetConversion(lnull)); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: null)", node.ToString()); Assert.Null(model.GetTypeInfo(node).Type); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: null) Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedTypeUDC01() { var source = @" class C { static void Main() { (short a, string b) x = (e: 1, f: new C1(""qq"")); System.Console.WriteLine(x.ToString()); } class C1 { private string s; public C1(string arg) { s = arg + 1; } public static implicit operator string (C1 arg) { return arg.s; } } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: new C1(""qq""))", node.ToString()); Assert.Equal("(System.Int32 e, C.C1 f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "{1, qq1}"); } [Fact] public void TupleConvertedTypeUDC01insource() { var source = @" class C { static void Main() { (short a, string b) x = ((short c, string d))(e: 1, f: new C1(""qq"")); System.Console.WriteLine(x.ToString()); } class C1 { private string s; public C1(string arg) { s = arg + 1; } public static implicit operator string (C1 arg) { return arg.s; } } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: new C1(""qq""))", node.ToString()); Assert.Equal("(System.Int32 e, C.C1 f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("C.C1", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitUserDefined, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: null) Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "{1, qq1}"); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC02() { var source = @" class C { static void Main() { C1 x = (1, ""qq""); System.Console.WriteLine(x.ToString()); } class C1 { private (byte, string) val; private C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { return new C1(arg); } public override string ToString() { return val.ToString(); } } } " + trivial2uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: "{1, qq}"); } [Fact] public void TupleConvertedTypeUDC03() { var source = @" class C { static void Main() { C1 x = (""1"", ""qq""); System.Console.WriteLine(x.ToString()); } class C1 { private (byte, string) val; private C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { return new C1(arg); } public override string ToString() { return val.ToString(); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS0029: Cannot implicitly convert type '(string, string)' to 'C.C1' // C1 x = ("1", "qq"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(""1"", ""qq"")").WithArguments("(string, string)", "C.C1").WithLocation(6, 16) ); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(""1"", ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.String, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, model.GetConversion(node)); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC04() { var source = @" public class C { static void Main() { C1 x = (1, ""qq""); System.Console.WriteLine(x.ToString()); } public class C1 { private (byte, string) val; public C1((byte, string) arg) { val = arg; } public override string ToString() { return val.ToString(); } } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator C.C1 ((T1, T2) arg) { return new C.C1(((byte)(int)(object)arg.Item1, (string)(object)arg.Item2)); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(1, ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: "{1, qq}"); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC05() { var source = @" public class C { static void Main() { C1 x = (1, ""qq""); System.Console.WriteLine(x.ToString()); } public class C1 { private (byte, string) val; public C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { System.Console.WriteLine(""C1""); return new C1(arg); } public override string ToString() { return val.ToString(); } } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator C.C1 ((T1, T2) arg) { System.Console.WriteLine(""VT""); return new C.C1(((byte)(int)(object)arg.Item1, (string)(object)arg.Item2)); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(1, ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: @"VT {1, qq}"); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC06() { var source = @" public class C { static void Main() { C1 x = (1, null); System.Console.WriteLine(x.ToString()); } public class C1 { private (byte, string) val; public C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { System.Console.WriteLine(""C1""); return new C1(arg); } public override string ToString() { return val.ToString(); } } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator C.C1 ((T1, T2) arg) { System.Console.WriteLine(""VT""); return new C.C1(((byte)(int)(object)arg.Item1, (string)(object)arg.Item2)); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(1, null)", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Null(typeInfo.Type); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: @"C1 {1, }"); } [Fact] public void TupleConvertedTypeUDC07() { var source = @" class C { static void Main() { C1 x = M1(); System.Console.WriteLine(x.ToString()); } static (int, string) M1() { return (1, ""qq""); } class C1 { private (byte, string) val; private C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { return new C1(arg); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS0029: Cannot implicitly convert type '(int, string)' to 'C.C1' // C1 x = M1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "M1()").WithArguments("(int, string)", "C.C1").WithLocation(6, 16) ); } [Fact] public void Inference01() { var source = @" using System; class C { static void Main() { Test((null, null)); Test((1, 1)); Test((()=>7, ()=>8), 2); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x, T y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" second first third 7 "); } [Fact] public void Inference02() { var source = @" using System; class C { static void Main() { Test((()=>7, ()=>8)); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" third 7 "); } [Fact] public void Inference02_WithoutTuple() { var source = @" using System; class C { static void Main() { Test(()=>7, ()=>8); } static void Test<T>(T x, T y) { System.Console.WriteLine(""first""); } static void Test(object x, object y) { System.Console.WriteLine(""second""); } static void Test<T>(Func<T> x, Func<T> y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" third 7 "); } [Fact] public void Inference03() { var source = @" using System; class C { static void Main() { Test(((x)=>x, (x)=>x)); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<int, T>, Func<T, T>) x) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1(5).ToString()); } } "; var comp = CompileAndVerify(source, expectedOutput: @" third 5 "); } [Fact] public void Inference04() { var source = @" using System; class C { static void Main() { Test( (x)=>x.y ); Test( (x)=>x.bob ); } static void Test<T>( Func<(byte x, byte y), T> x) { System.Console.WriteLine(""first""); System.Console.WriteLine(x((2,3)).ToString()); } static void Test<T>( Func<(int alice, int bob), T> x) { System.Console.WriteLine(""second""); System.Console.WriteLine(x((4,5)).ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first 3 second 5 "); } [Fact] public void Inference05() { var source = @" using System; class C { static void Main() { Test( ((x)=>x.x, (x)=>x.Item2) ); Test( ((x)=>x.bob, (x)=>x.Item1) ); } static void Test<T>( (Func<(byte x, byte y), T> f1, Func<(int, int), T> f2) x) { System.Console.WriteLine(""first""); System.Console.WriteLine(x.f1((2,3)).ToString()); System.Console.WriteLine(x.f2((2,3)).ToString()); } static void Test<T>( (Func<(int alice, int bob), T> f1, Func<(int, int), T> f2) x) { System.Console.WriteLine(""second""); System.Console.WriteLine(x.f1((4,5)).ToString()); System.Console.WriteLine(x.f2((4,5)).ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first 2 3 second 5 4 "); } [WorkItem(10801, "https://github.com/dotnet/roslyn/issues/10801")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/10801")] public void Inference06() { var source = @" using System; class Program { static void Main(string[] args) { M1((() => ""qq"", null)); } static void M1((Func<object> f, object o) a) { System.Console.WriteLine(1); } static void M1((Func<string> f, object o) a) { System.Console.WriteLine(2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" 2 "); } [Fact] public void Inference07() { var source = @" using System; class C { static void Main() { Test((x) => (x, x), (t) => 1); Test1((x) => (x, x), (t) => 1); Test2((a: 1, b: 2), (t) => (t.a, t.b)); } static void Test<U>(Func<int, ValueTuple<U, U>> f1, Func<ValueTuple<U, U>, int> f2) { System.Console.WriteLine(f2(f1(1))); } static void Test1<U>(Func<int, (U, U)> f1, Func<(U, U), int> f2) { System.Console.WriteLine(f2(f1(1))); } static void Test2<U, T>(U f1, Func<U, (T x, T y)> f2) { System.Console.WriteLine(f2(f1).y); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" 1 1 2 "); } [Fact] public void Inference08() { var source = @" using System; class C { static void Main() { Test1((a: 1, b: 2), (c: 3, d: 4)); Test2((a: 1, b: 2), (c: 3, d: 4), t => t.Item2); Test2((a: 1, b: 2), (a: 3, b: 4), t => t.a); Test2((a: 1, b: 2), (c: 3, d: 4), t => t.a); } static void Test1<T>(T x, T y) { System.Console.WriteLine(""test1""); System.Console.WriteLine(x); } static void Test2<T>(T x, T y, Func<T, int> f) { System.Console.WriteLine(""test2_1""); System.Console.WriteLine(f(x)); } static void Test2<T>(T x, object y, Func<T, int> f) { System.Console.WriteLine(""test2_2""); System.Console.WriteLine(f(x)); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" test1 {1, 2} test2_1 2 test2_1 1 test2_2 1 "); } [Fact] public void Inference08t() { var source = @" using System; class C { static void Main() { var ab = (a: 1, b: 2); var cd = (c: 3, d: 4); Test1(ab, cd); Test2(ab, cd, t => t.Item2); Test2(ab, ab, t => t.a); Test2(ab, cd, t => t.a); } static void Test1<T>(T x, T y) { System.Console.WriteLine(""test1""); System.Console.WriteLine(x); } static void Test2<T>(T x, T y, Func<T, int> f) { System.Console.WriteLine(""test2_1""); System.Console.WriteLine(f(x)); } static void Test2<T>(T x, object y, Func<T, int> f) { System.Console.WriteLine(""test2_2""); System.Console.WriteLine(f(x)); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" test1 {1, 2} test2_1 2 test2_1 1 test2_2 1 "); } [Fact] public void Inference09() { var source = @" using System; class C { static void Main() { // byval tuple, as a whole, sets a lower bound Test1((a: 1, b: 2), (ValueType)1); } static void Test1<T>(T x, T y) { System.Console.WriteLine(typeof(T)); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" System.ValueType "); } [Fact] public void Inference10() { var source = @" using System; class C { static void Main() { // byref tuple, as a whole, sets an exact bound var t = (a: 1, b: 2); Test1(ref t, (ValueType)1); } static void Test1<T>(ref T x, T y) { System.Console.WriteLine(typeof(T)); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.Test1<T>(ref T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1(ref t, (ValueType)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T>(ref T, T)").WithLocation(10, 9) ); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11() { var source = @" class C { static void Main() { object o = null; dynamic d = null; var ab = (a: 1, b: o); var ad = (a: 1, d: d); var t1 = Test1(ref ab, ad); // exact bound and lower bound var t2 = Test2(ab, ref ad); // lower bound and exact bound var t3 = Test3(ref ab, ref ad); // two exact bounds var d1 = Test1(ref o, d); var d2 = Test2(o, ref d); var d3 = Test3(ref o, ref d); } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (17,18): error CS0411: The type arguments for method 'C.Test3<T>(ref T, ref T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var d3 = Test3(ref o, ref d); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test3").WithArguments("C.Test3<T>(ref T, ref T)").WithLocation(17, 18) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("(System.Int32 a, dynamic) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("(System.Int32 a, dynamic) t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("(System.Int32 a, dynamic) t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); var d1 = names.ElementAt(7); Assert.Equal("dynamic d1", model.GetDeclaredSymbol(d1).ToTestDisplayString()); var d2 = names.ElementAt(8); Assert.Equal("dynamic d2", model.GetDeclaredSymbol(d2).ToTestDisplayString()); var d3 = names.ElementAt(9); Assert.Equal("T d3", model.GetDeclaredSymbol(d3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11InNestedType() { var source = @" class C { static void Main() { object o = null; dynamic d = null; var ab = new [] { ((a: 1, b: o), c: 2) }; var ad = new [] { ((a: 1, d: d), c: 2) }; var t1 = Test1(ref ab, ad); // exact bound and lower bound var t2 = Test2(ab, ref ad); // lower bound and exact bound var t3 = Test3(ref ab, ref ad); // two exact bounds } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("((System.Int32 a, dynamic), System.Int32 c)[] t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("((System.Int32 a, dynamic), System.Int32 c)[] t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("((System.Int32 a, dynamic), System.Int32 c)[] t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithLongTuple() { var source = @" class C { static void Main() { object o = null; dynamic d = null; var ay = (a: o, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, y: 9); var az = (a: d, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, 8, z: 10); var t1 = Test1(ref ay, az); // exact bound and lower bound var t2 = Test2(ay, ref az); // lower bound and exact bound var t3 = Test3(ref ay, ref az); // two exact bounds } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("(dynamic a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32, System.Int32) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("(dynamic a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32, System.Int32) t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("(dynamic a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32, System.Int32) t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11OnlyDynamicMismatch() { var source = @" using System.Linq; class C { static void Main() { object o = null; dynamic d = null; var doc = (new [] { ((a: d, b: o), c: 2) }).ToList(); var odc = (new [] { ((a: o, b: d), c: 2) }).ToList(); var t1 = Test1(ref doc, odc); // exact bound and lower bound var t2 = Test2(doc, ref odc); // lower bound and exact bound var t3 = Test3(ref doc, ref odc); // two exact bounds } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("System.Collections.Generic.List<((dynamic a, dynamic b), System.Int32 c)> t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("System.Collections.Generic.List<((dynamic a, dynamic b), System.Int32 c)> t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("System.Collections.Generic.List<((dynamic a, dynamic b), System.Int32 c)> t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithMoreThanTwoTypes() { var source = @" class C { static void Main() { var ab = (a: 1, b: 2); var cd = (c: 1, d: 2); var de = (d: 1, e: 2); var t1 = Test1(ref ab, cd, 1, de); } static T Test1<T>(ref T x, T y, T z, T w) => x; } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'C.Test1<T>(ref T, T, T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var t1 = Test1(ref ab, cd, 1, de); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T>(ref T, T, T, T)").WithLocation(10, 18) ); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithMoreThanTwoTypes2() { var source = @" class C { static void Main() { var abc = (a: 1, b: 2, c: 3); var abd = (a: 1, b: 2, d: 3); var byz = (b: 1, y: 2, c: 3); var t1 = Test1(ref abc, abd, byz); } static T Test1<T>(ref T x, T y, T z) => x; } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var t1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); Assert.Equal("(System.Int32, System.Int32, System.Int32) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); } [Fact] public void Inference11WithUpperBound() { var source = @" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Action<IEnumerable<(int a, dynamic b)>> x1 = null; Action<IEnumerable<(int a, object notB)>> x2 = null; var t1 = Test1(ref x1, x1, x2); // one exact bound and two upper bounds on T var t2 = Test2(x1, x2); // two upper bounds } public static T Test1<T>(ref Action<T> x, Action<T> y, Action<T> z) { return default(T); } public static T Test2<T>(Action<T> x, Action<T> y) { return default(T); } } "; var comp = CreateCompilationWithMscorlib40(source, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var t1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 a, dynamic)> t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 a, dynamic)> t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithImplicitConversion() { var source = @" class C { static void Main() { var ab = (a: 1, b: 2); var adL = (a: 1L, d: 2L); // `adL` is an exact bound, which `ab` can convert to, so the names on `ab` are ignored var t1 = Test1(ref adL, ab); var t2 = Test2(ab, ref adL); } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(2); Assert.Equal("(System.Int64 a, System.Int64 d) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(3); Assert.Equal("(System.Int64 a, System.Int64 d) t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); } [Fact] public void Inference12() { var source = @" class C { static void Main() { // nested tuple literals set lower bounds Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (object)1)); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); } static void Test1<T, U>((T, U) x, (T, U) y) { System.Console.WriteLine(typeof(U)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] "); } [Fact] public void Inference13() { var source = @" class C { static void Main() { // nested tuple literals set lower bounds Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (object)1)); Test1(Nullable((a: 1, b: (a: 1, b: 2))), (a: 1, b: (object)1)); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); } static T? Nullable<T>(T x) where T : struct { return x; } static void Test1<T, U>((T, U)? x, (T, U) y) { System.Console.WriteLine(typeof(U)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Object System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] "); } [Fact] public void Inference13_Err() { var source = @" class C { static void Main() { Test1(Nullable((a: 1, b: (a: 1, b: 2))), (a: 1, b: (object)1)); Test1((a: 1, b: (a: 1, b: 2)), Nullable((a: 1, b: (object)1))); } static T? Nullable<T>(T x) where T : struct { return x; } static void Test1<T, U>((T, U) x, (T, U) y) { System.Console.WriteLine(typeof(U)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,15): error CS1503: Argument 1: cannot convert from '(int a, (int a, int b) b)?' to '(int, object)' // Test1(Nullable((a: 1, b: (a: 1, b: 2))), (a: 1, b: (object)1)); Diagnostic(ErrorCode.ERR_BadArgType, "Nullable((a: 1, b: (a: 1, b: 2)))").WithArguments("1", "(int a, (int a, int b) b)?", "(int, object)").WithLocation(6, 15), // (7,40): error CS1503: Argument 2: cannot convert from '(int a, object b)?' to '(int, (int a, int b))' // Test1((a: 1, b: (a: 1, b: 2)), Nullable((a: 1, b: (object)1))); Diagnostic(ErrorCode.ERR_BadArgType, "Nullable((a: 1, b: (object)1))").WithArguments("2", "(int a, object b)?", "(int, (int a, int b))").WithLocation(7, 40) ); } [Fact] public void Inference14() { var source = @" class C { static void Main() { // nested tuple literals set lower bounds Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); } static void Test1<T, U>((T, U)? x, (T, U?) y) where U: struct { System.Console.WriteLine(typeof(U)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0411: The type arguments for method 'C.Test1<T, U>((T, U)?, (T, U?))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T, U>((T, U)?, (T, U?))").WithLocation(7, 9), // (8,9): error CS0411: The type arguments for method 'C.Test1<T, U>((T, U)?, (T, U?))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T, U>((T, U)?, (T, U?))").WithLocation(8, 9), // (9,9): error CS0411: The type arguments for method 'C.Test1<T, U>((T, U)?, (T, U?))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T, U>((T, U)?, (T, U?))").WithLocation(9, 9) ); } [Fact] public void Inference15() { var source = @" class C { static void Main() { Test1((a: ""q"", b: null), (a: null, b: ""w""), (x) => x.z); } static void Test1<T, U>((T, U) x, (T, U) y, System.Func<(T x, U z), T> f) { System.Console.WriteLine(typeof(U)); System.Console.WriteLine(f(y)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.String w "); } [Fact] public void Inference16() { var source = @" class C { static void Main() { // tuples set lower bounds var x = (1,2,3); Test(x); var x1 = (1,2,(long)3); Test(x1); var x2 = (1,(object)2,(long)3); Test(x2); } static void Test<T>((T, T, T) x) { System.Console.WriteLine(typeof(T)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Int32 System.Int64 System.Object "); } [Fact] public void Constraints_01() { var source = @" namespace System { public struct ValueTuple<T1, T2> where T2 : class { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C { static void Main((int, int) p) { var t0 = (1, 2); (int, int) t1 = t0; } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (14,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // static void Main((int, int) p) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "p").WithArguments("(T1, T2)", "T2", "int").WithLocation(14, 33), // (16,22): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // var t0 = (1, 2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "2").WithArguments("(T1, T2)", "T2", "int").WithLocation(16, 22), // (17,15): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // (int, int) t1 = t0; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("(T1, T2)", "T2", "int").WithLocation(17, 15) ); } [Fact] [WorkItem(15399, "https://github.com/dotnet/roslyn/issues/15399")] public void Constraints_02() { var source = @" using System; class Program { unsafe void M((int, int*) p, ValueTuple<int, int*> q) { (int, int*) t0 = p; var t1 = (1, (int*)null); var t2 = new ValueTuple<int, int*>(1, null); ValueTuple<int, int*> t3 = t2; } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: s_valueTupleRefs, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (5,31): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M((int, int*) p, ValueTuple<int, int*> q) Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(5, 31), // (5,56): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M((int, int*) p, ValueTuple<int, int*> q) Diagnostic(ErrorCode.ERR_BadTypeArgument, "q").WithArguments("int*").WithLocation(5, 56), // (7,15): error CS0306: The type 'int*' may not be used as a type argument // (int, int*) t0 = p; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(7, 15), // (8,22): error CS0306: The type 'int*' may not be used as a type argument // var t1 = (1, (int*)null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "(int*)null").WithArguments("int*").WithLocation(8, 22), // (9,38): error CS0306: The type 'int*' may not be used as a type argument // var t2 = new ValueTuple<int, int*>(1, null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(9, 38), // (10,25): error CS0306: The type 'int*' may not be used as a type argument // ValueTuple<int, int*> t3 = t2; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(10, 25), // (8,13): warning CS0219: The variable 't1' is assigned but its value is never used // var t1 = (1, (int*)null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t1").WithArguments("t1").WithLocation(8, 13) ); } [Fact] public void Constraints_03() { var source = @" using System.Collections.Generic; namespace System { public struct ValueTuple<T1, T2> where T2 : class { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C<T> { List<(T, T)> field = null; (U, U) M<U>(U x) { var t0 = new C<int>(); var t1 = M(1); return default((U, U)); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (15,12): error CS0452: The type 'U' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // (U, U) M<U>(U x) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "M").WithArguments("(T1, T2)", "T2", "U").WithLocation(15, 12), // (14,18): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // List<(T, T)> field = null; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "field").WithArguments("(T1, T2)", "T2", "T").WithLocation(14, 18), // (19,28): error CS0452: The type 'U' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // return default((U, U)); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "U").WithArguments("(T1, T2)", "T2", "U").WithLocation(19, 28), // (14,18): warning CS0414: The field 'C<T>.field' is assigned but its value is never used // List<(T, T)> field = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C<T>.field").WithLocation(14, 18) ); } [Fact] public void Constraints_04() { var source = @" using System.Collections.Generic; namespace System { public struct ValueTuple<T1, T2> where T2 : class { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C<T> where T : class { List<(T, T)> field = null; (U, U) M<U>(U x) where U : class { var t0 = new C<int>(); var t1 = M(1); return default((U, U)); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (17,24): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C<T>' // var t0 = new C<int>(); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("C<T>", "T", "int").WithLocation(17, 24), // (18,18): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C<T>.M<U>(U)' // var t1 = M(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "M").WithArguments("C<T>.M<U>(U)", "U", "int").WithLocation(18, 18), // (14,18): warning CS0414: The field 'C<T>.field' is assigned but its value is never used // List<(T, T)> field = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C<T>.field").WithLocation(14, 18) ); } [Fact] public void Constraints_05() { var source = @" using System.Collections.Generic; namespace System { public struct ValueTuple<T1, T2> where T2 : struct { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C<T> where T : class { List<(T, T)> field = null; (U, U) M<U>(U x) where U : class { var t0 = new C<int>(); var t1 = M((1, 2)); return default((U, U)); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (15,12): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // (U, U) M<U>(U x) where U : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M").WithArguments("(T1, T2)", "T2", "U").WithLocation(15, 12), // (14,18): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // List<(T, T)> field = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "field").WithArguments("(T1, T2)", "T2", "T").WithLocation(14, 18), // (17,24): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C<T>' // var t0 = new C<int>(); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("C<T>", "T", "int").WithLocation(17, 24), // (18,18): error CS0452: The type '(int, int)' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C<T>.M<U>(U)' // var t1 = M((1, 2)); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "M").WithArguments("C<T>.M<U>(U)", "U", "(int, int)").WithLocation(18, 18), // (19,28): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // return default((U, U)); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "U").WithArguments("(T1, T2)", "T2", "U").WithLocation(19, 28), // (14,18): warning CS0414: The field 'C<T>.field' is assigned but its value is never used // List<(T, T)> field = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C<T>.field").WithLocation(14, 18) ); } [Fact] public void Constraints_06() { var source = @" namespace System { public struct ValueTuple<T1> where T1 : class { public T1 Item1; public ValueTuple(T1 item1) { this.Item1 = item1; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where TRest : class { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } } } class C { void M((int, int, int, int, int, int, int, int) p) { var t0 = (1, 2, 3, 4, 5, 6, 7, 8); (int, int, int, int, int, int, int, int) t1 = t0; } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (42,53): error CS0452: The type 'ValueTuple<int>' must be a reference type in order to use it as parameter 'TRest' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' // void M((int, int, int, int, int, int, int, int) p) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "p").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "TRest", "System.ValueTuple<int>").WithLocation(42, 53), // (42,53): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method 'ValueTuple<T1>' // void M((int, int, int, int, int, int, int, int) p) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "p").WithArguments("System.ValueTuple<T1>", "T1", "int").WithLocation(42, 53), // (44,18): error CS0452: The type 'ValueTuple<int>' must be a reference type in order to use it as parameter 'TRest' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' // var t0 = (1, 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "(1, 2, 3, 4, 5, 6, 7, 8)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "TRest", "System.ValueTuple<int>").WithLocation(44, 18), // (44,40): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method 'ValueTuple<T1>' // var t0 = (1, 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "8").WithArguments("System.ValueTuple<T1>", "T1", "int").WithLocation(44, 40), // (45,9): error CS0452: The type 'ValueTuple<int>' must be a reference type in order to use it as parameter 'TRest' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' // (int, int, int, int, int, int, int, int) t1 = t0; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "(int, int, int, int, int, int, int, int)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "TRest", "System.ValueTuple<int>").WithLocation(45, 9), // (45,45): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method 'ValueTuple<T1>' // (int, int, int, int, int, int, int, int) t1 = t0; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("System.ValueTuple<T1>", "T1", "int").WithLocation(45, 45) ); } [Fact] public void LongTupleConstraints() { var source = @" using System; class Program { unsafe void M0((int, int, int, int, int, int, int, int*) p) { (int, int, int, int, int, int, int, int*) t1 = p; var t2 = (1, 2, 3, 4, 5, 6, 7, (int*)null); var t3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> (); var t4 = new ValueTuple<int, int, int, int, int, int, int, (int, int*)> (); ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> t5 = t3; ValueTuple<int, int, int, int, int, int, int, (int, int*)> t6 = t4; } unsafe void M1((int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) q) { (int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) v1 = q; var v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (int*)null); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: s_valueTupleRefs, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (15,102): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M1((int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) q) Diagnostic(ErrorCode.ERR_BadTypeArgument, "q").WithArguments("int*").WithLocation(15, 102), // (5,62): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M0((int, int, int, int, int, int, int, int*) p) Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(5, 62), // (7,45): error CS0306: The type 'int*' may not be used as a type argument // (int, int, int, int, int, int, int, int*) t1 = p; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(7, 45), // (8,40): error CS0306: The type 'int*' may not be used as a type argument // var t2 = (1, 2, 3, 4, 5, 6, 7, (int*)null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "(int*)null").WithArguments("int*").WithLocation(8, 40), // (9,84): error CS0306: The type 'int*' may not be used as a type argument // var t3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> (); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(9, 84), // (10,74): error CS0306: The type 'int*' may not be used as a type argument // var t4 = new ValueTuple<int, int, int, int, int, int, int, (int, int*)> (); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(10, 74), // (11,71): error CS0306: The type 'int*' may not be used as a type argument // ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> t5 = t3; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(11, 71), // (12,61): error CS0306: The type 'int*' may not be used as a type argument // ValueTuple<int, int, int, int, int, int, int, (int, int*)> t6 = t4; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(12, 61), // (8,13): warning CS0219: The variable 't2' is assigned but its value is never used // var t2 = (1, 2, 3, 4, 5, 6, 7, (int*)null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2").WithLocation(8, 13), // (17,85): error CS0306: The type 'int*' may not be used as a type argument // (int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) v1 = q; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(17, 85), // (18,70): error CS0306: The type 'int*' may not be used as a type argument // var v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (int*)null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "(int*)null").WithArguments("int*").WithLocation(18, 70), // (18,13): warning CS0219: The variable 'v2' is assigned but its value is never used // var v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (int*)null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "v2").WithArguments("v2").WithLocation(18, 13) ); } [Fact] public void RestrictedTypes1() { var source = @" class C { static void Main() { var x = (1, 2, new System.ArgIterator()); (int x, object y) y = (1, 2, new System.ArgIterator()); (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,24): error CS0306: The type 'ArgIterator' may not be used as a type argument // var x = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "new System.ArgIterator()").WithArguments("System.ArgIterator").WithLocation(6, 24), // (7,38): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, object y) y = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "new System.ArgIterator()").WithArguments("System.ArgIterator").WithLocation(7, 38), // (7,31): error CS0029: Cannot implicitly convert type '(int, int, System.ArgIterator)' to '(int x, object y)' // (int x, object y) y = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2, new System.ArgIterator())").WithArguments("(int, int, System.ArgIterator)", "(int x, object y)").WithLocation(7, 31), // (8,36): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "y").WithArguments("System.ArgIterator").WithLocation(8, 36), // (8,50): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "new System.ArgIterator()").WithArguments("System.ArgIterator").WithLocation(8, 50), // (8,43): error CS0029: Cannot implicitly convert type '(int, int, System.ArgIterator)' to '(int x, System.ArgIterator y)' // (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2, new System.ArgIterator())").WithArguments("(int, int, System.ArgIterator)", "(int x, System.ArgIterator y)").WithLocation(8, 43), // (6,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13) ); } [Fact] public void RestrictedTypes2() { var source = @" class C { static void Main() { (int x, System.ArgIterator y) y; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,36): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, System.ArgIterator y) y; Diagnostic(ErrorCode.ERR_BadTypeArgument, "y").WithArguments("System.ArgIterator").WithLocation(6, 36), // (6,39): warning CS0168: The variable 'y' is declared but never used // (int x, System.ArgIterator y) y; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 39) ); } [Fact, WorkItem(10569, "https://github.com/dotnet/roslyn/issues/10569")] public void IncompleteInterfaceMethod() { var source = @" public interface MyInterface { (int, int) Goo() } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,21): error CS1002: ; expected // (int, int) Goo() Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(3, 21) ); } [Fact] public void ImplementInterface() { var source = @" interface I { (int Alice, string Bob) M((int x, string y) value); (int Alice, string Bob) P1 { get; } } class C : I { static void Main() { var c = new C(); var x = c.M(c.P1); System.Console.WriteLine(x); } public (int Alice, string Bob) M((int x, string y) value) { return value; } public (int Alice, string Bob) P1 => (r: 1, s: ""hello""); } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, hello) "); } [Fact] public void ImplementInterfaceExplicitly() { var source = @" interface I { (int Alice, string Bob) M((int x, string y) value); (int Alice, string Bob) P1 { get; } } class C : I { static void Main() { I c = new C(); var x = c.M(c.P1); System.Console.WriteLine(x); System.Console.WriteLine(x.Alice); } (int Alice, string Bob) I.M((int x, string y) value) { return value; } public (int Alice, string Bob) P1 => (r: 1, s: ""hello""); } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, hello) 1"); } [Fact] public void TupleTypeArguments() { var source = @" interface I<TA, TB> where TB : TA { (TA, TB) M(TA a, TB b); } class C : I<(int, string), (int Alice, string Bob)> { static void Main() { var c = new C(); var x = c.M((1, ""Australia""), (2, ""Brazil"")); System.Console.WriteLine(x); } public ((int, string), (int Alice, string Bob)) M((int, string) x, (int Alice, string Bob) y) { return (x, y); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"((1, Australia), (2, Brazil))"); } [Fact] public void LongTupleTypeArguments() { var source = @" interface I<TA, TB> where TB : TA { (TA, TB) M(TA a, TB b); } class C : I<(int, string, int, string, int, string, int, string), (int A, string B, int C, string D, int E, string F, int G, string H)> { static void Main() { var c = new C(); var x = c.M((1, ""Australia"", 2, ""Brazil"", 3, ""Columbia"", 4, ""Ecuador""), (5, ""France"", 6, ""Germany"", 7, ""Honduras"", 8, ""India"")); System.Console.WriteLine(x); } public ((int, string, int, string, int, string, int, string), (int A, string B, int C, string D, int E, string F, int G, string H)) M((int, string, int, string, int, string, int, string) a, (int A, string B, int C, string D, int E, string F, int G, string H) b) { return (a, b); } } "; var comp = CompileAndVerify(source, expectedOutput: @"((1, Australia, 2, Brazil, 3, Columbia, 4, Ecuador), (5, France, 6, Germany, 7, Honduras, 8, India))"); } [Fact] public void OverrideGenericInterfaceWithDifferentNames() { string source = @" interface I<TA, TB> where TB : TA { (TA returnA, TB returnB) M((TA paramA, TB paramB) x); } class C : I<(int b, int a), (int a, int b)> { public virtual ((int, int) x, (int, int) y) M(((int, int), (int, int)) x) { throw new System.Exception(); } } class D : C, I<(int a, int b), (int c, int d)> { public override ((int b, int a), (int b, int a)) M(((int a, int b), (int b, int a)) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,49): error CS8141: The tuple element names in the signature of method 'C.M(((int, int), (int, int)))' must match the tuple element names of interface method 'I<(int b, int a), (int a, int b)>.M(((int b, int a) paramA, (int a, int b) paramB))' (including on the return type). // public virtual ((int, int) x, (int, int) y) M(((int, int), (int, int)) x) Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("C.M(((int, int), (int, int)))", "I<(int b, int a), (int a, int b)>.M(((int b, int a) paramA, (int a, int b) paramB))").WithLocation(9, 49), // (17,54): error CS8139: 'D.M(((int a, int b), (int b, int a)))': cannot change tuple element names when overriding inherited member 'C.M(((int, int), (int, int)))' // public override ((int b, int a), (int b, int a)) M(((int a, int b), (int b, int a)) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M(((int a, int b), (int b, int a)))", "C.M(((int, int), (int, int)))").WithLocation(17, 54), // (17,54): error CS8141: The tuple element names in the signature of method 'D.M(((int a, int b), (int b, int a)))' must match the tuple element names of interface method 'I<(int a, int b), (int c, int d)>.M(((int a, int b) paramA, (int c, int d) paramB))' (including on the return type). // public override ((int b, int a), (int b, int a)) M(((int a, int b), (int b, int a)) y) Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("D.M(((int a, int b), (int b, int a)))", "I<(int a, int b), (int c, int d)>.M(((int a, int b) paramA, (int c, int d) paramB))").WithLocation(17, 54) ); } [Fact] public void TupleWithoutFeatureFlag() { var source = @" class C { static void Main() { (int, int) x = (1, 1); } CS0151ERR_IntegralTypeValueExpected} " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int, int)").WithArguments("tuples", "7.0").WithLocation(6, 9), // (6,24): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 1)").WithArguments("tuples", "7.0").WithLocation(6, 24), // (8,36): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration // CS0151ERR_IntegralTypeValueExpected} Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}").WithLocation(8, 36) ); Assert.Equal("7.0", Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()[0])); Assert.Null(Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()[2])); Assert.Throws<ArgumentNullException>(() => Compilation.GetRequiredLanguageVersion(null)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28045")] public void DefaultAndFriendlyElementNames_01() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Console.WriteLine(v1.Item1); System.Console.WriteLine(v1.Item2); var v2 = M2(); System.Console.WriteLine(v2.Item1); System.Console.WriteLine(v2.Item2); System.Console.WriteLine(v2.a2); System.Console.WriteLine(v2.b2); var v6 = M6(); System.Console.WriteLine(v6.Item1); System.Console.WriteLine(v6.Item2); System.Console.WriteLine(v6.item1); System.Console.WriteLine(v6.item2); System.Console.WriteLine(v1.ToString()); System.Console.WriteLine(v2.ToString()); System.Console.WriteLine(v6.ToString()); } static (int, int) M1() { return (1, 11); } static (int a2, int b2) M2() { return (2, 22); } static (int item1, int item2) M6() { return (6, 66); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"1 11 2 22 2 22 6 66 6 66 (1, 11) (2, 22) (6, 66) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m6Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M6").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); Assert.Equal(new string[] { ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString" }, m1Tuple.TupleData.UnderlyingDefinitionToMemberMap.Values.Select(s => s.Name).OrderBy(n => n).ToArray()); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a2, System.Int32 b2).Item1", "System.Int32 (System.Int32 a2, System.Int32 b2).a2", "System.Int32 (System.Int32 a2, System.Int32 b2).Item2", "System.Int32 (System.Int32 a2, System.Int32 b2).b2", "(System.Int32 a2, System.Int32 b2)..ctor()", "(System.Int32 a2, System.Int32 b2)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32 a2, System.Int32 b2).Equals(System.Object obj)", "System.Boolean (System.Int32 a2, System.Int32 b2).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a2, System.Int32 b2).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a2, System.Int32 b2).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a2, System.Int32 b2).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2).GetHashCode()", "System.Int32 (System.Int32 a2, System.Int32 b2).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a2, System.Int32 b2).ToString()", "System.String (System.Int32 a2, System.Int32 b2).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a2, System.Int32 b2).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a2, System.Int32 b2).System.ITupleInternal.Size { get; }"); Assert.Equal(new string[] { ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString" }, m2Tuple.TupleData.UnderlyingDefinitionToMemberMap.Values.Select(s => s.Name).OrderBy(n => n).ToArray()); AssertTestDisplayString(m6Tuple.GetMembers(), "System.Int32 (System.Int32 item1, System.Int32 item2).Item1", "System.Int32 (System.Int32 item1, System.Int32 item2).item1", "System.Int32 (System.Int32 item1, System.Int32 item2).Item2", "System.Int32 (System.Int32 item1, System.Int32 item2).item2", "(System.Int32 item1, System.Int32 item2)..ctor()", "(System.Int32 item1, System.Int32 item2)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32 item1, System.Int32 item2).Equals(System.Object obj)", "System.Boolean (System.Int32 item1, System.Int32 item2).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32 item1, System.Int32 item2).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 item1, System.Int32 item2).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 item1, System.Int32 item2).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32 item1, System.Int32 item2).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 item1, System.Int32 item2).GetHashCode()", "System.Int32 (System.Int32 item1, System.Int32 item2).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 item1, System.Int32 item2).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 item1, System.Int32 item2).ToString()", "System.String (System.Int32 item1, System.Int32 item2).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 item1, System.Int32 item2).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 item1, System.Int32 item2).System.ITupleInternal.Size { get; }"); Assert.Equal(new string[] { ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString" }, m6Tuple.TupleData.UnderlyingDefinitionToMemberMap.Values.Select(s => s.Name).OrderBy(n => n).ToArray()); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("ValueTuple", m1Tuple.Name); Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind); Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind); Assert.False(m1Tuple.IsImplicitlyDeclared); Assert.True(m1Tuple.IsTupleType); Assert.True(m1Tuple.Equals(m1Tuple.TupleUnderlyingType, TypeCompareKind.ConsiderEverything)); var tupleType = comp.Compilation.CommonGetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.Same(tupleType, m1Tuple.ConstructedFrom); Assert.False(m1Tuple.IsDefinition); Assert.Same(tupleType, m1Tuple.OriginalDefinition); AssertTupleTypeEquality(m1Tuple); Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol); Assert.Same(m1Tuple.ContainingSymbol, m1Tuple.ContainingSymbol); Assert.Null(m1Tuple.GetUseSiteDiagnostic()); Assert.Null(m1Tuple.EnumUnderlyingType); AssertEx.SetEqual(new[] { "Item1", "Item2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m1Tuple.MemberNames.ToArray()); Assert.Equal("(System.Int32 a2, System.Int32 b2)", m2Tuple.ToTestDisplayString()); AssertEx.SetEqual(new[] { "Item1", "a2", "Item2", "b2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m2Tuple.MemberNames.ToArray()); Assert.Equal(2, m1Tuple.Arity); Assert.Equal(new[] { "T1", "T2" }, m1Tuple.TypeParameters.Select(tp => tp.ToTestDisplayString())); Assert.Equal("System.ValueType", m1Tuple.BaseType().ToTestDisplayString()); Assert.Null(m1Tuple.ComImportCoClass); Assert.True(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Assert.False(m1Tuple.IsComImport); Assert.Equal(new[] { "System.Int32", "System.Int32" }, m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Select(t => t.ToTestDisplayString())); Assert.True(m1Tuple.GetAttributes().IsEmpty); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).a2", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembers().IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty); Assert.Equal(6, m1Tuple.Interfaces().Length); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Tuple.GetEarlyAttributeDecodingMembers("Item1").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty); Assert.Equal(1, m1Tuple.Locations.Length); Assert.Equal("(int, int)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("(int a2, int b2)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); AssertTupleTypeEquality(m2Tuple); AssertTupleTypeEquality(m6Tuple); Assert.False(m1Tuple.Equals(m2Tuple)); Assert.False(m1Tuple.Equals(m6Tuple)); Assert.False(m6Tuple.Equals(m2Tuple)); AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m6Tuple); AssertTupleTypeMembersEquality(m2Tuple, m6Tuple); var m1Item1 = (FieldSymbol)m1Tuple.GetMembers()[0]; var m2Item1 = (FieldSymbol)m2Tuple.GetMembers()[0]; var m2a2 = (FieldSymbol)m2Tuple.GetMembers()[1]; AssertNonvirtualTupleElementField(m1Item1); AssertNonvirtualTupleElementField(m2Item1); AssertVirtualTupleElementField(m2a2); Assert.IsType<TupleElementFieldSymbol>(m1Item1); Assert.NotSame(m1Item1, m1Item1.OriginalDefinition); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Item1.ToTestDisplayString()); Assert.Equal("T1 (T1, T2).Item1", m1Item1.OriginalDefinition.ToTestDisplayString()); Assert.True(m1Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m1Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.True(m1Item1.Equals(m1Item1)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m1Item1.AssociatedSymbol); Assert.Same(m1Tuple, m1Item1.ContainingSymbol); Assert.Same(m1Tuple, m1Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m1Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1Item1.GetAttributes().IsEmpty); Assert.Null(m1Item1.GetUseSiteDiagnostic()); Assert.False(m1Item1.Locations.IsEmpty); Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m1Item1.TupleUnderlyingField.Name); Assert.True(m1Item1.IsImplicitlyDeclared); Assert.Null(m1Item1.TypeLayoutOffset); Assert.IsType<TupleElementFieldSymbol>(m2Item1); Assert.False(m2Item1.IsDefinition); Assert.NotSame(m2Item1, m2Item1.OriginalDefinition); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Item1.ToTestDisplayString()); Assert.Equal("T1 (T1, T2).Item1", m2Item1.OriginalDefinition.ToTestDisplayString()); Assert.True(m2Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m2Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.True(m2Item1.Equals(m2Item1)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2Item1.AssociatedSymbol); Assert.False(m2Tuple.IsDefinition); Assert.Same(m2Tuple, m2Item1.ContainingSymbol); Assert.Same(m2Tuple, m2Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m2Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2Item1.GetAttributes().IsEmpty); Assert.Null(m2Item1.GetUseSiteDiagnostic()); Assert.False(m2Item1.Locations.IsEmpty); Assert.Equal("Item1", m2Item1.Name); Assert.Equal("Item1", m2Item1.TupleUnderlyingField.Name); Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()); Assert.Equal("MetadataFile(System.ValueTuple.dll)", m2Item1.TupleUnderlyingField.Locations.Single().ToString()); Assert.Equal("SourceFile([826..828))", m2Item1.Locations.Single().ToString()); Assert.True(m2Item1.IsImplicitlyDeclared); Assert.Null(m2Item1.TypeLayoutOffset); Assert.IsType<TupleVirtualElementFieldSymbol>(m2a2); Assert.True(m2a2.IsDefinition); Assert.True(m2a2.Equals(m2a2)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).a2", m2a2.ToTestDisplayString()); Assert.True(m2a2.ContainingType.OriginalDefinition.TupleElements[0].Equals(m1Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2a2.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2a2.AssociatedSymbol); Assert.Same(m2Tuple, m2a2.ContainingSymbol); Assert.Same(m2Tuple, m2a2.TupleUnderlyingField.ContainingSymbol); Assert.True(m2a2.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2a2.GetAttributes().IsEmpty); Assert.Null(m2a2.GetUseSiteDiagnostic()); Assert.False(m2a2.Locations.IsEmpty); Assert.Equal("int a2", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m2a2.TupleUnderlyingField.Name); Assert.False(m2a2.IsImplicitlyDeclared); Assert.Null(m2a2.TypeLayoutOffset); Assert.False(m6Tuple.IsDefinition); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28045")] public void DefaultAndFriendlyElementNames_LongTuple() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Console.Write(v1.Item9 + "" ""); var v1b = M1b(); System.Console.Write(v1b.Item9 + "" ""); var v2 = M2(); System.Console.Write(v2.Item9 + "" ""); System.Console.Write(v2.i2 + "" ""); var v6 = M6(); System.Console.Write(v6.item8 + "" ""); } static (int, int, int, int, int, int, int, int, int) M1() => (1, 1, 1, 11, 11, 11, 111, 111, 111); static ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>> M1b() => (1, 1, 1, 11, 11, 11, 111, 111, 111); static (int a2, int b2, int c2, int d2, int e2, int f2, int g2, int h2, int i2) M2() => (2, 2, 2, 22, 22, 22, 222, 222, 222); static (int item1, int item2, int item3, int item4, int item5, int item6, int item7, int item8) M6() => (6, 6, 6, 66, 66, 66, 666, 666); } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"111 111 222 222 666"); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; var m1bTuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1b").ReturnType; var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m6Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M6").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7", "(System.Int32, System.Int32) (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item1", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).a2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).b2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item3", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).c2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item4", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).d2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item5", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).e2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item6", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).f2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item7", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).g2", "(System.Int32, System.Int32) (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Rest", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item8", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).h2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item9", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).i2", "(System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2)..ctor()", "(System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Equals(System.Object obj)", "System.Boolean (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).GetHashCode()", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).ToString()", "System.String (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.Size { get; }"); Assert.Equal("ValueTuple", m1Tuple.Name); Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind); Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind); Assert.False(m1Tuple.IsImplicitlyDeclared); Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString()); Assert.Equal("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", m1Tuple.OriginalDefinition.ToTestDisplayString()); Assert.Same(m1Tuple.OriginalDefinition, m1Tuple.ConstructedFrom); AssertTupleTypeEquality(m1Tuple); Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol); Assert.True(m1Tuple.TupleUnderlyingType.Equals(m1Tuple, TypeCompareKind.ConsiderEverything)); Assert.Null(m1Tuple.GetUseSiteDiagnostic()); Assert.Null(m1Tuple.EnumUnderlyingType); AssertEx.Equal(new[] { "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Rest", "Item8", "Item9" , ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m1Tuple.MemberNames.ToArray()); AssertEx.Equal(new[] { "Item1", "a2", "Item2", "b2", "Item3", "c2", "Item4", "d2", "Item5", "e2", "Item6", "f2", "Item7", "g2", "Rest", "Item8", "h2", "Item9", "i2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m2Tuple.MemberNames.ToArray()); Assert.Equal(8, m1Tuple.Arity); AssertEx.Equal(new[] { "T1", "T2", "T3", "T4", "T5", "T6", "T7", "TRest" }, m1Tuple.TypeParameters.ToTestDisplayStrings()); Assert.Equal("System.ValueType", m1Tuple.BaseType().ToTestDisplayString()); Assert.Null(m1Tuple.ComImportCoClass); Assert.True(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Assert.False(m1Tuple.IsComImport); AssertEx.Equal(new[] { "System.Int32", "System.Int32", "System.Int32", "System.Int32", "System.Int32", "System.Int32", "System.Int32", "(System.Int32, System.Int32)" }, m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.ToTestDisplayStrings()); Assert.True(m1Tuple.GetAttributes().IsEmpty); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item9", m2Tuple.GetMembers("Item9").Single().ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).i2", m2Tuple.GetMembers("i2").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembers().IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty); Assert.Equal(6, m1Tuple.Interfaces().Length); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", m1Tuple.GetEarlyAttributeDecodingMembers("Item1").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty); Assert.Equal(1, m1Tuple.Locations.Length); Assert.Equal("(int, int, int, int, int, int, int, int, int)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("(int a2, int b2, int c2, int d2, int e2, int f2, int g2, int h2, int i2)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); AssertTupleTypeEquality(m2Tuple); AssertTupleTypeEquality(m6Tuple); Assert.False(m1Tuple.Equals(m2Tuple)); Assert.False(m1Tuple.Equals(m6Tuple)); Assert.False(m6Tuple.Equals(m2Tuple)); AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m6Tuple); AssertTupleTypeMembersEquality(m2Tuple, m6Tuple); var m1Item7 = (FieldSymbol)m1Tuple.GetMembers().Where(m => m.Name == "Item7").Single(); var m1Item9 = (FieldSymbol)m1Tuple.GetMembers().Where(m => m.Name == "Item9").Single(); AssertNonvirtualTupleElementField(m1Item7); AssertVirtualTupleElementField(m1Item9); var m2g2 = (FieldSymbol)m2Tuple.GetMembers().Where(m => m.Name == "g2").Single(); var m2Item9 = (FieldSymbol)m2Tuple.GetMembers().Where(m => m.Name == "Item9").Single(); var m2i2 = (FieldSymbol)m2Tuple.GetMembers().Where(m => m.Name == "i2").Single(); AssertVirtualTupleElementField(m2g2); AssertVirtualTupleElementField(m2Item9); AssertVirtualTupleElementField(m2i2); Assert.Same(m1Item9, m1Item9.OriginalDefinition); Assert.True(m1Item9.Equals(m1Item9)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item2", m1Item9.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m1Item9.AssociatedSymbol); Assert.Same(m1Tuple, m1Item9.ContainingSymbol); Assert.Same(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Last().Type, m1Item9.TupleUnderlyingField.ContainingSymbol); Assert.True(m1Item9.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1Item9.GetAttributes().IsEmpty); Assert.Null(m1Item9.GetUseSiteDiagnostic()); Assert.False(m1Item9.Locations.IsEmpty); Assert.True(m1Item9.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item2", m1Item9.TupleUnderlyingField.Name); Assert.True(m1Item9.IsImplicitlyDeclared); Assert.Null(m1Item9.TypeLayoutOffset); Assert.Same(m2Item9, m2Item9.OriginalDefinition); Assert.True(m2Item9.Equals(m2Item9)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item2", m2Item9.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2Item9.AssociatedSymbol); Assert.Same(m2Tuple, m2Item9.ContainingSymbol); Assert.Same(m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Last().Type, m2Item9.TupleUnderlyingField.ContainingSymbol); Assert.True(m2Item9.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2Item9.GetAttributes().IsEmpty); Assert.Null(m2Item9.GetUseSiteDiagnostic()); Assert.False(m2Item9.Locations.IsEmpty); Assert.Equal("Item9", m2Item9.Name); Assert.Equal("Item2", m2Item9.TupleUnderlyingField.Name); Assert.Equal("SourceFile([739..741))", m2Item9.Locations.Single().ToString()); Assert.Equal("MetadataFile(System.ValueTuple.dll)", m2Item9.TupleUnderlyingField.Locations.Single().ToString()); Assert.True(m2Item9.IsImplicitlyDeclared); Assert.Null(m2Item9.TypeLayoutOffset); Assert.Same(m2i2, m2i2.OriginalDefinition); Assert.True(m2i2.Equals(m2i2)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item2", m2i2.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2i2.AssociatedSymbol); Assert.Same(m2Tuple, m2i2.ContainingSymbol); Assert.Same(m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Last().Type, m2i2.TupleUnderlyingField.ContainingSymbol); Assert.True(m2i2.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2i2.GetAttributes().IsEmpty); Assert.Null(m2i2.GetUseSiteDiagnostic()); Assert.False(m2i2.Locations.IsEmpty); Assert.Equal("int i2", m2i2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item2", m2i2.TupleUnderlyingField.Name); Assert.False(m2i2.IsImplicitlyDeclared); Assert.Null(m2i2.TypeLayoutOffset); } private static void AssertTupleTypeEquality(TypeSymbol tuple) { Assert.True(tuple.Equals(tuple)); Assert.True(tuple.Equals(tuple, TypeCompareKind.ConsiderEverything)); Assert.True(tuple.Equals(tuple, TypeCompareKind.IgnoreDynamicAndTupleNames)); var members = tuple.GetMembers(); for (int i = 0; i < members.Length; i++) { for (int j = 0; j < members.Length; j++) { if (i != j) { Assert.NotSame(members[i], members[j]); Assert.False(members[i].Equals(members[j])); Assert.False(members[j].Equals(members[i])); } } } } private static void AssertTupleTypeMembersEquality(TypeSymbol tuple1, TypeSymbol tuple2) { Assert.NotSame(tuple1, tuple2); if (tuple1.Equals(tuple2)) { Assert.True(tuple2.Equals(tuple1)); var members1 = tuple1.GetMembers(); var members2 = tuple2.GetMembers(); Assert.Equal(members1.Length, members2.Length); for (int i = 0; i < members1.Length; i++) { Assert.NotSame(members1[i], members2[i]); Assert.True(members1[i].Equals(members2[i])); Assert.True(members2[i].Equals(members1[i])); Assert.Equal(members2[i].GetHashCode(), members1[i].GetHashCode()); if (members1[i].Kind == SymbolKind.Method) { var parameters1 = ((MethodSymbol)members1[i]).Parameters; var parameters2 = ((MethodSymbol)members2[i]).Parameters; AssertTupleMembersParametersEquality(parameters1, parameters2); var typeParameters1 = ((MethodSymbol)members1[i]).TypeParameters; var typeParameters2 = ((MethodSymbol)members2[i]).TypeParameters; Assert.Equal(typeParameters1.Length, typeParameters2.Length); for (int j = 0; j < typeParameters1.Length; j++) { Assert.NotSame(typeParameters1[j], typeParameters2[j]); Assert.True(typeParameters1[j].Equals(typeParameters2[j])); Assert.True(typeParameters2[j].Equals(typeParameters1[j])); Assert.Equal(typeParameters2[j].GetHashCode(), typeParameters1[j].GetHashCode()); } } else if (members1[i].Kind == SymbolKind.Property) { var parameters1 = ((PropertySymbol)members1[i]).Parameters; var parameters2 = ((PropertySymbol)members2[i]).Parameters; AssertTupleMembersParametersEquality(parameters1, parameters2); } } for (int i = 0; i < members1.Length; i++) { for (int j = 0; j < members2.Length; j++) { if (i != j) { Assert.NotSame(members1[i], members2[j]); Assert.False(members1[i].Equals(members2[j])); } } } } else { Assert.False(tuple2.Equals(tuple1)); var members1 = tuple1.GetMembers(); var members2 = tuple2.GetMembers(); foreach (var m in members1) { Assert.False(members2.Any(u => u.Equals(m))); Assert.False(members2.Any(u => m.Equals(u))); } } } private static void AssertTupleMembersParametersEquality(ImmutableArray<ParameterSymbol> parameters1, ImmutableArray<ParameterSymbol> parameters2) { Assert.Equal(parameters1.Length, parameters2.Length); for (int j = 0; j < parameters1.Length; j++) { Assert.NotSame(parameters1[j], parameters2[j]); Assert.True(parameters1[j].Equals(parameters2[j])); Assert.True(parameters2[j].Equals(parameters1[j])); Assert.Equal(parameters2[j].GetHashCode(), parameters1[j].GetHashCode()); } } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_02() { var source = @" using System; class C { static void Main() { var v3 = M3(); System.Console.WriteLine(v3.Item1); System.Console.WriteLine(v3.Item2); System.Console.WriteLine(v3.Item3); System.Console.WriteLine(v3.Item4); System.Console.WriteLine(v3.Item5); System.Console.WriteLine(v3.Item6); System.Console.WriteLine(v3.Item7); System.Console.WriteLine(v3.Item8); System.Console.WriteLine(v3.Item9); System.Console.WriteLine(v3.Rest.Item1); System.Console.WriteLine(v3.Rest.Item2); System.Console.WriteLine(v3.ToString()); } static (int, int, int, int, int, int, int, int, int) M3() { return (31, 32, 33, 34, 35, 36, 37, 38, 39); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"31 32 33 34 35 36 37 38 39 38 39 (31, 32, 33, 34, 35, 36, 37, 38, 39) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; AssertTupleTypeEquality(m3Tuple); AssertTestDisplayString(m3Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7", "(System.Int32, System.Int32) (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); var m3Item8 = (FieldSymbol)m3Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m3Item8); Assert.Same(m3Item8, m3Item8.OriginalDefinition); Assert.True(m3Item8.Equals(m3Item8)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m3Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m3Item8.AssociatedSymbol); Assert.Same(m3Tuple, m3Item8.ContainingSymbol); Assert.NotEqual(m3Tuple.TupleUnderlyingType, m3Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m3Tuple, m3Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m3Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m3Item8.GetAttributes().IsEmpty); Assert.Null(m3Item8.GetUseSiteDiagnostic()); Assert.False(m3Item8.Locations.IsEmpty); Assert.True(m3Item8.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m3Item8.TupleUnderlyingField.Name); Assert.True(m3Item8.IsImplicitlyDeclared); Assert.Null(m3Item8.TypeLayoutOffset); var m3TupleRestTuple = (NamedTypeSymbol)((FieldSymbol)m3Tuple.GetMembers("Rest").Single()).Type; AssertTestDisplayString(m3TupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); Assert.True(m3TupleRestTuple.IsTupleType); AssertTupleTypeEquality(m3TupleRestTuple); Assert.True(m3TupleRestTuple.Locations.IsEmpty); Assert.True(m3TupleRestTuple.DeclaringSyntaxReferences.IsEmpty); foreach (var m in m3TupleRestTuple.GetMembers().OfType<FieldSymbol>()) { Assert.True(m.Locations.IsEmpty); } } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_03() { var source = @" using System; class C { static void Main() { var v4 = M4 (); System.Console.WriteLine(v4.Item1); System.Console.WriteLine(v4.Item2); System.Console.WriteLine(v4.Item3); System.Console.WriteLine(v4.Item4); System.Console.WriteLine(v4.Item5); System.Console.WriteLine(v4.Item6); System.Console.WriteLine(v4.Item7); System.Console.WriteLine(v4.Item8); System.Console.WriteLine(v4.Item9); System.Console.WriteLine(v4.Rest.Item1); System.Console.WriteLine(v4.Rest.Item2); System.Console.WriteLine(v4.a4); System.Console.WriteLine(v4.b4); System.Console.WriteLine(v4.c4); System.Console.WriteLine(v4.d4); System.Console.WriteLine(v4.e4); System.Console.WriteLine(v4.f4); System.Console.WriteLine(v4.g4); System.Console.WriteLine(v4.h4); System.Console.WriteLine(v4.i4); System.Console.WriteLine(v4.ToString()); } static (int a4, int b4, int c4, int d4, int e4, int f4, int g4, int h4, int i4) M4() { return (41, 42, 43, 44, 45, 46, 47, 48, 49); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"41 42 43 44 45 46 47 48 49 48 49 41 42 43 44 45 46 47 48 49 (41, 42, 43, 44, 45, 46, 47, 48, 49) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m4Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M4").ReturnType; AssertTupleTypeEquality(m4Tuple); AssertTestDisplayString(m4Tuple.GetMembers(), "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item1", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".a4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item2", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".b4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item3", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".c4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".d4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item5", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".e4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item6", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".f4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item7", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".g4", "(System.Int32, System.Int32) (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Rest", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item8", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".h4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item9", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".i4", "(System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + "..ctor()", "(System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + "..ctor" + "(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Equals(System.Object obj)", "System.Boolean (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".GetHashCode()", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".ToString()", "System.String (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.Size { get; }" ); var m4Item8 = (FieldSymbol)m4Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m4Item8); Assert.Same(m4Item8, m4Item8.OriginalDefinition); Assert.True(m4Item8.Equals(m4Item8)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m4Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m4Item8.AssociatedSymbol); Assert.Same(m4Tuple, m4Item8.ContainingSymbol); Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m4Tuple, m4Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m4Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m4Item8.GetAttributes().IsEmpty); Assert.Null(m4Item8.GetUseSiteDiagnostic()); Assert.False(m4Item8.Locations.IsEmpty); Assert.Equal("Item1", m4Item8.TupleUnderlyingField.Name); Assert.True(m4Item8.IsImplicitlyDeclared); Assert.Null(m4Item8.TypeLayoutOffset); var m4h4 = (FieldSymbol)m4Tuple.GetMembers("h4").Single(); AssertVirtualTupleElementField(m4h4); Assert.Same(m4h4, m4h4.OriginalDefinition); Assert.True(m4h4.Equals(m4h4)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m4h4.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m4h4.AssociatedSymbol); Assert.Same(m4Tuple, m4h4.ContainingSymbol); Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4h4.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m4Tuple, m4h4.TupleUnderlyingField.ContainingSymbol); Assert.True(m4h4.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m4h4.GetAttributes().IsEmpty); Assert.Null(m4h4.GetUseSiteDiagnostic()); Assert.False(m4h4.Locations.IsEmpty); Assert.Equal("int h4", m4h4.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m4h4.TupleUnderlyingField.Name); Assert.False(m4h4.IsImplicitlyDeclared); Assert.Null(m4h4.TypeLayoutOffset); var m4TupleRestTuple = ((FieldSymbol)m4Tuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m4TupleRestTuple); AssertTestDisplayString(m4TupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); foreach (var m in m4TupleRestTuple.GetMembers().OfType<FieldSymbol>()) { Assert.True(m.Locations.IsEmpty); } } [Fact] public void DefaultAndFriendlyElementNames_04() { var source = @" class C { static void Main() { var v4 = M4 (); System.Console.WriteLine(v4.Rest.a4); System.Console.WriteLine(v4.Rest.b4); System.Console.WriteLine(v4.Rest.c4); System.Console.WriteLine(v4.Rest.d4); System.Console.WriteLine(v4.Rest.e4); System.Console.WriteLine(v4.Rest.f4); System.Console.WriteLine(v4.Rest.g4); System.Console.WriteLine(v4.Rest.h4); System.Console.WriteLine(v4.Rest.i4); } static (int a4, int b4, int c4, int d4, int e4, int f4, int g4, int h4, int i4) M4() { return (41, 42, 43, 44, 45, 46, 47, 48, 49); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,42): error CS1061: '(int, int)' does not contain a definition for 'a4' and no extension method 'a4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.a4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a4").WithArguments("(int, int)", "a4").WithLocation(8, 42), // (9,42): error CS1061: '(int, int)' does not contain a definition for 'b4' and no extension method 'b4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.b4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b4").WithArguments("(int, int)", "b4").WithLocation(9, 42), // (10,42): error CS1061: '(int, int)' does not contain a definition for 'c4' and no extension method 'c4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.c4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c4").WithArguments("(int, int)", "c4").WithLocation(10, 42), // (11,42): error CS1061: '(int, int)' does not contain a definition for 'd4' and no extension method 'd4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.d4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "d4").WithArguments("(int, int)", "d4").WithLocation(11, 42), // (12,42): error CS1061: '(int, int)' does not contain a definition for 'e4' and no extension method 'e4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.e4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "e4").WithArguments("(int, int)", "e4").WithLocation(12, 42), // (13,42): error CS1061: '(int, int)' does not contain a definition for 'f4' and no extension method 'f4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.f4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "f4").WithArguments("(int, int)", "f4").WithLocation(13, 42), // (14,42): error CS1061: '(int, int)' does not contain a definition for 'g4' and no extension method 'g4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.g4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "g4").WithArguments("(int, int)", "g4").WithLocation(14, 42), // (15,42): error CS1061: '(int, int)' does not contain a definition for 'h4' and no extension method 'h4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.h4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "h4").WithArguments("(int, int)", "h4").WithLocation(15, 42), // (16,42): error CS1061: '(int, int)' does not contain a definition for 'i4' and no extension method 'i4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.i4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "i4").WithArguments("(int, int)", "i4").WithLocation(16, 42) ); } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_05() { var source = @" using System; class C { static void Main() { var v5 = M5(); System.Console.WriteLine(v5.Item1); System.Console.WriteLine(v5.Item2); System.Console.WriteLine(v5.Item3); System.Console.WriteLine(v5.Item4); System.Console.WriteLine(v5.Item5); System.Console.WriteLine(v5.Item6); System.Console.WriteLine(v5.Item7); System.Console.WriteLine(v5.Item8); System.Console.WriteLine(v5.Item9); System.Console.WriteLine(v5.Item10); System.Console.WriteLine(v5.Item11); System.Console.WriteLine(v5.Item12); System.Console.WriteLine(v5.Item13); System.Console.WriteLine(v5.Item14); System.Console.WriteLine(v5.Item15); System.Console.WriteLine(v5.Item16); System.Console.WriteLine(v5.Rest.Item1); System.Console.WriteLine(v5.Rest.Item2); System.Console.WriteLine(v5.Rest.Item3); System.Console.WriteLine(v5.Rest.Item4); System.Console.WriteLine(v5.Rest.Item5); System.Console.WriteLine(v5.Rest.Item6); System.Console.WriteLine(v5.Rest.Item7); System.Console.WriteLine(v5.Rest.Item8); System.Console.WriteLine(v5.Rest.Item9); System.Console.WriteLine(v5.Rest.Rest.Item1); System.Console.WriteLine(v5.Rest.Rest.Item2); System.Console.WriteLine(v5.ToString()); } static (int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8, int Item9, int Item10, int Item11, int Item12, int Item13, int Item14, int Item15, int Item16) M5() { return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 508 509 510 511 512 513 514 515 516 515 516 (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m5Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M5").ReturnType; AssertTupleTypeEquality(m5Tuple); AssertTestDisplayString(m5Tuple.GetMembers(), "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item1", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item2", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item3", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item4", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item5", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item6", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item7", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Rest", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item8", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item9", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item10", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item11", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item12", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item13", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item14", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item15", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item16", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16)..ctor()", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) rest)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Equals(System.Object obj)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).GetHashCode()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).ToString()", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.Size { get; }" ); var m5Item8 = (FieldSymbol)m5Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m5Item8); Assert.Same(m5Item8, m5Item8.OriginalDefinition); Assert.True(m5Item8.Equals(m5Item8)); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", m5Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m5Item8.AssociatedSymbol); Assert.Same(m5Tuple, m5Item8.ContainingSymbol); Assert.NotEqual(m5Tuple.TupleUnderlyingType, m5Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m5Tuple, m5Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m5Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m5Item8.GetAttributes().IsEmpty); Assert.Null(m5Item8.GetUseSiteDiagnostic()); Assert.False(m5Item8.Locations.IsEmpty); Assert.Equal("int Item8", m5Item8.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m5Item8.TupleUnderlyingField.Name); Assert.False(m5Item8.IsImplicitlyDeclared); Assert.Null(m5Item8.TypeLayoutOffset); var m5TupleRestTuple = ((FieldSymbol)m5Tuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m5TupleRestTuple); AssertTestDisplayString(m5TupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7", "(System.Int32, System.Int32) (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); foreach (var m in m5TupleRestTuple.GetMembers().OfType<FieldSymbol>()) { if (m.Name != "Rest") { Assert.True(m.Locations.IsEmpty); } else { Assert.Equal("Rest", m.Name); } } var m5TupleRestTupleRestTuple = ((FieldSymbol)m5TupleRestTuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m5TupleRestTupleRestTuple); AssertTestDisplayString(m5TupleRestTupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); foreach (var m in m5TupleRestTupleRestTuple.GetMembers().OfType<FieldSymbol>()) { Assert.True(m.Locations.IsEmpty); } } [Fact] public void DefaultAndFriendlyElementNames_06() { var source = @" class C { static void Main() { var v5 = M5(); System.Console.WriteLine(v5.Rest.Item10); System.Console.WriteLine(v5.Rest.Item11); System.Console.WriteLine(v5.Rest.Item12); System.Console.WriteLine(v5.Rest.Item13); System.Console.WriteLine(v5.Rest.Item14); System.Console.WriteLine(v5.Rest.Item15); System.Console.WriteLine(v5.Rest.Item16); System.Console.WriteLine(v5.Rest.Rest.Item3); System.Console.WriteLine(v5.Rest.Rest.Item4); System.Console.WriteLine(v5.Rest.Rest.Item5); System.Console.WriteLine(v5.Rest.Rest.Item6); System.Console.WriteLine(v5.Rest.Rest.Item7); System.Console.WriteLine(v5.Rest.Rest.Item8); System.Console.WriteLine(v5.Rest.Rest.Item9); System.Console.WriteLine(v5.Rest.Rest.Item10); System.Console.WriteLine(v5.Rest.Rest.Item11); System.Console.WriteLine(v5.Rest.Rest.Item12); System.Console.WriteLine(v5.Rest.Rest.Item13); System.Console.WriteLine(v5.Rest.Rest.Item14); System.Console.WriteLine(v5.Rest.Rest.Item15); System.Console.WriteLine(v5.Rest.Rest.Item16); } static (int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8, int Item9, int Item10, int Item11, int Item12, int Item13, int Item14, int Item15, int Item16) M5() { return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item10' and no extension method 'Item10' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item10); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item10").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item10").WithLocation(8, 42), // (9,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item11' and no extension method 'Item11' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item11); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item11").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item11").WithLocation(9, 42), // (10,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item12' and no extension method 'Item12' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item12); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item12").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item12").WithLocation(10, 42), // (11,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item13' and no extension method 'Item13' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item13); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item13").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item13").WithLocation(11, 42), // (12,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item14' and no extension method 'Item14' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item14); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item14").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item14").WithLocation(12, 42), // (13,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item15' and no extension method 'Item15' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item15); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item15").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item15").WithLocation(13, 42), // (14,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item16' and no extension method 'Item16' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item16); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item16").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item16").WithLocation(14, 42), // (16,47): error CS1061: '(int, int)' does not contain a definition for 'Item3' and no extension method 'Item3' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item3); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item3").WithArguments("(int, int)", "Item3").WithLocation(16, 47), // (17,47): error CS1061: '(int, int)' does not contain a definition for 'Item4' and no extension method 'Item4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item4").WithArguments("(int, int)", "Item4").WithLocation(17, 47), // (18,47): error CS1061: '(int, int)' does not contain a definition for 'Item5' and no extension method 'Item5' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item5); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item5").WithArguments("(int, int)", "Item5").WithLocation(18, 47), // (19,47): error CS1061: '(int, int)' does not contain a definition for 'Item6' and no extension method 'Item6' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item6); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item6").WithArguments("(int, int)", "Item6").WithLocation(19, 47), // (20,47): error CS1061: '(int, int)' does not contain a definition for 'Item7' and no extension method 'Item7' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item7); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item7").WithArguments("(int, int)", "Item7").WithLocation(20, 47), // (21,47): error CS1061: '(int, int)' does not contain a definition for 'Item8' and no extension method 'Item8' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("(int, int)", "Item8").WithLocation(21, 47), // (22,47): error CS1061: '(int, int)' does not contain a definition for 'Item9' and no extension method 'Item9' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item9); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item9").WithArguments("(int, int)", "Item9").WithLocation(22, 47), // (23,47): error CS1061: '(int, int)' does not contain a definition for 'Item10' and no extension method 'Item10' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item10); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item10").WithArguments("(int, int)", "Item10").WithLocation(23, 47), // (24,47): error CS1061: '(int, int)' does not contain a definition for 'Item11' and no extension method 'Item11' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item11); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item11").WithArguments("(int, int)", "Item11").WithLocation(24, 47), // (25,47): error CS1061: '(int, int)' does not contain a definition for 'Item12' and no extension method 'Item12' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item12); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item12").WithArguments("(int, int)", "Item12").WithLocation(25, 47), // (26,47): error CS1061: '(int, int)' does not contain a definition for 'Item13' and no extension method 'Item13' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item13); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item13").WithArguments("(int, int)", "Item13").WithLocation(26, 47), // (27,47): error CS1061: '(int, int)' does not contain a definition for 'Item14' and no extension method 'Item14' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item14); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item14").WithArguments("(int, int)", "Item14").WithLocation(27, 47), // (28,47): error CS1061: '(int, int)' does not contain a definition for 'Item15' and no extension method 'Item15' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item15); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item15").WithArguments("(int, int)", "Item15").WithLocation(28, 47), // (29,47): error CS1061: '(int, int)' does not contain a definition for 'Item16' and no extension method 'Item16' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item16); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item16").WithArguments("(int, int)", "Item16").WithLocation(29, 47) ); } [Fact] public void DefaultAndFriendlyElementNames_07() { var source = @" class C { static void Main() { } static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() { return (701, 702, 703, 704, 705, 706, 707, 708, 709); } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): error CS8125: Tuple member name 'Item9' is only allowed at position 9. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item9").WithArguments("Item9", "9").WithLocation(9, 17), // (9,28): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(9, 28), // (9,39): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(9, 39), // (9,50): error CS8125: Tuple member name 'Item3' is only allowed at position 3. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item3").WithArguments("Item3", "3").WithLocation(9, 50), // (9,61): error CS8125: Tuple member name 'Item4' is only allowed at position 4. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item4").WithArguments("Item4", "4").WithLocation(9, 61), // (9,72): error CS8125: Tuple member name 'Item5' is only allowed at position 5. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item5").WithArguments("Item5", "5").WithLocation(9, 72), // (9,83): error CS8125: Tuple member name 'Item6' is only allowed at position 6. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item6").WithArguments("Item6", "6").WithLocation(9, 83), // (9,94): error CS8125: Tuple member name 'Item7' is only allowed at position 7. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item7").WithArguments("Item7", "7").WithLocation(9, 94), // (9,105): error CS8125: Tuple member name 'Item8' is only allowed at position 8. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item8").WithArguments("Item8", "8").WithLocation(9, 105) ); var c = comp.GetTypeByMetadataName("C"); var m7Tuple = c.GetMember<MethodSymbol>("M7").ReturnType; AssertTupleTypeEquality(m7Tuple); AssertTestDisplayString(m7Tuple.GetMembers(), "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item1", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item9", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item2", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item1", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item3", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item2", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item4", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item3", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item5", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item4", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item6", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item5", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item7", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item6", "(System.Int32, System.Int32) (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Rest", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item8", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item7", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item9", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item8", "(System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + "..ctor" + "(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.String (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".ToString()", "(System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + "..ctor()" ); } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_08() { var source = @" class C { static void Main() { } static (int a1, int a2, int a3, int a4, int a5, int a6, int a7, int Item1) M8() { return (801, 802, 803, 804, 805, 806, 807, 808); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,73): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // static (int a1, int a2, int a3, int a4, int a5, int a6, int a7, int Item1) M8() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(9, 73) ); var c = comp.GetTypeByMetadataName("C"); var m8Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M8").ReturnType; AssertTupleTypeEquality(m8Tuple); AssertTestDisplayString(m8Tuple.GetMembers(), "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item1", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a1", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item2", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a2", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item3", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a3", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item4", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a4", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item5", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a5", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item6", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a6", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item7", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a7", "System.ValueTuple<System.Int32> (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Rest", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item8", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item1", "(System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1)..ctor()", "(System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, System.ValueTuple<System.Int32> rest)", "System.Boolean (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Equals(System.Object obj)", "System.Boolean (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).GetHashCode()", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).ToString()", "System.String (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.Size { get; }"); var m8Item8 = (FieldSymbol)m8Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m8Item8); Assert.Same(m8Item8, m8Item8.OriginalDefinition); Assert.True(m8Item8.Equals(m8Item8)); Assert.Equal("System.Int32 System.ValueTuple<System.Int32>.Item1", m8Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m8Item8.AssociatedSymbol); Assert.Same(m8Tuple, m8Item8.ContainingSymbol); Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m8Tuple, m8Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m8Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m8Item8.GetAttributes().IsEmpty); Assert.Null(m8Item8.GetUseSiteDiagnostic()); Assert.False(m8Item8.Locations.IsEmpty); Assert.Equal("Item1", m8Item8.TupleUnderlyingField.Name); Assert.True(m8Item8.IsImplicitlyDeclared); Assert.Null(m8Item8.TypeLayoutOffset); var m8Item1 = (FieldSymbol)m8Tuple.GetMembers("Item1").Last(); AssertVirtualTupleElementField(m8Item1); Assert.Same(m8Item1, m8Item1.OriginalDefinition); Assert.True(m8Item1.Equals(m8Item1)); Assert.Equal("System.Int32 System.ValueTuple<System.Int32>.Item1", m8Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m8Item1.AssociatedSymbol); Assert.Same(m8Tuple, m8Item1.ContainingSymbol); Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item1.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m8Tuple, m8Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m8Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m8Item1.GetAttributes().IsEmpty); Assert.Null(m8Item1.GetUseSiteDiagnostic()); Assert.False(m8Item1.Locations.IsEmpty); Assert.Equal("Item1", m8Item1.Name); Assert.Equal("Item1", m8Item1.TupleUnderlyingField.Name); Assert.NotEqual(m8Item1.Locations.Single(), m8Item1.TupleUnderlyingField.Locations.Single()); Assert.False(m8Item1.IsImplicitlyDeclared); Assert.Null(m8Item1.TypeLayoutOffset); var m8TupleRestTuple = ((FieldSymbol)m8Tuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m8TupleRestTuple); AssertTestDisplayString(m8TupleRestTuple.GetMembers(), "System.Int32 System.ValueTuple<System.Int32>.Item1", "System.ValueTuple<System.Int32>..ctor()", "System.ValueTuple<System.Int32>..ctor(System.Int32 item1)", "System.Boolean System.ValueTuple<System.Int32>.Equals(System.Object obj)", "System.Boolean System.ValueTuple<System.Int32>.Equals(System.ValueTuple<System.Int32> other)", "System.Boolean System.ValueTuple<System.Int32>.System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32>.System.IComparable.CompareTo(System.Object other)", "System.Int32 System.ValueTuple<System.Int32>.CompareTo(System.ValueTuple<System.Int32> other)", "System.Int32 System.ValueTuple<System.Int32>.System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 System.ValueTuple<System.Int32>.GetHashCode()", "System.Int32 System.ValueTuple<System.Int32>.System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32>.System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String System.ValueTuple<System.Int32>.ToString()", "System.String System.ValueTuple<System.Int32>.System.ITupleInternal.ToStringEnd()", "System.Int32 System.ValueTuple<System.Int32>.System.ITupleInternal.Size.get", "System.Int32 System.ValueTuple<System.Int32>.System.ITupleInternal.Size { get; }"); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void DefaultAndFriendlyElementNames_09() { var source = @" using System; class C { static void Main() { var v1 = (1, 11); System.Console.WriteLine(v1.Item1); System.Console.WriteLine(v1.Item2); var v2 =(a2: 2, b2: 22); System.Console.WriteLine(v2.Item1); System.Console.WriteLine(v2.Item2); System.Console.WriteLine(v2.a2); System.Console.WriteLine(v2.b2); var v6 = (item1: 6, item2: 66); System.Console.WriteLine(v6.Item1); System.Console.WriteLine(v6.Item2); System.Console.WriteLine(v6.item1); System.Console.WriteLine(v6.item2); System.Console.WriteLine(v1.ToString()); System.Console.WriteLine(v2.ToString()); System.Console.WriteLine(v6.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 11 2 22 2 22 6 66 6 66 {1, 11} {2, 22} {6, 66} "); var c = (CSharpCompilation)comp.Compilation; var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); var m1Tuple = model.LookupSymbols(node.SpanStart, name: "v1").OfType<ILocalSymbol>().Single().Type.GetSymbol<NamedTypeSymbol>(); var m2Tuple = model.LookupSymbols(node.SpanStart, name: "v2").OfType<ILocalSymbol>().Single().Type.GetSymbol<NamedTypeSymbol>(); var m6Tuple = model.LookupSymbols(node.SpanStart, name: "v6").OfType<ILocalSymbol>().Single().Type.GetSymbol<NamedTypeSymbol>(); AssertEx.Equal(new[] { "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "System.String (System.Int32, System.Int32).ToString()" }, m1Tuple.GetMembersUnordered().ToTestDisplayStrings().ToImmutableArray().Sort()); AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32, System.Int32).ToString()", "(System.Int32, System.Int32)..ctor()"); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a2, System.Int32 b2).Item1", "System.Int32 (System.Int32 a2, System.Int32 b2).a2", "System.Int32 (System.Int32 a2, System.Int32 b2).Item2", "System.Int32 (System.Int32 a2, System.Int32 b2).b2", "(System.Int32 a2, System.Int32 b2)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32 a2, System.Int32 b2).ToString()", "(System.Int32 a2, System.Int32 b2)..ctor()"); AssertTestDisplayString(m6Tuple.GetMembers(), "System.Int32 (System.Int32 item1, System.Int32 item2).Item1", "System.Int32 (System.Int32 item1, System.Int32 item2).item1", "System.Int32 (System.Int32 item1, System.Int32 item2).Item2", "System.Int32 (System.Int32 item1, System.Int32 item2).item2", "(System.Int32 item1, System.Int32 item2)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32 item1, System.Int32 item2).ToString()", "(System.Int32 item1, System.Int32 item2)..ctor()"); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("ValueTuple", m1Tuple.Name); Assert.Equal("System", m1Tuple.ContainingNamespace.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind); Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind); Assert.False(m1Tuple.IsImplicitlyDeclared); Assert.True(m1Tuple.IsTupleType); Assert.Same(m1Tuple, m1Tuple); Assert.Equal("(T1, T2)", m1Tuple.ConstructedFrom.ToTestDisplayString()); Assert.Equal("(T1, T2)", m1Tuple.OriginalDefinition.ToTestDisplayString()); Assert.NotSame(m1Tuple, m1Tuple.ConstructedFrom); Assert.NotSame(m1Tuple, m1Tuple.OriginalDefinition); AssertTupleTypeEquality(m1Tuple); Assert.Null(m1Tuple.GetUseSiteDiagnostic()); Assert.Null(m1Tuple.EnumUnderlyingType); Assert.Equal(new string[] { "Item1", "Item2", ".ctor", "ToString" }, m1Tuple.MemberNames.ToArray()); Assert.Equal(new string[] { "Item1", "a2", "Item2", "b2", ".ctor", "ToString" }, m2Tuple.MemberNames.ToArray()); Assert.Equal(2, m1Tuple.Arity); Assert.Equal(new[] { "T1", "T2" }, m1Tuple.TypeParameters.ToTestDisplayStrings()); Assert.Equal("System.ValueType", m1Tuple.BaseType().ToTestDisplayString()); Assert.Null(m1Tuple.ComImportCoClass); Assert.True(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Assert.False(m1Tuple.IsComImport); Assert.Equal(new[] { "System.Int32", "System.Int32" }, m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.ToTestDisplayStrings()); Assert.True(m1Tuple.GetAttributes().IsEmpty); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).a2", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembers().IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty); Assert.True(m1Tuple.Interfaces().IsEmpty); Assert.Equal(m1Tuple.GetEarlyAttributeDecodingMembers().Select(m => m.Name).ToArray(), m1Tuple.GetEarlyAttributeDecodingMembers().Select(m => m.Name).ToArray()); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Tuple.GetEarlyAttributeDecodingMembers("Item1").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty); Assert.Equal(1, m1Tuple.Locations.Length); Assert.Equal("(1, 11)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("(a2: 2, b2: 22)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.True(m1Tuple.TupleUnderlyingType.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("public struct ValueTuple<T1, T2>", m1Tuple.OriginalDefinition.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 32)); AssertTupleTypeEquality(m2Tuple); AssertTupleTypeEquality(m6Tuple); Assert.False(m1Tuple.Equals(m2Tuple)); Assert.False(m1Tuple.Equals(m6Tuple)); Assert.False(m6Tuple.Equals(m2Tuple)); AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m6Tuple); AssertTupleTypeMembersEquality(m2Tuple, m6Tuple); var m1Item1 = (FieldSymbol)m1Tuple.GetMembers()[0]; var m2Item1 = (FieldSymbol)m2Tuple.GetMembers()[0]; var m2a2 = (FieldSymbol)m2Tuple.GetMembers()[1]; AssertNonvirtualTupleElementField(m1Item1); AssertNonvirtualTupleElementField(m2Item1); AssertVirtualTupleElementField(m2a2); Assert.Equal("TupleElementFieldSymbol", m1Item1.GetType().Name); Assert.NotSame(m1Item1, m1Item1.OriginalDefinition); Assert.True(m1Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m1Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.Equal("T1 (T1, T2).Item1", m1Item1.OriginalDefinition.ToTestDisplayString()); Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(m1Item1.OriginalDefinition); Assert.True(m1Item1.Equals(m1Item1)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m1Item1.AssociatedSymbol); Assert.Same(m1Tuple, m1Item1.ContainingSymbol); Assert.Same(m1Tuple, m1Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m1Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1Item1.GetAttributes().IsEmpty); Assert.Null(m1Item1.GetUseSiteDiagnostic()); Assert.False(m1Item1.Locations.IsEmpty); Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m1Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.True(m1Item1.IsImplicitlyDeclared); Assert.Null(m1Item1.TypeLayoutOffset); Assert.Equal("TupleElementFieldSymbol", m2Item1.GetType().Name); Assert.NotSame(m2Item1, m2Item1.OriginalDefinition); Assert.True(m2Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m2Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.Equal("T1 (T1, T2).Item1", m2Item1.OriginalDefinition.ToTestDisplayString()); Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(m2Item1.OriginalDefinition); Assert.True(m2Item1.Equals(m2Item1)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2Item1.AssociatedSymbol); Assert.Same(m2Tuple, m2Item1.ContainingSymbol); Assert.Same(m2Tuple, m2Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m2Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2Item1.GetAttributes().IsEmpty); Assert.Null(m2Item1.GetUseSiteDiagnostic()); Assert.False(m2Item1.Locations.IsEmpty); Assert.True(m2Item1.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m2Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()); Assert.Equal("SourceFile([891..896))", m2Item1.TupleUnderlyingField.Locations.Single().ToString()); Assert.Equal("SourceFile([196..198))", m2Item1.Locations.Single().ToString()); Assert.True(m2Item1.IsImplicitlyDeclared); Assert.Null(m2Item1.TypeLayoutOffset); Assert.Equal("TupleVirtualElementFieldSymbol", m2a2.GetType().Name); Assert.Same(m2a2, m2a2.OriginalDefinition); Assert.True(m2a2.Equals(m2a2)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2a2.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2a2.AssociatedSymbol); Assert.Same(m2Tuple, m2a2.ContainingSymbol); Assert.Same(m2Tuple, m2a2.TupleUnderlyingField.ContainingSymbol); Assert.True(m2a2.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2a2.GetAttributes().IsEmpty); Assert.Null(m2a2.GetUseSiteDiagnostic()); Assert.False(m2a2.Locations.IsEmpty); Assert.Equal("a2", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m2a2.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.False(m2a2.IsImplicitlyDeclared); Assert.Null(m2a2.TypeLayoutOffset); var m1ToString = m1Tuple.GetMember<MethodSymbol>("ToString"); Assert.NotSame(m1ToString, m1ToString.OriginalDefinition); Assert.Same(m1ToString, m1ToString.ConstructedFrom); Assert.Equal("System.String (T1, T2).ToString()", m1ToString.OriginalDefinition.ToTestDisplayString()); Assert.Equal("System.String (System.Int32, System.Int32).ToString()", m1ToString.ConstructedFrom.ToTestDisplayString()); Assert.Same(m1Tuple, m1ToString.ContainingSymbol); Assert.Null(m1ToString.AssociatedSymbol); Assert.False(m1ToString.IsExplicitInterfaceImplementation); Assert.True(m1ToString.ExplicitInterfaceImplementations.IsEmpty); Assert.False(m1ToString.ReturnsVoid); Assert.True(m1ToString.TypeArgumentsWithAnnotations.IsEmpty); Assert.True(m1ToString.TypeParameters.IsEmpty); Assert.True(m1ToString.GetAttributes().IsEmpty); Assert.Null(m1ToString.GetUseSiteDiagnostic()); Assert.Equal("System.String System.ValueType.ToString()", m1ToString.OverriddenMethod.ToTestDisplayString()); Assert.False(m1ToString.Locations.IsEmpty); Assert.Equal("public override string ToString()", m1ToString.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 33)); } [Fact] public void CustomValueTupleWithStrangeThings_01() { var source = @" class C { static void Main() { var x1 = M9().Item1; var x2 = M9().Item2; var y = (int, int).C9; System.ValueTuple<int, int>.C9 z = null; System.Console.WriteLine(z); } static (int, int) M9() { return (901, 902); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public class C9{} } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (10,18): error CS1525: Invalid expression term 'int' // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(10, 18), // (10,23): error CS1525: Invalid expression term 'int' // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(10, 23) ); var c = comp.GetTypeByMetadataName("C"); var m9Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M9").ReturnType; AssertTupleTypeEquality(m9Tuple); AssertTestDisplayString(m9Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32, System.Int32).ToString()", "(System.Int32, System.Int32)..ctor()"); Assert.True(m9Tuple.Equals(m9Tuple.TupleUnderlyingType, TypeCompareKind.ConsiderEverything)); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembers().Single().ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembers("C9").Single().ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembers("C9", 0).Single().ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembersUnordered().Single().ToTestDisplayString()); } [Fact] public void CustomValueTupleWithStrangeThings_02() { var source = @" partial class C { static void Main() { } public static (int, int) M10() { return (101, 102); } static (int, int, int, int, int, int, int, int, int) M101() { return (1, 1, 1, 1, 1, 1, 1, 1, 1); } I1 Test01() { return M10(); } static (int a, int b) M102() { return (1, 1); } void Test02() { System.Console.WriteLine(M10().Item1); System.Console.WriteLine(M10().Item20); System.Console.WriteLine(M102().a); } static (int a, int b, int c, int d, int e, int f, int g, int h, int Item2) M103() { return (1, 1, 1, 1, 1, 1, 1, 1, 1); } } interface I1 { void M1(); int P1 { get; set; } event System.Action E1; } namespace System { [Obsolete] public struct ValueTuple<T1, T2> : I1 { [Obsolete] public T1 Item1; [System.Runtime.InteropServices.FieldOffsetAttribute(20)] public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.Item20 = 0; this.Item21 = 0; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public class C9{} void I1.M1(){} [Obsolete] public byte Item20; [System.Runtime.InteropServices.FieldOffsetAttribute(21)] public byte Item21; [Obsolete] public void M2() {} int I1.P1 { get; set; } [Obsolete] public int P2 { get; set; } event System.Action I1.E1 {add{} remove{}} [Obsolete] public event System.Action E2; } } partial class C { static void Test03() { M10().M2(); var x = M10().P2; M10().E2 += null; } } " + trivialRemainingTuples + tupleattributes_cs; var comp = CreateCompilation(source); var c = comp.GetTypeByMetadataName("C"); // Note: we don't report on Item2 because it is considered implicitly declared (see `ClsComplianceChecker.DoNotVisit`) comp.VerifyDiagnostics( // (8,19): warning CS0612: '(T1, T2)' is obsolete // public static (int, int) M10() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(T1, T2)").WithLocation(8, 19), // (8,19): warning CS0612: '(int, int)' is obsolete // public static (int, int) M10() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(int, int)").WithLocation(8, 19), // (13,12): warning CS0612: '(T1, T2)' is obsolete // static (int, int, int, int, int, int, int, int, int) M101() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int, int, int, int, int, int, int, int)").WithArguments("(T1, T2)").WithLocation(13, 12), // (23,12): warning CS0612: '(T1, T2)' is obsolete // static (int a, int b) M102() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int a, int b)").WithArguments("(T1, T2)").WithLocation(23, 12), // (23,12): warning CS0612: '(int a, int b)' is obsolete // static (int a, int b) M102() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int a, int b)").WithArguments("(int a, int b)").WithLocation(23, 12), // (35,73): error CS8125: Tuple element name 'Item2' is only allowed at position 2. // static (int a, int b, int c, int d, int e, int f, int g, int h, int Item2) M103() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(35, 73), // (35,12): warning CS0612: '(T1, T2)' is obsolete // static (int a, int b, int c, int d, int e, int f, int g, int h, int Item2) M103() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int a, int b, int c, int d, int e, int f, int g, int h, int Item2)").WithArguments("(T1, T2)").WithLocation(35, 12), // (55,10): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [System.Runtime.InteropServices.FieldOffsetAttribute(20)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffsetAttribute").WithLocation(55, 10), // (78,10): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [System.Runtime.InteropServices.FieldOffsetAttribute(21)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffsetAttribute").WithLocation(78, 10), // (10,16): warning CS0612: '(T1, T2)' is obsolete // return (101, 102); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(101, 102)").WithArguments("(T1, T2)").WithLocation(10, 16), // (15,16): warning CS0612: '(T1, T2)' is obsolete // return (1, 1, 1, 1, 1, 1, 1, 1, 1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 1, 1, 1, 1, 1, 1, 1, 1)").WithArguments("(T1, T2)").WithLocation(15, 16), // (25,16): warning CS0612: '(T1, T2)' is obsolete // return (1, 1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 1)").WithArguments("(T1, T2)").WithLocation(25, 16), // (58,16): error CS0843: Auto-implemented property '(T1, T2).I1.P1' must be fully assigned before control is returned to the caller. // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "ValueTuple").WithArguments("(T1, T2).I1.P1").WithLocation(58, 16), // (58,16): error CS0843: Auto-implemented property '(T1, T2).P2' must be fully assigned before control is returned to the caller. // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "ValueTuple").WithArguments("(T1, T2).P2").WithLocation(58, 16), // (58,16): error CS0171: Field '(T1, T2).E2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).E2").WithLocation(58, 16), // (30,34): warning CS0612: '(int, int).Item1' is obsolete // System.Console.WriteLine(M10().Item1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().Item1").WithArguments("(int, int).Item1").WithLocation(30, 34), // (31,34): warning CS0612: '(int, int).Item20' is obsolete // System.Console.WriteLine(M10().Item20); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().Item20").WithArguments("(int, int).Item20").WithLocation(31, 34), // (32,34): warning CS0612: '(int a, int b).a' is obsolete // System.Console.WriteLine(M102().a); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M102().a").WithArguments("(int a, int b).a").WithLocation(32, 34), // (37,16): warning CS0612: '(T1, T2)' is obsolete // return (1, 1, 1, 1, 1, 1, 1, 1, 1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 1, 1, 1, 1, 1, 1, 1, 1)").WithArguments("(T1, T2)").WithLocation(37, 16), // (98,9): warning CS0612: '(int, int).M2()' is obsolete // M10().M2(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().M2()").WithArguments("(int, int).M2()").WithLocation(98, 9), // (99,17): warning CS0612: '(int, int).P2' is obsolete // var x = M10().P2; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().P2").WithArguments("(int, int).P2").WithLocation(99, 17), // (100,9): warning CS0612: '(int, int).E2' is obsolete // M10().E2 += null; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().E2").WithArguments("(int, int).E2").WithLocation(100, 9), // (90,36): warning CS0067: The event '(T1, T2).E2' is never used // public event System.Action E2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("(T1, T2).E2").WithLocation(90, 36) ); var m10Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M10").ReturnType; AssertTupleTypeEquality(m10Tuple); Assert.Equal("System.ObsoleteAttribute", m10Tuple.GetAttributes().Single().ToString()); Assert.Equal("I1", m10Tuple.Interfaces().Single().ToTestDisplayString()); var m102Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M102").ReturnType; AssertTupleTypeEquality(m102Tuple); var m10Item1 = (FieldSymbol)m10Tuple.GetMembers("Item1").Single(); var m102Item20 = (FieldSymbol)m102Tuple.GetMembers("Item20").Single(); var m102a = (FieldSymbol)m102Tuple.GetMembers("a").Single(); AssertNonvirtualTupleElementField(m10Item1); AssertTupleNonElementField(m102Item20); AssertVirtualTupleElementField(m102a); Assert.Equal("System.ObsoleteAttribute", m10Item1.GetAttributes().Single().ToString()); Assert.Equal("System.ObsoleteAttribute", m102Item20.GetAttributes().Single().ToString()); Assert.Equal("System.ObsoleteAttribute", m102a.GetAttributes().Single().ToString()); var m10Item2 = (FieldSymbol)m10Tuple.GetMembers("Item2").Single(); var m102Item21 = (FieldSymbol)m102Tuple.GetMembers("Item21").Single(); var m102Item2 = (FieldSymbol)m102Tuple.GetMembers("Item2").Single(); var m102b = (FieldSymbol)m102Tuple.GetMembers("b").Single(); AssertNonvirtualTupleElementField(m10Item2); AssertNonvirtualTupleElementField(m102Item2); AssertTupleNonElementField(m102Item21); AssertVirtualTupleElementField(m102b); Assert.Equal(20, m10Item2.TypeLayoutOffset); Assert.Equal(20, m102Item2.TypeLayoutOffset); Assert.Equal(21, m102Item21.TypeLayoutOffset); Assert.Null(m102b.TypeLayoutOffset); Assert.Equal(20, m102b.TupleUnderlyingField.TypeLayoutOffset); var m103Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M103").ReturnType; AssertTupleTypeEquality(m103Tuple); var m103Item2 = (FieldSymbol)m103Tuple.GetMembers("Item2").Last(); var m103Item9 = (FieldSymbol)m103Tuple.GetMembers("Item9").Single(); AssertVirtualTupleElementField(m103Item2); AssertVirtualTupleElementField(m103Item9); Assert.Null(m103Item2.TypeLayoutOffset); Assert.Equal(20, m103Item2.TupleUnderlyingField.TypeLayoutOffset); Assert.Null(m103Item9.TypeLayoutOffset); Assert.Equal(20, m103Item9.TupleUnderlyingField.TypeLayoutOffset); var m10I1M1 = m10Tuple.GetMember<MethodSymbol>("I1.M1"); Assert.True(m10I1M1.IsExplicitInterfaceImplementation); Assert.Equal("void I1.M1()", m10I1M1.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); var m10M2 = m10Tuple.GetMember<MethodSymbol>("M2"); Assert.Equal("System.ObsoleteAttribute", m10M2.GetAttributes().Single().ToString()); var m10I1P1 = m10Tuple.GetMember<PropertySymbol>("I1.P1"); Assert.True(m10I1P1.IsExplicitInterfaceImplementation); Assert.Equal("System.Int32 I1.P1 { get; set; }", m10I1P1.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1P1.GetMethod.IsExplicitInterfaceImplementation); Assert.Equal("System.Int32 I1.P1.get", m10I1P1.GetMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1P1.SetMethod.IsExplicitInterfaceImplementation); Assert.Equal("void I1.P1.set", m10I1P1.SetMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); var m10P2 = m10Tuple.GetMember<PropertySymbol>("P2"); Assert.Equal("System.ObsoleteAttribute", m10P2.GetAttributes().Single().ToString()); var m10I1E1 = m10Tuple.GetMember<EventSymbol>("I1.E1"); Assert.True(m10I1E1.IsExplicitInterfaceImplementation); Assert.Equal("event System.Action I1.E1", m10I1E1.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1E1.AddMethod.IsExplicitInterfaceImplementation); Assert.Equal("void I1.E1.add", m10I1E1.AddMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1E1.RemoveMethod.IsExplicitInterfaceImplementation); Assert.Equal("void I1.E1.remove", m10I1E1.RemoveMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); var m10E2 = m10Tuple.GetMember<EventSymbol>("E2"); Assert.Equal("System.ObsoleteAttribute", m10E2.GetAttributes().Single().ToString()); } private void AssertTupleNonElementField(FieldSymbol sym) { Assert.True(sym.ContainingType.IsTupleType); Assert.False(sym.IsVirtualTupleField); //it is not an element so index must be negative Assert.True(sym.TupleElementIndex < 0); } private void AssertVirtualTupleElementField(FieldSymbol sym) { Assert.True(sym.ContainingType.IsTupleType); Assert.True(sym.IsVirtualTupleField); //it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0); } private void AssertNonvirtualTupleElementField(FieldSymbol sym) { Assert.True(sym.ContainingType.IsTupleType); Assert.False(sym.IsVirtualTupleField); //it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0); //if it was 8th or after, it would be virtual Assert.True(sym.TupleElementIndex < NamedTypeSymbol.ValueTupleRestPosition - 1); } [Fact] public void CustomValueTupleWithGenericMethod() { var source = @" class C { static void Main() { M9().Test(""Yes""); } static (int, int) M9() { return (901, 902); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public void Test<U>(U val) { System.Console.WriteLine(typeof(U)); System.Console.WriteLine(val); } } } " + tupleattributes_cs; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.String Yes"); var c = comp.GetTypeByMetadataName("C"); var m9Tuple = c.GetMember<MethodSymbol>("M9").ReturnType; AssertTupleTypeEquality(m9Tuple); var m9Test = m9Tuple.GetMember<MethodSymbol>("Test"); Assert.NotSame(m9Test, m9Test.OriginalDefinition); Assert.Same(m9Test, m9Test.ConstructedFrom); Assert.Equal("void (T1, T2).Test<U>(U val)", m9Test.OriginalDefinition.ToTestDisplayString()); Assert.Equal("void (System.Int32, System.Int32).Test<U>(U val)", m9Test.ConstructedFrom.ToTestDisplayString()); Assert.NotSame(m9Test.TypeParameters.Single(), m9Test.TypeParameters.Single().OriginalDefinition); Assert.Same(m9Test, m9Test.TypeParameters.Single().ContainingSymbol); Assert.Same(m9Test, m9Test.Parameters.Single().ContainingSymbol); Assert.Equal(0, m9Test.TypeParameters.Single().Ordinal); Assert.Equal(1, m9Test.Arity); } [ConditionalFact(typeof(DesktopOnly))] public void CreationOfTupleSymbols_01() { var source = @" class C { static void Main() { } static (int, int) M1() { return (101, 102); } static (int, int, int, int, int, int, int, int, int) M2() { return (1, 1, 1, 1, 1, 1, 1, 1, 1); } static (int, int, int) M3() { return (101, 102, 103); } } namespace System { public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2, T3 item3) => throw null; } } "; var comp = CreateCompilation(source); var c = comp.GetTypeByMetadataName("C"); comp.VerifyDiagnostics(); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; { var t1 = NamedTypeSymbol.CreateTuple(m1Tuple); var t2 = NamedTypeSymbol.CreateTuple(m1Tuple); Assert.True(t1.Equals(t2)); AssertTupleTypeMembersEquality(t1, t2); var t3 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")); var t4 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")); var t5 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("b", "a")); Assert.False(t1.Equals(t3)); Assert.True(t1.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t3); Assert.True(t3.Equals(t4)); AssertTupleTypeMembersEquality(t3, t4); Assert.False(t5.Equals(t3)); Assert.True(t5.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t5, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t5, t3); var t6 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item1", "Item2")); var t7 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item1", "Item2")); Assert.True(t6.Equals(t7)); AssertTupleTypeMembersEquality(t6, t7); Assert.False(t1.Equals(t6)); Assert.True(t1.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t6.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t6); var t8 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item2", "Item1")); Assert.False(t1.Equals(t8)); Assert.True(t1.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t8); Assert.False(t6.Equals(t8)); Assert.True(t6.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t6, t8); } var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; { var t1 = NamedTypeSymbol.CreateTuple(m2Tuple, default(ImmutableArray<string>)); var t2 = NamedTypeSymbol.CreateTuple(m2Tuple, default(ImmutableArray<string>)); Assert.True(t1.Equals(t2)); AssertTupleTypeMembersEquality(t1, t2); var t3 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "h", "i")); var t4 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "h", "i")); var t5 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "i", "h")); Assert.False(t1.Equals(t3)); Assert.True(t1.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t3); Assert.True(t3.Equals(t4)); AssertTupleTypeMembersEquality(t3, t4); Assert.False(t5.Equals(t3)); Assert.True(t5.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t5, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t5, t3); var t6 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); var t7 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); Assert.True(t6.Equals(t7)); AssertTupleTypeMembersEquality(t6, t7); Assert.False(t1.Equals(t6)); Assert.True(t1.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t6.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t6); var t8 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item9", "Item8")); Assert.False(t1.Equals(t8)); Assert.True(t1.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t8); Assert.False(t6.Equals(t8)); Assert.True(t6.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t6, t8); var t9 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "Item1", "Item2")); var t10 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "Item1", "Item2")); Assert.True(t9.Equals(t10)); AssertTupleTypeMembersEquality(t9, t10); var t11 = NamedTypeSymbol.CreateTuple(m2Tuple.OriginalDefinition.Construct( m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.RemoveAt(7). Add(TypeWithAnnotations.Create(NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")))) )); Assert.False(t1.Equals(t11)); AssertTupleTypeMembersEquality(t1, t11); Assert.True(t1.Equals(t11, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t11.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t1.Equals(t11)); Assert.True(t1.Equals(t11, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t11.Equals(t1)); Assert.True(t11.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTestDisplayString(t11.GetMembers(), "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item1", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item2", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item3", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item4", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item5", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item6", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item7", "(System.Int32 a, System.Int32 b) System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Rest", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item8", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item9", "System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>..ctor()", "System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>..ctor" + "(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, " + "(System.Int32 a, System.Int32 b) rest)", "System.Boolean System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Equals(System.Object obj)", "System.Boolean System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".Equals(System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)> other)", "System.Boolean System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.IComparable.CompareTo(System.Object other)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".CompareTo(System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)> other)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".GetHashCode()", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.ToString()", "System.String System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.ToStringEnd()", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.Size.get", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.Size { get; }" ); var t12 = NamedTypeSymbol.CreateTuple(m2Tuple.OriginalDefinition.Construct( m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.RemoveAt(7). Add(TypeWithAnnotations.Create(NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item1", "Item2")))) ), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); Assert.False(t1.Equals(t12)); AssertTupleTypeMembersEquality(t1, t12); Assert.True(t1.Equals(t12, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t12.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t1.TupleUnderlyingType.Equals(t12.TupleUnderlyingType)); Assert.True(t1.TupleUnderlyingType.Equals(t12.TupleUnderlyingType, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t12.TupleUnderlyingType.Equals(t1.TupleUnderlyingType)); Assert.True(t12.TupleUnderlyingType.Equals(t1.TupleUnderlyingType, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t1.Equals(t12)); Assert.True(t1.Equals(t12, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t12.Equals(t1)); Assert.True(t12.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTestDisplayString(t12.GetMembers(), "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item1", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item2", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item3", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item4", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item5", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item6", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item7", "(System.Int32 Item1, System.Int32 Item2) (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Rest", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item8", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item9", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)..ctor()", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + "..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32 Item1, System.Int32 Item2) rest)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Equals(System.Object obj)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".GetHashCode()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).ToString()", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.Size.get", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.Size { get; }" ); var t13 = NamedTypeSymbol.CreateTuple(m2Tuple.OriginalDefinition.Construct( m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.RemoveAt(7). Add(TypeWithAnnotations.Create(NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")))) ), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "item9")); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>", t13.ToTestDisplayString()); } var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; { var t1 = NamedTypeSymbol.CreateTuple(m3Tuple); var t2 = NamedTypeSymbol.CreateTuple(m3Tuple); Assert.True(t1.Equals(t2)); AssertTupleTypeMembersEquality(t1, t2); var t3 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("a", "b", "c")); var t4 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("a", "b", "c")); var t5 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("c", "b", "a")); Assert.False(t1.Equals(t3)); Assert.True(t1.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t3); Assert.True(t3.Equals(t4)); AssertTupleTypeMembersEquality(t3, t4); Assert.False(t5.Equals(t3)); Assert.True(t5.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t5, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t5, t3); var t6 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("Item1", "Item2", "Item3")); var t7 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("Item1", "Item2", "Item3")); Assert.True(t6.Equals(t7)); AssertTupleTypeMembersEquality(t6, t7); Assert.False(t1.Equals(t6)); Assert.True(t1.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t6.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t6); var t8 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("Item2", "Item3", "Item1")); Assert.False(t1.Equals(t8)); Assert.True(t1.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t8); Assert.False(t6.Equals(t8)); Assert.True(t6.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t6, t8); } } private static void AssertTestDisplayString(ImmutableArray<Symbol> symbols, params string[] baseLine) { AssertEx.Equal(baseLine, symbols.Select(s => s.ToTestDisplayString())); } [Fact] public void UnifyUnderlyingWithTuple_01() { var source1 = @" class C { static void Main() { var v1 = Test.M1(); System.Console.WriteLine(v1.Item8); System.Console.WriteLine(v1.Item9); } } "; var source2 = @" using System; public class Test { public static ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>> M1() { return (1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; var comp1 = CreateCompilationWithMscorlib40(source2 + source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); UnifyUnderlyingWithTuple_01_AssertCompilation(comp1); var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseDll); var comp2CompilationRef = comp2.ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib45(source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, comp2CompilationRef }, options: TestOptions.ReleaseExe); Assert.NotSame(comp2.Assembly, (AssemblySymbol)comp3.GetAssemblyOrModuleSymbol(comp2CompilationRef)); // We are interested in retargeting scenario UnifyUnderlyingWithTuple_01_AssertCompilation(comp3); var comp4 = CreateCompilationWithMscorlib40(source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, comp2.EmitToImageReference() }, options: TestOptions.ReleaseExe); UnifyUnderlyingWithTuple_01_AssertCompilation(comp4); } private void UnifyUnderlyingWithTuple_01_AssertCompilation(CSharpCompilation comp) { CompileAndVerify(comp, expectedOutput: @"8 9 "); var test = comp.GetTypeByMetadataName("Test"); var m1Tuple = (NamedTypeSymbol)test.GetMember<MethodSymbol>("M1").ReturnType; Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); } [Fact] public void UnifyUnderlyingWithTuple_02() { var source = @" using System; class C { static void Main() { System.Console.WriteLine(nameof(ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>>)); System.Console.WriteLine(typeof(ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>>)); System.Console.WriteLine(typeof((int, int, int, int, int, int, int, int, int))); System.Console.WriteLine(typeof((int a, int b, int c, int d, int e, int f, int g, int h, int i))); System.Console.WriteLine(typeof(ValueTuple<,>)); System.Console.WriteLine(typeof(ValueTuple<,,,,,,,>)); } } "; var comp = CompileAndVerify(source, expectedOutput: @"ValueTuple System.ValueTuple`8[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.ValueTuple`2[System.Int32,System.Int32]] System.ValueTuple`8[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.ValueTuple`2[System.Int32,System.Int32]] System.ValueTuple`8[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.ValueTuple`2[System.Int32,System.Int32]] System.ValueTuple`2[T1,T2] System.ValueTuple`8[T1,T2,T3,T4,T5,T6,T7,TRest] "); var c = (CSharpCompilation)comp.Compilation; var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); var nameofNode = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "nameof").Single(); var nameofArg = ((InvocationExpressionSyntax)nameofNode.Parent).ArgumentList.Arguments.Single().Expression; var nameofArgSymbolInfo = model.GetSymbolInfo(nameofArg); Assert.True(((ITypeSymbol)nameofArgSymbolInfo.Symbol).IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", nameofArgSymbolInfo.Symbol.ToTestDisplayString()); var typeofNodes = tree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().ToArray(); Assert.Equal(5, typeofNodes.Length); for (int i = 0; i < typeofNodes.Length; i++) { var t = typeofNodes[i]; var typeInfo = model.GetTypeInfo(t.Type); var symbolInfo = model.GetSymbolInfo(t.Type); Assert.Equal(typeInfo.Type, symbolInfo.Symbol); switch (i) { case 0: case 1: Assert.True(typeInfo.Type.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", typeInfo.Type.ToTestDisplayString()); break; case 2: Assert.True(typeInfo.Type.IsTupleType); Assert.Equal("(System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32 h, System.Int32 i)", typeInfo.Type.ToTestDisplayString()); break; default: Assert.False(typeInfo.Type.IsTupleType); Assert.True(((INamedTypeSymbol)typeInfo.Type).IsUnboundGenericType); break; } } } [Fact] public void UnifyUnderlyingWithTuple_03() { var source = @" class C { static void Main() { System.Console.WriteLine(nameof((int, int))); System.Console.WriteLine(nameof((int a, int b))); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,42): error CS1525: Invalid expression term 'int' // System.Console.WriteLine(nameof((int, int))); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 42), // (6,47): error CS1525: Invalid expression term 'int' // System.Console.WriteLine(nameof((int, int))); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 47), // (7,42): error CS8185: A declaration is not allowed in this context. // System.Console.WriteLine(nameof((int a, int b))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int a").WithLocation(7, 42), // (7,49): error CS8185: A declaration is not allowed in this context. // System.Console.WriteLine(nameof((int a, int b))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int b").WithLocation(7, 49), // (7,41): error CS8081: Expression does not have a name. // System.Console.WriteLine(nameof((int a, int b))); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(int a, int b)").WithLocation(7, 41) ); } [Fact] public void UnifyUnderlyingWithTuple_04() { var source1 = @" class C { static void Main() { var v1 = Test.M1(); System.Console.WriteLine(v1.Rest.a); System.Console.WriteLine(v1.Rest.b); } } "; var source2 = @" using System; public class Test { public static ValueTuple<int, int, int, int, int, int, int, (int a, int b)> M1() { return (1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; var comp1 = CreateCompilationWithMscorlib40(source2 + source1, references: s_valueTupleRefs, options: TestOptions.ReleaseExe); unifyUnderlyingWithTuple_04_AssertCompilation(comp1); var comp2 = CreateCompilationWithMscorlib40(source2, references: s_valueTupleRefs, options: TestOptions.ReleaseDll); var comp2CompilationRef = comp2.ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib45(source1, references: (new[] { comp2CompilationRef }).Concat(s_valueTupleRefs), options: TestOptions.ReleaseExe); Assert.NotSame(comp2.Assembly, (AssemblySymbol)comp3.GetAssemblyOrModuleSymbol(comp2CompilationRef)); // We are interested in retargeting scenario unifyUnderlyingWithTuple_04_AssertCompilation(comp3); var comp4 = CreateCompilationWithMscorlib40(source1, references: (new[] { comp2.EmitToImageReference() }).Concat(s_valueTupleRefs), options: TestOptions.ReleaseExe); unifyUnderlyingWithTuple_04_AssertCompilation(comp4); void unifyUnderlyingWithTuple_04_AssertCompilation(CSharpCompilation comp) { CompileAndVerify(comp, expectedOutput: @"8 9 "); var test = comp.GetTypeByMetadataName("Test"); var m1Tuple = (NamedTypeSymbol)test.GetMember<MethodSymbol>("M1").ReturnType; Assert.True(m1Tuple.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>", m1Tuple.ToTestDisplayString()); } } [ConditionalFact(typeof(DesktopOnly))] public void UnifyUnderlyingWithTuple_05() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var v1 = Test<ValueTuple<int, int>>.M1((1, 2, 3, 4, 5, 6, 7, 8, 9)); System.Console.WriteLine(v1.Item8); System.Console.WriteLine(v1.Item9); var v2 = Test<(int a, int b)>.M2((1, 2, 3, 4, 5, 6, 7, 10, 11)); System.Console.WriteLine(v2.Item8); System.Console.WriteLine(v2.Item9); System.Console.WriteLine(v2.Rest.a); System.Console.WriteLine(v2.Rest.b); Test<ValueTuple<int, int>>.F1 = (1, 2, 3, 4, 5, 6, 7, 12, 13); var v3 = Test<ValueTuple<int, int>>.F1; System.Console.WriteLine(v3.Item8); System.Console.WriteLine(v3.Item9); Test<ValueTuple<int, int>>.P1 = (1, 2, 3, 4, 5, 6, 7, 14, 15); var v4 = Test<ValueTuple<int, int>>.P1; System.Console.WriteLine(v4.Item8); System.Console.WriteLine(v4.Item9); var v5 = Test<ValueTuple<int, int>>.M3((1, 2, 3, 4, 5, 6, 7, 16, 17)); System.Console.WriteLine(v5[0].Item8); System.Console.WriteLine(v5[0].Item9); var v6 = Test<ValueTuple<int, int>>.M4((1, 2, 3, 4, 5, 6, 7, 18, 19)); System.Console.WriteLine(v6[0].Item8); System.Console.WriteLine(v6[0].Item9); var v7 = (new Test33()).M5((1, 2, 3, 4, 5, 6, 7, 20, 21)); System.Console.WriteLine(v7.Item8); System.Console.WriteLine(v7.Item9); var v8 = (1, 2).M6((1, 2, 3, 4, 5, 6, 7, 22, 23)); System.Console.WriteLine(v8.Item8); System.Console.WriteLine(v8.Item9); } } class Test<T> where T : struct { public static ValueTuple<int, int, int, int, int, int, int, T> M1(ValueTuple<int, int, int, int, int, int, int, T> val) { return val; } public static ValueTuple<int, int, int, int, int, int, int, T> M2(ValueTuple<int, int, int, int, int, int, int, T> val) { return val; } public static ValueTuple<int, int, int, int, int, int, int, T> F1; public static ValueTuple<int, int, int, int, int, int, int, T> P1 {get; set;} public static ValueTuple<int, int, int, int, int, int, int, T>[] M3(ValueTuple<int, int, int, int, int, int, int, T> val) { return new [] {val}; } public static List<ValueTuple<int, int, int, int, int, int, int, T>> M4(ValueTuple<int, int, int, int, int, int, int, T> val) { return new List<ValueTuple<int, int, int, int, int, int, int, T>>() {val}; } } abstract class Test31<T> { public abstract U M5<U>(U val) where U : T; } abstract class Test32<T> : Test31<ValueTuple<int, int, int, int, int, int, int, T>> where T : struct { } class Test33 : Test32<ValueTuple<int, int>> { public override U M5<U>(U val) { return val; } } static class Test4 { public static ValueTuple<int, int, int, int, int, int, int, T> M6<T>(this T target, ValueTuple<int, int, int, int, int, int, int, T> val) where T : struct { return val; } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true), expectedOutput: @"8 9 10 11 10 11 12 13 14 15 16 17 18 19 20 21 22 23 "); var test = comp.Compilation.GetTypeByMetadataName("Test`1"); var m1Tuple = (INamedTypeSymbol)test.GetMember<IMethodSymbol>("M1").ReturnType; Assert.False(m1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", m1Tuple.ToTestDisplayString()); m1Tuple = (INamedTypeSymbol)test.GetMember<IMethodSymbol>("M1").Parameters[0].Type; Assert.False(m1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", m1Tuple.ToTestDisplayString()); var c = (CSharpCompilation)comp.Compilation; var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); var m1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M1").Single(); var symbolInfo = model.GetSymbolInfo(m1); m1Tuple = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); m1Tuple = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).Parameters[0].Type; Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var m2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M2").Single(); symbolInfo = model.GetSymbolInfo(m2); var m2Tuple = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m2Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>", m2Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.Int32 b)", m2Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var f1Tuple = (INamedTypeSymbol)test.GetMember<IFieldSymbol>("F1").Type; Assert.False(f1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", f1Tuple.ToTestDisplayString()); var f1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "F1").First(); symbolInfo = model.GetSymbolInfo(f1); f1Tuple = (INamedTypeSymbol)((IFieldSymbol)symbolInfo.Symbol).Type; Assert.True(f1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", f1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", f1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var p1Tuple = (INamedTypeSymbol)test.GetMember<IPropertySymbol>("P1").Type; Assert.False(p1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", p1Tuple.ToTestDisplayString()); var p1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "P1").First(); symbolInfo = model.GetSymbolInfo(p1); p1Tuple = (INamedTypeSymbol)((IPropertySymbol)symbolInfo.Symbol).Type; Assert.True(p1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", p1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", p1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var m3TupleArray = (IArrayTypeSymbol)test.GetMember<IMethodSymbol>("M3").ReturnType; Assert.False(m3TupleArray.ElementType.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>[]", m3TupleArray.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IList<System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>>", m3TupleArray.Interfaces[0].ToTestDisplayString()); var m3 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M3").Single(); symbolInfo = model.GetSymbolInfo(m3); m3TupleArray = (IArrayTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m3TupleArray.ElementType.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)[]", m3TupleArray.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IList<(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)>", m3TupleArray.Interfaces[0].ToTestDisplayString()); var m4TupleList = (INamedTypeSymbol)test.GetMember<IMethodSymbol>("M4").ReturnType; Assert.False(m4TupleList.TypeArguments[0].IsTupleType); Assert.Equal("System.Collections.Generic.List<System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>>", m4TupleList.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IList<System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>>", m4TupleList.Interfaces[0].ToTestDisplayString()); var m4 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M4").Single(); symbolInfo = model.GetSymbolInfo(m4); m4TupleList = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m4TupleList.TypeArguments[0].IsTupleType); Assert.Equal("System.Collections.Generic.List<(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)>", m4TupleList.ToTestDisplayString()); var m5 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M5").Single(); symbolInfo = model.GetSymbolInfo(m5); var m5Tuple = ((IMethodSymbol)symbolInfo.Symbol).TypeParameters[0].ConstraintTypes.Single(); Assert.True(m5Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m5Tuple.ToTestDisplayString()); var m6 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M6").Single(); symbolInfo = model.GetSymbolInfo(m6); var m6Method = (IMethodSymbol)symbolInfo.Symbol; Assert.Equal(MethodKind.ReducedExtension, m6Method.MethodKind); var m6Tuple = m6Method.ReturnType; Assert.True(m6Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m6Tuple.ToTestDisplayString()); m6Tuple = m6Method.Parameters.Last().Type; Assert.True(m6Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m6Tuple.ToTestDisplayString()); } [Fact] public void UnifyUnderlyingWithTuple_06() { var source = @" using System; unsafe class C { static void Main() { var x = Test<ValueTuple<int, int>>.E1; var v7 = Test<ValueTuple<int, int>>.M5(); System.Console.WriteLine(v7->Item8); System.Console.WriteLine(v7->Item9); Test1<ValueTuple<int, int>> v1 = null; System.Console.WriteLine(v1.Item8); ITest2<ValueTuple<int, int>> v2 = null; System.Console.WriteLine(v2.Item8); } } unsafe class Test<T> where T : struct { public static event ValueTuple<int, int, int, int, int, int, int, T> E1; public static ValueTuple<int, int, int, int, int, int, int, T>* M5() { return null; } } class Test1<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct { } interface ITest2<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct { } "; var comp = (Compilation)CreateCompilation(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)); comp.VerifyDiagnostics( // (31,18): error CS0509: 'Test1<T>': cannot derive from sealed type 'ValueTuple<int, int, int, int, int, int, int, T>' // class Test1<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "ValueTuple<int, int, int, int, int, int, int, T>").WithArguments("Test1<T>", "System.ValueTuple<int, int, int, int, int, int, int, T>").WithLocation(31, 18), // (35,23): error CS0527: Type 'ValueTuple<int, int, int, int, int, int, int, T>' in interface list is not an interface // interface ITest2<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "ValueTuple<int, int, int, int, int, int, int, T>").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, T>").WithLocation(35, 23), // (25,69): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('ValueTuple<int, int, int, int, int, int, int, T>') // public static ValueTuple<int, int, int, int, int, int, int, T>* M5() Diagnostic(ErrorCode.ERR_ManagedAddr, "M5").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, T>").WithLocation(25, 69), // (23,74): error CS0066: 'Test<T>.E1': event must be of a delegate type // public static event ValueTuple<int, int, int, int, int, int, int, T> E1; Diagnostic(ErrorCode.ERR_EventNotDelegate, "E1").WithArguments("Test<T>.E1").WithLocation(23, 74), // (7,44): error CS0070: The event 'Test<(int, int)>.E1' can only appear on the left hand side of += or -= (except when used from within the type 'Test<(int, int)>') // var x = Test<ValueTuple<int, int>>.E1; Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("Test<(int, int)>.E1", "Test<(int, int)>").WithLocation(7, 44), // (14,37): error CS1061: 'Test1<(int, int)>' does not contain a definition for 'Item8' and no accessible extension method 'Item8' accepting a first argument of type 'Test1<(int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v1.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("Test1<(int, int)>", "Item8").WithLocation(14, 37), // (17,37): error CS1061: 'ITest2<(int, int)>' does not contain a definition for 'Item8' and no accessible extension method 'Item8' accepting a first argument of type 'ITest2<(int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v2.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("ITest2<(int, int)>", "Item8").WithLocation(17, 37) ); var test = comp.GetTypeByMetadataName("Test`1"); var e1Tuple = (INamedTypeSymbol)test.GetMember<IEventSymbol>("E1").Type; Assert.False(e1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", e1Tuple.ToTestDisplayString()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var e1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "E1").Single(); var symbolInfo = model.GetSymbolInfo(e1); e1Tuple = (INamedTypeSymbol)((IEventSymbol)symbolInfo.CandidateSymbols.Single()).Type; Assert.True(e1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", e1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", e1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var m5TuplePointer = (IPointerTypeSymbol)test.GetMember<IMethodSymbol>("M5").ReturnType; Assert.False(m5TuplePointer.PointedAtType.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>*", m5TuplePointer.ToTestDisplayString()); var m5 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M5").Single(); symbolInfo = model.GetSymbolInfo(m5); m5TuplePointer = (IPointerTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m5TuplePointer.PointedAtType.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)*", m5TuplePointer.ToTestDisplayString()); var v1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "v1").Single(); symbolInfo = model.GetSymbolInfo(v1); var v1Type = ((ILocalSymbol)symbolInfo.Symbol).Type; Assert.Equal("Test1<(System.Int32, System.Int32)>", v1Type.ToTestDisplayString()); var v1Tuple = v1Type.BaseType; Assert.False(v1Tuple.IsTupleType); Assert.Equal("System.Object", v1Tuple.ToTestDisplayString()); var v2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "v2").Single(); symbolInfo = model.GetSymbolInfo(v2); var v2Type = ((ILocalSymbol)symbolInfo.Symbol).Type; Assert.Equal("ITest2<(System.Int32, System.Int32)>", v2Type.ToTestDisplayString()); Assert.True(v2Type.Interfaces.IsEmpty); } [Fact] public void UnifyUnderlyingWithTuple_07() { var source1 = @" using System; public class Test<T> { public static ValueTuple<int, int, int, int, int, int, int, T> M1() { throw new NotImplementedException(); } } " + trivialRemainingTuples + tupleattributes_cs; var source2 = @" class C { static void Main() { var v1 = Test<(int, int, int, int, int, int, int, int, int)>.M1(); System.Console.WriteLine(v1.Item8); System.Console.WriteLine(v1.Item9); System.Console.WriteLine(v1.Rest.Item8); System.Console.WriteLine(v1.Rest.Item9); } } " + trivial2uple + trivialRemainingTuples + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40(source1, options: TestOptions.ReleaseDll); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { comp1.ToMetadataReference() }, options: TestOptions.ReleaseExe); comp2.VerifyDiagnostics( // (7,37): error CS1061: 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' does not contain a definition for 'Item8' and no extension method 'Item8' accepting a first argument of type 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v1.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>", "Item8").WithLocation(7, 37), // (8,37): error CS1061: 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' does not contain a definition for 'Item9' and no extension method 'Item9' accepting a first argument of type 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v1.Item9); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item9").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>", "Item9").WithLocation(8, 37) ); } [Fact] public void UnifyUnderlyingWithTuple_08() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string) y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string(ValueTuple<T1, T2> arg) { return arg.ToString(); } public static explicit operator long(ValueTuple<T1, T2> arg) { return ((long)(int)(object)arg.Item1 + (long)(int)(object)arg.Item2); } public static implicit operator ValueTuple<T1, T2>(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return new ValueTuple<T1, T2>(arg.Key, arg.Value); } public static explicit operator ValueTuple<T1, T2>(string arg) { return new ValueTuple<T1, T2>((T1)(object)arg, (T2)(object)arg); } public static ValueTuple<T1, T2> operator +(ValueTuple<T1, T2> arg) { return arg; } public static long operator -(ValueTuple<T1, T2> arg) { return -(long)arg; } public static bool operator !(ValueTuple<T1, T2> arg) { return (long)arg == 0; } public static long operator ~(ValueTuple<T1, T2> arg) { return -(long)arg; } public static ValueTuple<T1, T2> operator ++(ValueTuple<T1, T2> arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1+1), (T2)(object)((int)(object)arg.Item2+1)); } public static ValueTuple<T1, T2> operator --(ValueTuple<T1, T2> arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1 - 1), (T2)(object)((int)(object)arg.Item2 - 1)); } public static bool operator true(ValueTuple<T1, T2> arg) { return (long)arg != 0; } public static bool operator false(ValueTuple<T1, T2> arg) { return (long)arg == 0; } public static long operator + (ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |(ValueTuple<T1, T2> arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib40(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnifyUnderlyingWithTuple_09() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string) y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string((T1, T2) arg) { return arg.ToString(); } public static explicit operator long((T1, T2) arg) { return ((long)(int)(object)arg.Item1 + (long)(int)(object)arg.Item2); } public static implicit operator (T1, T2)(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return (arg.Key, arg.Value); } public static explicit operator (T1, T2)(string arg) { return ((T1)(object)arg, (T2)(object)arg); } public static (T1, T2) operator +((T1, T2) arg) { return arg; } public static long operator -((T1, T2) arg) { return -(long)arg; } public static bool operator !((T1, T2) arg) { return (long)arg == 0; } public static long operator ~((T1, T2) arg) { return -(long)arg; } public static (T1, T2) operator ++((T1, T2) arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1+1), (T2)(object)((int)(object)arg.Item2+1)); } public static (T1, T2) operator --((T1, T2) arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1 - 1), (T2)(object)((int)(object)arg.Item2 - 1)); } public static bool operator true((T1, T2) arg) { return (long)arg != 0; } public static bool operator false((T1, T2) arg) { return (long)arg == 0; } public static long operator + ((T1, T2) arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -((T1, T2) arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *((T1, T2) arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /((T1, T2) arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %((T1, T2) arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &((T1, T2) arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |((T1, T2) arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^((T1, T2) arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<((T1, T2) arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>((T1, T2) arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==((T1, T2) arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=((T1, T2) arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >((T1, T2) arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <((T1, T2) arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=((T1, T2) arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=((T1, T2) arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib40(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] [WorkItem(11530, "https://github.com/dotnet/roslyn/issues/11530")] public void UnifyUnderlyingWithTuple_10() { var source = @" using System.Collections.Generic; class Test { static void Main() { var a = new KeyValuePair<int, long>(1, 2); (int, long) b = a; System.Console.WriteLine(b.Item1); System.Console.WriteLine(b.Item2); b.Item1++; b.Item2++; a = b; System.Console.WriteLine(a.Key); System.Console.WriteLine(a.Value); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static implicit operator KeyValuePair<T1, T2>(ValueTuple<T1, T2> tuple) { T1 k; T2 v; (k, v) = tuple; return new KeyValuePair<T1, T2>(k, v); } public static implicit operator ValueTuple<T1, T2>(KeyValuePair<T1, T2> kvp) { return (kvp.Key, kvp.Value); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, options: TestOptions.ReleaseExe, expectedOutput: @"1 2 2 3"); } [Fact] [WorkItem(11986, "https://github.com/dotnet/roslyn/issues/11986")] public void UnifyUnderlyingWithTuple_11() { var source = @" using System.Collections.Generic; class Test { static void Main() { var a = (1, 2); System.Console.WriteLine((int)a); System.Console.WriteLine((long)a); System.Console.WriteLine((string)a); System.Console.WriteLine((double)a); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static explicit operator int((T1, T2)? source) { return 1; } public static explicit operator long(Nullable<(T1, T2)> source) { return 2; } public static explicit operator string(Nullable<ValueTuple<T1, T2>> source) { return ""3""; } public static explicit operator double(ValueTuple<T1, T2>? source) { return 4; } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, options: TestOptions.ReleaseExe, expectedOutput: @"1 2 3 4"); } [Fact] public void UnifyUnderlyingWithTuple_12() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { (int, int)? x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string)? y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string(ValueTuple<T1, T2>? arg) { return arg.ToString(); } public static explicit operator long(ValueTuple<T1, T2>? arg) { return ((long)(int)(object)arg.Value.Item1 + (long)(int)(object)arg.Value.Item2); } public static implicit operator ValueTuple<T1, T2>?(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return new ValueTuple<T1, T2>(arg.Key, arg.Value); } public static explicit operator ValueTuple<T1, T2>?(string arg) { return new ValueTuple<T1, T2>((T1)(object)arg, (T2)(object)arg); } public static ValueTuple<T1, T2>? operator +(ValueTuple<T1, T2>? arg) { return arg; } public static long operator -(ValueTuple<T1, T2>? arg) { return -(long)arg; } public static bool operator !(ValueTuple<T1, T2>? arg) { return (long)arg == 0; } public static long operator ~(ValueTuple<T1, T2>? arg) { return -(long)arg; } public static ValueTuple<T1, T2>? operator ++(ValueTuple<T1, T2>? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1+1), (T2)(object)((int)(object)arg.Value.Item2+1)); } public static ValueTuple<T1, T2>? operator --(ValueTuple<T1, T2>? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1 - 1), (T2)(object)((int)(object)arg.Value.Item2 - 1)); } public static bool operator true(ValueTuple<T1, T2>? arg) { return (long)arg != 0; } public static bool operator false(ValueTuple<T1, T2>? arg) { return (long)arg == 0; } public static long operator + (ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |(ValueTuple<T1, T2>? arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib46(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnifyUnderlyingWithTuple_13() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { (int, int)? x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string)? y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string((T1, T2)? arg) { return arg.ToString(); } public static explicit operator long((T1, T2)? arg) { return ((long)(int)(object)arg.Value.Item1 + (long)(int)(object)arg.Value.Item2); } public static implicit operator (T1, T2)?(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return (arg.Key, arg.Value); } public static explicit operator (T1, T2)?(string arg) { return ((T1)(object)arg, (T2)(object)arg); } public static (T1, T2)? operator +((T1, T2)? arg) { return arg; } public static long operator -((T1, T2)? arg) { return -(long)arg; } public static bool operator !((T1, T2)? arg) { return (long)arg == 0; } public static long operator ~((T1, T2)? arg) { return -(long)arg; } public static (T1, T2)? operator ++((T1, T2)? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1+1), (T2)(object)((int)(object)arg.Value.Item2+1)); } public static (T1, T2)? operator --((T1, T2)? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1 - 1), (T2)(object)((int)(object)arg.Value.Item2 - 1)); } public static bool operator true((T1, T2)? arg) { return (long)arg != 0; } public static bool operator false((T1, T2)? arg) { return (long)arg == 0; } public static long operator + ((T1, T2)? arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -((T1, T2)? arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *((T1, T2)? arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /((T1, T2)? arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %((T1, T2)? arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &((T1, T2)? arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |((T1, T2)? arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^((T1, T2)? arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<((T1, T2)? arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>((T1, T2)? arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==((T1, T2)? arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=((T1, T2)? arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >((T1, T2)? arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <((T1, T2)? arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=((T1, T2)? arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=((T1, T2)? arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib46(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void ConstructorInvocation_01() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var v1 = new ValueTuple<int, int>(1, 2); System.Console.WriteLine(v1.ToString()); var v2 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>> (10, 20, 30, 40, 50, 60, 70, new ValueTuple<int, int>(80, 90)); System.Console.WriteLine(v2.ToString()); var v3 = new ValueTuple<int, int, int, int, int, int, int, (int, int)> (100, 200, 300, 400, 500, 600, 700, (800, 900)); System.Console.WriteLine(v3.ToString()); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"(1, 2) (10, 20, 30, 40, 50, 60, 70, 80, 90) (100, 200, 300, 400, 500, 600, 700, 800, 900) "); } [Fact] public void PropertiesAsMembers_01() { var source = @" using System; class C { static void Main() { var v1 = M1(); v1.P1 = 33; System.Console.WriteLine(v1.P1); System.Console.WriteLine(v1[-1, -2]); } static (int, int) M1() { return (1, 11); } static (int a2, int b2) M2() { return (2, 22); } static (int, int) M3() { return (6, 66); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.P1 = 0; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public int P1 {get; set;} public int this[int a, int b] { get { return 44; } } } } "; var comp = CompileAndVerify(source, expectedOutput: @"33 44"); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "System.Int32 (System.Int32, System.Int32).<P1>k__BackingField", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32, System.Int32).ToString()", "System.Int32 (System.Int32, System.Int32).P1 { readonly get; set; }", "readonly System.Int32 (System.Int32, System.Int32).P1.get", "void (System.Int32, System.Int32).P1.set", "System.Int32 (System.Int32, System.Int32).this[System.Int32 a, System.Int32 b] { get; }", "System.Int32 (System.Int32, System.Int32).this[System.Int32 a, System.Int32 b].get", "(System.Int32, System.Int32)..ctor()"); AssertTupleTypeEquality(m1Tuple); Assert.Equal(new string[] { "Item1", "Item2", "<P1>k__BackingField", ".ctor", "ToString", "P1", "get_P1", "set_P1", "this[]", "get_Item"}, m1Tuple.MemberNames.ToArray()); Assert.Equal("System.Int32 (System.Int32, System.Int32).P1 { readonly get; set; }", m1Tuple.GetEarlyAttributeDecodingMembers("P1").Single().ToTestDisplayString()); var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m3Tuple); var m1P1 = m1Tuple.GetMember<PropertySymbol>("P1"); var m1P1Get = m1Tuple.GetMember<MethodSymbol>("get_P1"); var m1P1Set = m1Tuple.GetMember<MethodSymbol>("set_P1"); Assert.Equal(SymbolKind.Property, m1P1.Kind); Assert.NotSame(m1P1, m1P1.OriginalDefinition); Assert.True(m1P1.Equals(m1P1)); Assert.Equal("System.Int32 (System.Int32, System.Int32).P1 { readonly get; set; }", m1P1.ToTestDisplayString()); Assert.Same(m1Tuple, m1P1.ContainingSymbol); Assert.True(m1P1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1P1.GetAttributes().IsEmpty); Assert.Null(m1P1.GetUseSiteDiagnostic()); Assert.False(m1P1.IsImplicitlyDeclared); Assert.True(m1P1.Parameters.IsEmpty); Assert.True(m1P1Get.Equals(m1P1.GetMethod, TypeCompareKind.ConsiderEverything)); Assert.True(m1P1Set.Equals(m1P1.SetMethod, TypeCompareKind.ConsiderEverything)); Assert.False(m1P1.IsExplicitInterfaceImplementation); Assert.True(m1P1.ExplicitInterfaceImplementations.IsEmpty); Assert.False(m1P1.IsIndexer); Assert.Null(m1P1.OverriddenProperty); Assert.True(m1P1.Equals(m1P1Get.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1P1Get.IsImplicitlyDeclared); Assert.True(m1P1.Equals(m1P1Set.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1P1Set.IsImplicitlyDeclared); var m1P1BackingField = m1Tuple.GetMember<FieldSymbol>("<P1>k__BackingField"); Assert.True(m1P1.Equals(m1P1BackingField.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1P1BackingField.IsImplicitlyDeclared); Assert.True(m1P1BackingField.TupleUnderlyingField.IsImplicitlyDeclared); var m1this = m1Tuple.GetMember<PropertySymbol>("this[]"); var m1thisGet = m1Tuple.GetMember<MethodSymbol>("get_Item"); Assert.Equal(SymbolKind.Property, m1this.Kind); Assert.NotSame(m1this, m1this.OriginalDefinition); Assert.True(m1this.Equals(m1this)); Assert.Same(m1Tuple, m1this.ContainingSymbol); Assert.True(m1this.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1this.GetAttributes().IsEmpty); Assert.Null(m1this.GetUseSiteDiagnostic()); Assert.False(m1this.IsImplicitlyDeclared); Assert.Equal(2, m1this.Parameters.Length); Assert.True(m1thisGet.Equals(m1this.GetMethod, TypeCompareKind.ConsiderEverything)); Assert.Null(m1this.SetMethod); Assert.False(m1this.IsExplicitInterfaceImplementation); Assert.True(m1this.ExplicitInterfaceImplementations.IsEmpty); Assert.True(m1this.IsIndexer); Assert.Null(m1this.OverriddenProperty); Assert.False(m1this.IsDefinition); Assert.False(m1thisGet.IsImplicitlyDeclared); } private class SyntaxReferenceEqualityComparer : IEqualityComparer<SyntaxReference> { public static readonly SyntaxReferenceEqualityComparer Instance = new SyntaxReferenceEqualityComparer(); private SyntaxReferenceEqualityComparer() { } public bool Equals(SyntaxReference x, SyntaxReference y) { return x.GetSyntax().Equals(y.GetSyntax()); } public int GetHashCode(SyntaxReference obj) { return obj.GetHashCode(); } } [Fact] public void EventsAsMembers_01() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Action<int> d1 = (int i1) => System.Console.WriteLine(i1); v1.Test(v1, d1); System.Action<long> d2 = (long i2) => System.Console.WriteLine(i2); v1.E1 += d1; v1.RaiseE1(); v1.E1 -= d1; v1.RaiseE1(); v1.E2 += d2; v1.RaiseE2(); v1.E2 -= d2; v1.RaiseE2(); } static (int, long) M1() { return (1, 11); } static (int a2, long b2) M2() { return (2, 22); } static (int, long) M3() { return (6, 66); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this._e2 = null; } public event System.Action<T1> E1; private System.Action<T2> _e2; public event System.Action<T2> E2 { add { _e2 += value; } remove { _e2 -= value; } } public void RaiseE1() { System.Console.WriteLine(""-""); if (E1 == null) { System.Console.WriteLine(""null""); } else { E1(Item1); } System.Console.WriteLine(""-""); } public void RaiseE2() { System.Console.WriteLine(""--""); if (_e2 == null) { System.Console.WriteLine(""null""); } else { _e2(Item2); } System.Console.WriteLine(""--""); } public void Test((T1, T2) val, System.Action<T1> d) { val.E1 += d; System.Console.WriteLine(val.E1); val.E1(val.Item1); val.E1 -= d; System.Console.WriteLine(val.E1 == null); } } } " + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"System.Action`1[System.Int32] 1 True - 1 - - null - -- 11 -- -- null --"); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int64).Item1", "System.Int64 (System.Int32, System.Int64).Item2", "System.Action<System.Int64> (System.Int32, System.Int64)._e2", "(System.Int32, System.Int64)..ctor(System.Int32 item1, System.Int64 item2)", "void (System.Int32, System.Int64).E1.add", "void (System.Int32, System.Int64).E1.remove", "event System.Action<System.Int32> (System.Int32, System.Int64).E1", "event System.Action<System.Int64> (System.Int32, System.Int64).E2", "void (System.Int32, System.Int64).E2.add", "void (System.Int32, System.Int64).E2.remove", "void (System.Int32, System.Int64).RaiseE1()", "void (System.Int32, System.Int64).RaiseE2()", "void (System.Int32, System.Int64).Test((System.Int32, System.Int64) val, System.Action<System.Int32> d)", "(System.Int32, System.Int64)..ctor()"); AssertTupleTypeEquality(m1Tuple); Assert.Equal(new string[] { "Item1", "Item2", "_e2", ".ctor", "add_E1", "remove_E1", "E1", "E2", "add_E2", "remove_E2", "RaiseE1", "RaiseE2", "Test" }, m1Tuple.MemberNames.ToArray()); Assert.Equal("event System.Action<System.Int32> (System.Int32, System.Int64).E1", m1Tuple.GetEarlyAttributeDecodingMembers("E1").Single().ToTestDisplayString()); Assert.Equal("event System.Action<System.Int64> (System.Int32, System.Int64).E2", m1Tuple.GetEarlyAttributeDecodingMembers("E2").Single().ToTestDisplayString()); var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m3Tuple); var m1E1 = m1Tuple.GetMember<EventSymbol>("E1"); var m1E1Add = m1Tuple.GetMember<MethodSymbol>("add_E1"); var m1E1Remove = m1Tuple.GetMember<MethodSymbol>("remove_E1"); Assert.Equal(SymbolKind.Event, m1E1.Kind); Assert.NotSame(m1E1, m1E1.OriginalDefinition); Assert.Equal("event System.Action<System.Int32> (System.Int32, System.Int64).E1", m1E1.ToTestDisplayString()); Assert.Equal("event System.Action<T1> (T1, T2).E1", m1E1.OriginalDefinition.ToTestDisplayString()); Assert.True(m1E1.Equals(m1E1)); Assert.Equal("event System.Action<System.Int32> (System.Int32, System.Int64).E1", m1E1.ToTestDisplayString()); Assert.Same(m1Tuple, m1E1.ContainingSymbol); Assert.True(m1E1.GetAttributes().IsEmpty); Assert.Null(m1E1.GetUseSiteDiagnostic()); Assert.True(m1E1.DeclaringSyntaxReferences.SequenceEqual(m1E1.DeclaringSyntaxReferences, SyntaxReferenceEqualityComparer.Instance)); Assert.False(m1E1.IsImplicitlyDeclared); Assert.True(m1E1Add.Equals(m1E1.AddMethod, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1Remove.Equals(m1E1.RemoveMethod, TypeCompareKind.ConsiderEverything)); Assert.False(m1E1.IsExplicitInterfaceImplementation); Assert.True(m1E1.ExplicitInterfaceImplementations.IsEmpty); Assert.Null(m1E1.OverriddenEvent); Assert.True(m1E1.Equals(m1E1Add.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1Add.IsImplicitlyDeclared); Assert.True(m1E1.Equals(m1E1Remove.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1Remove.IsImplicitlyDeclared); var m1E1BackingField = m1E1.AssociatedField; Assert.Equal("System.Action<System.Int32> (System.Int32, System.Int64).E1", m1E1BackingField.ToTestDisplayString()); Assert.Same(m1Tuple, m1E1BackingField.ContainingSymbol); Assert.True(m1E1.Equals(m1E1BackingField.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1BackingField.IsImplicitlyDeclared); Assert.True(m1E1BackingField.TupleUnderlyingField.IsImplicitlyDeclared); var m1E2 = m1Tuple.GetMember<EventSymbol>("E2"); var m1E2Add = m1Tuple.GetMember<MethodSymbol>("add_E2"); var m1E2Remove = m1Tuple.GetMember<MethodSymbol>("remove_E2"); Assert.Equal(SymbolKind.Event, m1E2.Kind); Assert.Equal("event System.Action<System.Int64> (System.Int32, System.Int64).E2", m1E2.ToTestDisplayString()); Assert.Equal("event System.Action<T2> (T1, T2).E2", m1E2.OriginalDefinition.ToTestDisplayString()); Assert.Same(m1Tuple, m1E2.ContainingSymbol); Assert.True(m1E2.GetAttributes().IsEmpty); Assert.Null(m1E2.GetUseSiteDiagnostic()); Assert.True(m1E2.DeclaringSyntaxReferences.SequenceEqual(m1E2.DeclaringSyntaxReferences, SyntaxReferenceEqualityComparer.Instance)); Assert.False(m1E2.IsImplicitlyDeclared); Assert.NotSame(m1E2Add, m1E2.AddMethod); Assert.True(m1E2Add.Equals(m1E2.AddMethod, TypeCompareKind.ConsiderEverything)); Assert.NotSame(m1E2Remove, m1E2.RemoveMethod); Assert.True(m1E2Remove.Equals(m1E2.RemoveMethod, TypeCompareKind.ConsiderEverything)); Assert.False(m1E2.IsExplicitInterfaceImplementation); Assert.True(m1E2.ExplicitInterfaceImplementations.IsEmpty); Assert.Null(m1E2.OverriddenEvent); Assert.Null(m1E2.AssociatedField); Assert.NotSame(m1E2, m1E2Add.AssociatedSymbol); Assert.True(m1E2.Equals(m1E2Add.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1E2Add.IsImplicitlyDeclared); Assert.NotSame(m1E2, m1E2Remove.AssociatedSymbol); Assert.True(m1E2.Equals(m1E2Remove.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1E2Remove.IsImplicitlyDeclared); } [Fact] public void EventsAsMembers_02() { var source = @" class C { static void Main() { var v1 = M1(); v1.E1(); } static (int, long) M1() { return (1, 11); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this.E1(); } public event System.Action E1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,12): error CS0070: The event '(int, long).E1' can only appear on the left hand side of += or -= (except when used from within the type '(int, long)') // v1.E1(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("(int, long).E1", "(int, long)").WithLocation(7, 12) ); } [Fact] public void TupleTypeWithPatternIs() { var source = @" class C { void Match(object o) { if (o is (int, int) t) { } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,19): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (o is (int, int) t) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(6, 19), // (6,24): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (o is (int, int) t) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(6, 24), // (6,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // if (o is (int, int) t) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int, int)").WithArguments("object", "2").WithLocation(6, 18) ); } [Fact] public void TupleAsStatement() { var source = @" class C { void M(int x) { (x, x); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (x, x); Diagnostic(ErrorCode.ERR_IllegalStatement, "(x, x)").WithLocation(6, 9) ); } [Fact] public void TupleTypeWithPatternIs2() { var source = @" class C { void Match(object o) { if (o is (int a, int b)) { } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // if (o is (int a, int b)) { } Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(int a, int b)").WithArguments("object", "Deconstruct").WithLocation(6, 18), // (6,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // if (o is (int a, int b)) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int a, int b)").WithArguments("object", "2").WithLocation(6, 18) ); } [Fact] public void TupleDeclarationWithPatternIs() { var source = @" class C { void Match(object o) { if (o is (1, 2)) { } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // if (o is (1, 2)) { } Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(6, 18), // (6,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // if (o is (1, 2)) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(6, 18) ); } [Fact] public void TupleTypeWithPatternSwitch() { var source = @" class C { void Match(object o) { switch(o) { case (int, int) tuple: return; } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,19): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // case (int, int) tuple: return; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(7, 19), // (7,24): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // case (int, int) tuple: return; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(7, 24), // (7,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (int, int) tuple: return; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int, int)").WithArguments("object", "2").WithLocation(7, 18) ); } [Fact] public void TupleLiteralWithPatternSwitch() { var source = @" class C { void Match(object o) { switch(o) { case (1, 1): return; } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 1): return; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 1)").WithArguments("object", "Deconstruct").WithLocation(7, 18), // (7,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 1): return; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 1)").WithArguments("object", "2").WithLocation(7, 18) ); } [Fact] public void TupleLiteralWithPatternSwitch2() { var source = @" class C { void Match(object o) { switch(o) { case (1, 1) t: return; } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 1) t: return; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 1)").WithArguments("object", "Deconstruct").WithLocation(7, 18), // (7,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 1) t: return; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 1)").WithArguments("object", "2").WithLocation(7, 18) ); } [Fact] public void TupleAsStatement2() { var source = @" class C { void M() { (1, 1); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (1, 1); Diagnostic(ErrorCode.ERR_IllegalStatement, "(1, 1)").WithLocation(6, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/11282 + https://github.com/dotnet/roslyn/issues/11291")] [WorkItem(11282, "https://github.com/dotnet/roslyn/issues/11282")] [WorkItem(11291, "https://github.com/dotnet/roslyn/issues/11291")] public void TargetTyping_01() { var source = @" class C { static void Main() { var x0 = new {tuple = (null, null)}; System.Console.WriteLine(x0.ToString()); System.ValueType x1 = (null, ""1""); } [TestAttribute((null, ""2""))] [TestAttribute((3, ""3""))] [TestAttribute(Val = (null, ""4""))] [TestAttribute(Val = (5, ""5""))] static void AttributeTarget1(){} async System.Threading.Tasks.Task AsyncTest() { await (null, ""6""); await (7, ""7""); } static void Default((int, string) val1 = (8, null), (int, string) val2 = (9, ""9""), (int, string) val3 = (""10"", ""10"")) {} [TestAttribute((""11"", ""11""))] [TestAttribute(Val = (""12"", ""12""))] static void AttributeTarget2(){} enum TestEnum { V1 = (13, null), V2 = (14, ""14""), V3 = (""15"", ""15""), } static void Test2() { var x = (16, (16 , null)); System.Console.WriteLine(x); var u = __refvalue((17, null), (int, string)); var v = __refvalue((18, ""18""), (int, string)); var w = __refvalue((""19"", ""19""), (int, string)); } } class TestAttribute : System.Attribute { public TestAttribute() {} public TestAttribute((int, string) val) {} public (int, string) Val {get; set;} } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, references: new[] { SystemRef }); comp.VerifyDiagnostics( // (6,32): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // var x0 = new {tuple = (null, null)}; Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(6, 32), // (6,38): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // var x0 = new {tuple = (null, null)}; Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(6, 38), // (8,31): error CS8330: Cannot implicitly convert tuple expression to 'ValueType' // System.ValueType x1 = (null, "1"); Diagnostic(ErrorCode.Unknown, @"(null, ""1"")").WithArguments("System.ValueType").WithLocation(8, 31), // (11,20): error CS1503: Argument 1: cannot convert from '<tuple>' to '(int, string)' // [TestAttribute((null, "2"))] Diagnostic(ErrorCode.ERR_BadArgType, @"(null, ""2"")").WithArguments("1", "<tuple>", "(int, string)").WithLocation(11, 20), // (12,6): error CS0181: Attribute constructor parameter 'val' has type '(int, string)', which is not a valid attribute parameter type // [TestAttribute((3, "3"))] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "TestAttribute").WithArguments("val", "(int, string)").WithLocation(12, 6), // (13,20): error CS0655: 'Val' is not a valid named attribute argument because it is not a valid attribute parameter type // [TestAttribute(Val = (null, "4"))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "Val").WithArguments("Val").WithLocation(13, 20), // (14,20): error CS0655: 'Val' is not a valid named attribute argument because it is not a valid attribute parameter type // [TestAttribute(Val = (5, "5"))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "Val").WithArguments("Val").WithLocation(14, 20), // (19,16): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // await (null, "6"); Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(19, 16), // (20,9): error CS1061: '(int, string)' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // await (7, "7"); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, @"await (7, ""7"")").WithArguments("(int, string)", "GetAwaiter").WithLocation(20, 9), // (23,46): error CS1736: Default parameter value for 'val1' must be a compile-time constant // static void Default((int, string) val1 = (8, null), Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(8, null)").WithArguments("val1").WithLocation(23, 46), // (24,46): error CS1736: Default parameter value for 'val2' must be a compile-time constant // (int, string) val2 = (9, "9")) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"(9, ""9"")").WithArguments("val2").WithLocation(24, 46), // (25,46): error CS1736: Default parameter value for 'val3' must be a compile-time constant // (int, string) val3 = ("10", "10")) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"(""10"", ""10"")").WithArguments("val3").WithLocation(25, 46), // (28,20): error CS1503: Argument 1: cannot convert from '<tuple>' to '(int, string)' // [TestAttribute(("11", "11"))] Diagnostic(ErrorCode.ERR_BadArgType, @"(""11"", ""11"")").WithArguments("1", "<tuple>", "(int, string)").WithLocation(28, 20), // (29,20): error CS0655: 'Val' is not a valid named attribute argument because it is not a valid attribute parameter type // [TestAttribute(Val = ("12", "12"))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "Val").WithArguments("Val").WithLocation(29, 20), // (34,14): error CS8330: Cannot implicitly convert tuple expression to 'int' // V1 = (13, null), Diagnostic(ErrorCode.Unknown, "(13, null)").WithArguments("int").WithLocation(34, 14), // (35,14): error CS8330: Cannot implicitly convert tuple expression to 'int' // V2 = (14, "14"), Diagnostic(ErrorCode.Unknown, @"(14, ""14"")").WithArguments("int").WithLocation(35, 14), // (36,14): error CS8330: Cannot implicitly convert tuple expression to 'int' // V3 = ("15", "15"), Diagnostic(ErrorCode.Unknown, @"(""15"", ""15"")").WithArguments("int").WithLocation(36, 14), // (41,28): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // var x = (16, (16 , null)); Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(41, 28), // (44,17): error CS8330: Cannot implicitly convert tuple expression to 'TypedReference' // var u = __refvalue((17, null), (int, string)); Diagnostic(ErrorCode.Unknown, "__refvalue((17, null), (int, string))").WithArguments("System.TypedReference").WithLocation(44, 17), // (45,17): error CS8330: Cannot implicitly convert tuple expression to 'TypedReference' // var v = __refvalue((18, "18"), (int, string)); Diagnostic(ErrorCode.Unknown, @"__refvalue((18, ""18""), (int, string))").WithArguments("System.TypedReference").WithLocation(45, 17), // (46,17): error CS8330: Cannot implicitly convert tuple expression to 'TypedReference' // var w = __refvalue(("19", "19"), (int, string)); Diagnostic(ErrorCode.Unknown, @"__refvalue((""19"", ""19""), (int, string))").WithArguments("System.TypedReference").WithLocation(46, 17) ); } [Fact] public void TargetTyping_02() { var source = @" class C { static void Print<T>(T val) { System.Console.WriteLine($""{typeof(T)} - {val.ToString()}""); } static void Main() { var x0 = new {tuple = (1, ""s"")}; Print(x0.tuple); System.ValueType x1 = (2, ""s""); Print(x1); (int, (int, string)) x2 = (3, (3 , null)); Print(x2); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.ValueTuple`2[System.Int32,System.String] - {1, s} System.ValueType - {2, s} System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.String]] - {3, {3, }} "); } [Fact] public void TargetTyping_03() { var source = @" class Class { void Method() { tuple = (1, ""hello""); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,31): error CS0103: The name 'tuple' does not exist in the current context // class Class { void Method() { tuple = (1, "hello"); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "tuple").WithArguments("tuple").WithLocation(2, 31) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""hello"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.String)", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind); } [Fact] public void MissingUnderlyingType() { string source = @" class C { void M() { (int, int) x = (1, 1); } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = (INamedTypeSymbol)((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; Assert.True(xSymbol.IsTupleType); Assert.Equal("(System.Int32, System.Int32)[missing]", xSymbol.ToTestDisplayString()); Assert.Null(xSymbol.TupleUnderlyingType); Assert.True(xSymbol.IsErrorType()); Assert.True(xSymbol.IsReferenceType); AssertEx.Equal(new[] { "System.Int32 (System.Int32, System.Int32)[missing].Item1", "System.Int32 (System.Int32, System.Int32)[missing].Item2" }, ((ErrorTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembersUnordered().ToTestDisplayStrings().ToImmutableArray().Sort()); AssertEx.Equal("System.Int32 (System.Int32, System.Int32)[missing].Item1", ((NamedTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembers("Item1").Single().ToTestDisplayString()); } [Fact] public void MissingUnderlyingType_WithNames() { string source = @" class C { void M() { (int a, int b) x = (1, 1); } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = (INamedTypeSymbol)((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; Assert.True(xSymbol.IsTupleType); Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", xSymbol.ToTestDisplayString()); Assert.True(xSymbol.TupleUnderlyingType.IsErrorType()); Assert.True(xSymbol.IsErrorType()); Assert.True(xSymbol.IsReferenceType); AssertEx.Equal(new[] { "System.Int32 (System.Int32 a, System.Int32 b)[missing].a", "System.Int32 (System.Int32 a, System.Int32 b)[missing].b", "System.Int32 (System.Int32 a, System.Int32 b)[missing].Item1", "System.Int32 (System.Int32 a, System.Int32 b)[missing].Item2" }, ((ErrorTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembersUnordered().ToTestDisplayStrings().ToImmutableArray().Sort()); AssertEx.Equal("System.Int32 (System.Int32 a, System.Int32 b)[missing].Item1", ((NamedTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembers("Item1").Single().ToTestDisplayString()); AssertEx.Equal("System.Int32 (System.Int32 a, System.Int32 b)[missing].a", ((NamedTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembers("a").Single().ToTestDisplayString()); } [Fact, CompilerTrait(CompilerFeature.LocalFunctions)] public void LocalFunction() { var source = @" class C { static void Main() { (int, int) Local((int, int) x) { return x; } System.Console.WriteLine(Local((1, 2))); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 2)"); comp.VerifyDiagnostics(); } [Fact] public void LocalFunctionWithNamedTuple() { var source = @" class C { static void Main() { (int a, int b) Local((int c, int d) x) { return x; } System.Console.WriteLine(Local((d: 1, c: 2)).b); } } "; var comp = CompileAndVerify(source, expectedOutput: "2"); comp.VerifyDiagnostics( // (7,41): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(int c, int d)'. // System.Console.WriteLine(Local((d: 1, c: 2)).b); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 1").WithArguments("d", "(int c, int d)").WithLocation(7, 41), // (7,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int c, int d)'. // System.Console.WriteLine(Local((d: 1, c: 2)).b); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 2").WithArguments("c", "(int c, int d)").WithLocation(7, 47) ); } [Fact, CompilerTrait(CompilerFeature.LocalFunctions)] public void LocalFunctionWithLongTuple() { var source = @" class C { static void Main() { (int, string, int, string, int, string, int, string) Local((int, string, int, string, int, string, int, string) x) { return x; } System.Console.WriteLine(Local((1, ""Alice"", 2, ""Brenda"", 3, ""Chloe"", 4, ""Dylan""))); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, Alice, 2, Brenda, 3, Chloe, 4, Dylan)"); comp.VerifyDiagnostics(); } [Fact] public void TupleMembersInLambda() { var source = @" using System; class C { static Action action; static void Main() { var tuple = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8); action += () => { Console.Write(tuple.Item1 + "" "" + tuple.a + "" "" + tuple.Rest + "" "" + tuple.Item8 + "" "" + tuple.h); }; action(); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 1 (8) 8 8"); comp.VerifyDiagnostics(); } [Fact] public void LongTupleConstructor() { var source = @" class C { void M() { var x = new (int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8); var y = new (int, int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int, int, int, int, int, int, int)").WithLocation(6, 21), // (7,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var y = new (int, int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int, int, int, int, int, int, int, int)").WithLocation(7, 21) ); } [Fact] public void TupleWithDynamicInSeparateCompilations() { var lib_cs = @" public class C { public static (dynamic, dynamic) M((dynamic, dynamic) x) { return x; } } "; var source = @" class D { static void Main() { var x = C.M((1, ""hello"")); x.Item1.DynamicMethod1(); x.Item2.DynamicMethod2(); } } "; var libComp = CreateCompilation(lib_cs, assemblyName: "lib"); libComp.VerifyDiagnostics(); var comp1 = CreateCompilation(source, references: new[] { libComp.ToMetadataReference() }); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] [WorkItem(11322, "https://github.com/dotnet/roslyn/issues/11322")] public void LiteralsAndAmbiguousVT_01() { var source = @" class C3 { public static void Main() { var x = (1, 1); System.Console.WriteLine(x.GetType().Assembly); } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); comp = CreateCompilationWithMscorlib40(source, references: new[] { comp2.ToMetadataReference(), comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); comp = CreateCompilationWithMscorlib40(source, references: new[] { comp2.ToMetadataReference(ImmutableArray.Create("alias")), comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [Fact] [WorkItem(11322, "https://github.com/dotnet/roslyn/issues/11322")] public void LiteralsAndAmbiguousVT_02() { var source1 = trivial2uple; var source2 = @" public static class C2 { public static void M1(this string x, (int, string) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source3 = @" class C3 { public static void Main() { ""x"".M1((1, null)); } } "; var comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,16): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) ); comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference().WithAliases(ImmutableArray.Create("alias")), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); var source4 = @" extern alias alias1; using alias1; class C3 { public static void Main() { ""x"".M1((1, null)); } } "; comp = CreateCompilationWithMscorlib40(source4, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); } [Fact] [WorkItem(11322, "https://github.com/dotnet/roslyn/issues/11322")] public void LongLiteralsAndAmbiguousVT_02() { var source1 = trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; var source2 = @" public static class C2 { public static void M1(this string x, (int, string, int, string, int, string, int, string, int, string) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source3 = @" class C3 { public static void Main() { ""x"".M1((1, null, 1, null, 1, null, 1, null, 1, null)); } } "; var comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,16): error CS8356: Predefined type 'System.ValueTuple`3' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null, 1, null, 1, null, 1, null, 1, null)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`3", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16), // (6,16): error CS8356: Predefined type 'System.ValueTuple`8' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null, 1, null, 1, null, 1, null, 1, null)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`8", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) ); comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference().WithAliases(ImmutableArray.Create("alias")), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); var source4 = @" extern alias alias1; using alias1; class C3 { public static void Main() { ""x"".M1((1, null, 1, null, 1, null, 1, null, 1, null)); } } "; comp = CreateCompilationWithMscorlib40(source4, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); } [Fact] [WorkItem(11323, "https://github.com/dotnet/roslyn/issues/11323")] public void ExactlyMatchingExpression() { var source1 = @" namespace NS1 { public static class C1 { public static void M1(this string x, (int, int) y) { System.Console.WriteLine(""C1.M1""); } } } "; var source2 = @" namespace NS2 { public static class C2 { public static void M1(this string x, (int, int) y) { System.Console.WriteLine(""C2.M1""); } } } "; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, references: s_valueTupleRefs, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, references: s_valueTupleRefs, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source3 = @" extern alias alias1; using alias1::NS2; using NS1; class C3 { public static void Main() { ""x"".M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib40(source3, references: s_valueTupleRefs.Concat(new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }), parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,13): error CS0121: The call is ambiguous between the following methods or properties: 'NS2.C2.M1(string, (int, int))' and 'NS1.C1.M1(string, (int, int))' // "x".M1((1, 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("NS2.C2.M1(string, (int, int))", "NS1.C1.M1(string, (int, int))").WithLocation(10, 13) ); var source4 = @" using NS1; class C3 { public static void Main() { ""x"".M1((1, 1)); } } "; comp = CreateCompilationWithMscorlib40(source4, references: s_valueTupleRefs.Concat(new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }), parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1.M1"); var source5 = @" extern alias alias1; using alias1::NS2; class C3 { public static void Main() { ""x"".M1((1, 1)); } } "; comp = CreateCompilationWithMscorlib40(source5, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")), ValueTupleRef, SystemRuntimeFacadeRef }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); } [Fact] public void MultipleVT_01() { var source1 = @" public class C1 { public void M1((int, int) y) { System.Console.WriteLine(""C1.M1""); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public void M1((int, int) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source = @" extern alias alias1; class C3 { public static void Main() { new C1().M1((1, 1)); new alias1::C2().M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib46(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"C1.M1 C2.M1"); } [Fact] [WorkItem(11325, "https://github.com/dotnet/roslyn/issues/11325")] public void MultipleVT_02() { var source1 = @" public class C1 { public (int, int) M2() { System.Console.WriteLine(""C1.M2""); return (1, 1); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public void M3((int, int) y) { System.Console.WriteLine(""C2.M3""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source = @" extern alias alias1; class C3 { public static void Main() { new alias1::C2().M3(new C1().M2()); } } "; var comp = CreateCompilation(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"C1.M2 C2.M3"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/11326")] [WorkItem(11326, "https://github.com/dotnet/roslyn/issues/11326")] public void GetTypeInfo_01() { var source = @" class C { static void Main() { var x1 = ((short, string))(1, ""hello""); var x2 = ((short, string))(2, null); var x3 = (short)11; var x4 = (string)null; var x5 = (System.Func<int>)(() => 12); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); //comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var n1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal(@"(1, ""hello"")", n1.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(n1)); var n2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(2, null)", n2.ToString()); Assert.Null(model.GetTypeInfo(n2).Type); Assert.Null(model.GetTypeInfo(n2).ConvertedType); Assert.Equal(Conversion.Identity, model.GetConversion(n2)); var n3 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(4); Assert.Equal(@"11", n3.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(n3).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(n3).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(n3)); var n4 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(5); Assert.Equal(@"null", n4.ToString()); Assert.Null(model.GetTypeInfo(n4).Type); Assert.Null(model.GetTypeInfo(n4).ConvertedType); Assert.Equal(Conversion.Identity, model.GetConversion(n4)); var n5 = nodes.OfType<LambdaExpressionSyntax>().Single(); Assert.Equal(@"() => 12", n5.ToString()); Assert.Null(model.GetTypeInfo(n5).Type); Assert.Equal("System.Func<System.Int32>", model.GetTypeInfo(n5).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.AnonymousFunction, model.GetConversion(n5).Kind); } [Fact] [WorkItem(11326, "https://github.com/dotnet/roslyn/issues/11326")] public void GetTypeInfo_02() { var source = @" class C { static void Main() { (short, string) x1 = (1, ""hello""); (short, string) x2 = (2, null); short x3 = 11; string x4 = null; System.Func<int> x5 = () => 12; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); //comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var n1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal(@"(1, ""hello"")", n1.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).Type.ToTestDisplayString()); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n1).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n1).Kind); var n2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(2, null)", n2.ToString()); Assert.Null(model.GetTypeInfo(n2).Type); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n2).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n2).Kind); var n3 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(4); Assert.Equal(@"11", n3.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(n3).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(n3).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(n3).Kind); var n4 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(5); Assert.Equal(@"null", n4.ToString()); Assert.Null(model.GetTypeInfo(n4).Type); Assert.Equal("System.String", model.GetTypeInfo(n4).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitReference, model.GetConversion(n4)); var n5 = nodes.OfType<LambdaExpressionSyntax>().Single(); Assert.Equal(@"() => 12", n5.ToString()); Assert.Null(model.GetTypeInfo(n5).Type); Assert.Equal("System.Func<System.Int32>", model.GetTypeInfo(n5).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.AnonymousFunction, model.GetConversion(n5).Kind); } [Fact] [WorkItem(36185, "https://github.com/dotnet/roslyn/issues/36185")] public void GetTypeInfo_03() { var source = @" class C { static void Main() { M((1, ""hello"")); M((2, null)); } public static void M((short, string) x) { } } " + trivial2uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var n1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal(@"(1, ""hello"")", n1.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).Type.ToTestDisplayString()); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n1).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n1).Kind); var n2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(2, null)", n2.ToString()); Assert.Null(model.GetTypeInfo(n2).Type); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n2).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n2).Kind); } [Fact] [WorkItem(14600, "https://github.com/dotnet/roslyn/issues/14600")] public void GetSymbolInfo_01() { var source = @" class C { static void Main() { // error is intentional. GetSymbolInfo should still work DummyType x1 = (Alice: 1, ""hello""); var Alice = x1.Alice; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var nc = nodes.OfType<NameColonSyntax>().ElementAt(0); var sym = model.GetSymbolInfo(nc.Name); Assert.Equal(SymbolKind.Field, sym.Symbol.Kind); Assert.Equal("Alice", sym.Symbol.Name); Assert.Equal(nc.Name.GetLocation(), sym.Symbol.Locations[0]); } [Fact] public void GetSymbolInfo_WithInferredName() { var source = @" class C { static void Main() { string Bob = ""hello""; var x1 = (Alice: 1, Bob); var Alice = x1.Alice; var BobCopy = x1.Bob; } } "; var tree = Parse(source, options: TestOptions.Regular7_1); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1Bob = nodes.OfType<MemberAccessExpressionSyntax>().ElementAt(1); Assert.Equal("x1.Bob", x1Bob.ToString()); var x1Symbol = model.GetSymbolInfo(x1Bob.Expression).Symbol as ILocalSymbol; Assert.Equal("(System.Int32 Alice, System.String Bob)", x1Symbol.Type.ToTestDisplayString()); var bobField = x1Symbol.Type.GetMember("Bob"); Assert.Equal(SymbolKind.Field, bobField.Kind); var secondElement = nodes.OfType<TupleExpressionSyntax>().First().Arguments[1]; Assert.Equal(secondElement.GetLocation(), bobField.Locations[0]); } [Fact] [WorkItem(23651, "https://github.com/dotnet/roslyn/issues/23651")] public void GetSymbolInfo_WithDuplicateInferredName() { var source = @" class C { static object M(string Bob) { var x1 = (Bob, Bob); return x1; } } "; var tree = Parse(source, options: TestOptions.Regular7_1); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = nodes.OfType<VariableDeclaratorSyntax>().Single(); Assert.Equal("x1 = (Bob, Bob)", x1.ToString()); var x1Symbol = (ILocalSymbol)model.GetDeclaredSymbol(x1); Assert.Equal("(System.String, System.String) x1", x1Symbol.ToTestDisplayString()); Assert.True(x1Symbol.Type.GetSymbol().TupleElementNames.IsDefault); } [Fact] public void CompileTupleLib() { string additionalSource = @" namespace System { public class SR { public static string ArgumentException_ValueTupleIncorrectType { get { return """"; } } public static string ArgumentException_ValueTupleLastArgumentNotAValueTuple { get { return """"; } } } } namespace System.Diagnostics { public static class Debug { public static void Assert(bool condition) { } public static void Assert(bool condition, string message) { } } } "; var tupleComp = CreateCompilationWithMscorlib40( tuplelib_cs + tupleattributes_cs + additionalSource); tupleComp.VerifyDiagnostics(); var source = @" class C { static void Main() { var x = (1, 2); System.Console.WriteLine(x.ToString()); } } "; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "(1, 2)", references: new[] { tupleComp.ToMetadataReference() }); comp.VerifyDiagnostics(); } [Fact] public void ImplicitConversions01() { var source = @" using System; class C { static void Main() { // long tuple var x1 = (1,2,3,4,5,6,7,8,9,10,11,12); (long, long, long, long, long, long, long, long,long, long, long, long) y1 = x1; System.Console.WriteLine(y1); // long nested tuple var x2 = (1,2,3,4,5,6,7,8,9,10,11,(1,2,3,4,5,6,7,8,9,10,11,12)); (long, long, long, long, long, long, long, long,long, long, long, (long, long, long, long, long, long, long, long,long, long, long, long)) y2 = x2; System.Console.WriteLine(y2); // user defined conversion var x3 = (1,1); C1 y3 = x3; x3 = y3; System.Console.WriteLine(x3); } class C1 { static public implicit operator C1((long, long) arg) { return new C1(); } static public implicit operator (byte, byte)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, expectedOutput: @" (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) (2, 2) "); } [Fact] public void ExplicitConversions01() { var source = @" using System; class C { static void Main() { // long tuple var x1 = (1,2,3,4,5,6,7,8,9,10,11,12); (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte) y1 = ((byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte))x1; System.Console.WriteLine(y1); // long nested tuple var x2 = (1,2,3,4,5,6,7,8,9,10,11,(1,2,3,4,5,6,7,8,9,10,11,12)); (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte)) y2 = ((byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte)))x2; System.Console.WriteLine(y2); // user defined conversion var x3 = (1,1); C1 y3 = (C1)x3; x3 = ((int, int))y3; System.Console.WriteLine(x3); } class C1 { static public explicit operator C1((long, long) arg) { return new C1(); } static public explicit operator (byte, byte)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, expectedOutput: @" (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) (2, 2) "); } [Fact] public void ImplicitConversions02() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = x; x = y; System.Console.WriteLine(x); x = ((int, int))(C1)x; System.Console.WriteLine(x); } class C1 { static public implicit operator C1((long, long) arg) { return new C1(); } static public implicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2)"); comp.VerifyIL("C.Main", @" { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<byte, byte> V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0015: conv.i8 IL_0016: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_001b: call ""C.C1 C.C1.op_Implicit(System.ValueTuple<long, long>)"" IL_0020: call ""System.ValueTuple<byte, byte> C.C1.op_Implicit(C.C1)"" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_002c: ldloc.1 IL_002d: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_0032: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0037: dup IL_0038: box ""System.ValueTuple<int, int>"" IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0050: conv.i8 IL_0051: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_0056: call ""C.C1 C.C1.op_Implicit(System.ValueTuple<long, long>)"" IL_005b: call ""System.ValueTuple<byte, byte> C.C1.op_Implicit(C.C1)"" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_0067: ldloc.1 IL_0068: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_006d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0072: box ""System.ValueTuple<int, int>"" IL_0077: call ""void System.Console.WriteLine(object)"" IL_007c: ret } "); ; } [Fact] public void ExplicitConversions02() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = (C1)x; x = ((int a, int b))y; System.Console.WriteLine(x); x = ((int, int))(C1)x; System.Console.WriteLine(x); } class C1 { static public explicit operator C1((long, long) arg) { return new C1(); } static public explicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2)"); comp.VerifyIL("C.Main", @" { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<byte, byte> V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0015: conv.i8 IL_0016: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_001b: call ""C.C1 C.C1.op_Explicit(System.ValueTuple<long, long>)"" IL_0020: call ""System.ValueTuple<byte, byte> C.C1.op_Explicit(C.C1)"" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_002c: ldloc.1 IL_002d: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_0032: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0037: dup IL_0038: box ""System.ValueTuple<int, int>"" IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0050: conv.i8 IL_0051: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_0056: call ""C.C1 C.C1.op_Explicit(System.ValueTuple<long, long>)"" IL_005b: call ""System.ValueTuple<byte, byte> C.C1.op_Explicit(C.C1)"" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_0067: ldloc.1 IL_0068: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_006d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0072: box ""System.ValueTuple<int, int>"" IL_0077: call ""void System.Console.WriteLine(object)"" IL_007c: ret } "); } [Fact] public void ImplicitConversions03() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = x; (int, int)? x1 = y; System.Console.WriteLine(x1); x1 = ((int, int)?)(C1)x; System.Console.WriteLine(x1); } class C1 { static public implicit operator C1((long, long)? arg) { return new C1(); } static public implicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2) "); } [Fact] public void ExplicitConversions03() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = (C1)x; (int, int)? x1 = ((int, int)?)y; System.Console.WriteLine(x1); x1 = ((int, int)?)(C1)x; System.Console.WriteLine(x1); } class C1 { static public explicit operator C1((long, long)? arg) { return new C1(); } static public explicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2) "); } [Fact] public void ImplicitConversions04() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, (1, 1)))))); C1 y = x; (int, int) x2 = y; System.Console.WriteLine(x2); (int, (int, int)) x3 = y; System.Console.WriteLine(x3); (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))) x12 = y; System.Console.WriteLine(x12); } class C1 { private byte x; static public implicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public implicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public implicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public implicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, 2) (3, (4, 5)) (6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17)))))))))))"); } [Fact] public void ExplicitConversions04Err() { // explicit conversion case similar to ImplicitConversions04 // is a compiler error since explicit tuple conversions do not stack up like // implicit tuple conversions which are in standard implicit set. var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, (1, 1)))))); C1 y = (C1)x; (int, int) x2 = ((int, int))y; System.Console.WriteLine(x2); (int, (int, int)) x3 = ((int, (int, int)))y; System.Console.WriteLine(x3); (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))) x12 = ((int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))))y; System.Console.WriteLine(x12); } class C1 { private byte x; static public explicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public explicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public explicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public explicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (8,16): error CS0030: Cannot convert type '(int, (int, (int, (int, (int, (int, int))))))' to 'C.C1' // C1 y = (C1)x; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C1)x").WithArguments("(int, (int, (int, (int, (int, (int, int))))))", "C.C1").WithLocation(8, 16), // (13,32): error CS0030: Cannot convert type 'C.C1' to '(int, (int, int))' // (int, (int, int)) x3 = ((int, (int, int)))y; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((int, (int, int)))y").WithArguments("C.C1", "(int, (int, int))").WithLocation(13, 32), // (16,96): error CS0030: Cannot convert type 'C.C1' to '(int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int)))))))))))' // (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))) x12 = ((int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))))y; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))))y").WithArguments("C.C1", "(int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int)))))))))))").WithLocation(16, 96) ); } [Fact] public void ImplicitConversions05() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = y; System.Console.WriteLine(x1); } class C1 { private byte x; static public implicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public implicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public implicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public implicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, (2, (3, (4, (5, 6))))) "); } [Fact] public void ExplicitConversions05() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = (C1)((int, C1))((int, (int, C1)))((int, (int, (int, C1))))((int, (int, (int, (int, C1)))))x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = ((int, (object, (byte, (int?, (long, IComparable)?))?))?) ((int, (object, (byte, (int?, C1))?))?) ((int, (object, (byte, C1)?))?) ((int, (object, C1))?) ((int, C1)?) (C1)y; System.Console.WriteLine(x1); } class C1 { private byte x; static public explicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public explicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public explicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public explicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, (2, (3, (4, (5, 6))))) "); } [Fact] public void ImplicitConversions05Err() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = y; System.Console.WriteLine(x1); } class C1 { private byte x; static public implicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public implicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,70): error CS0029: Cannot implicitly convert type 'C.C1' to '(int, (object, (byte, (int?, (long, System.IComparable)?))?))?' // (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y").WithArguments("C.C1", "(int, (object, (byte, (int?, (long, System.IComparable)?))?))?").WithLocation(10, 70) ); } [Fact] public void ExplicitConversions05Err() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = (C1)((int, C1))((int, (int, C1)))((int, (int, (int, C1))))((int, (int, (int, (int, C1)))))x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = ((int, (object, (byte, (int?, (long, IComparable)?))?))?) ((int, (object, (byte, (int?, C1))?))?) ((int, (object, (byte, C1)?))?) ((int, (object, C1))?) ((int, C1)?) (C1)y; System.Console.WriteLine(x1); } class C1 { private byte x; static public explicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public explicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,70): error CS0030: Cannot convert type 'C.C1' to '(int, C.C1)?' // ((int, C1)?) Diagnostic(ErrorCode.ERR_NoExplicitConv, @"((int, C1)?) (C1)y").WithArguments("C.C1", "(int, C.C1)?").WithLocation(14, 70) ); } [Fact] public void ImplicitConversions06Err() { var source = @" class C { static void Main() { var x = (1, 1); (long, long) y = x; System.Console.WriteLine(y); } } namespace System { // struct with two values (missing a field) public struct ValueTuple<T1, T2> { public T1 Item1; public ValueTuple(T1 item1, T2 item2) => throw null; } } "; var comp = CreateCompilation(source, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (7,26): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (long, long) y = x; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "x").WithArguments("Item2", "(T1, T2)", "ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 26) ); } [Fact] public void ExplicitConversions06Err() { var source = @" class C { static void Main() { var x = (1, 1); (byte, byte) y = ((byte, byte))x; System.Console.WriteLine(y); } } namespace System { // struct with two values (missing a field) public struct ValueTuple<T1, T2> { public T1 Item1; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; } } } "; var comp = CreateCompilation(source, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (7,26): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (byte, byte) y = ((byte, byte))x; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "((byte, byte))x").WithArguments("Item2", "(T1, T2)", "ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 26) ); } [Fact] public void ImplicitConversions07() { var source = @" using System; internal class Program { static void Main(string[] args) { var t = (1, 1); (C2, C2) aa = t; System.Console.WriteLine(aa); } // accessibility of operators. Notice Private private class C2 { public static implicit operator C2(int arg) { return new C2(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {Program+C2, Program+C2} "); } [Fact] public void ExplicitConversions07() { var source = @" using System; internal class Program { static void Main(string[] args) { var t = (1, 1); (C2, C2) aa = ((C2, C2))t; System.Console.WriteLine(aa); } // accessibility of operators. Notice Private private class C2 { public static explicit operator C2(int arg) { return new C2(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {Program+C2, Program+C2} "); } [Fact] public void ExplicitConversionsSimple01() { var source = @" using System; class C { static void Main() { var x = (a:1, b:2); var y = ((byte, byte))x; System.Console.WriteLine(y); var z = ((int, int))((long)3, (object)4); System.Console.WriteLine(z); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {1, 2} {3, 4}"); comp.VerifyIL("C.Main", @" { // Code size 65 (0x41) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: conv.u1 IL_000f: ldloc.0 IL_0010: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0015: conv.u1 IL_0016: newobj ""System.ValueTuple<byte, byte>..ctor(byte, byte)"" IL_001b: box ""System.ValueTuple<byte, byte>"" IL_0020: call ""void System.Console.WriteLine(object)"" IL_0025: ldc.i4.3 IL_0026: ldc.i4.4 IL_0027: box ""int"" IL_002c: unbox.any ""int"" IL_0031: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0036: box ""System.ValueTuple<int, int>"" IL_003b: call ""void System.Console.WriteLine(object)"" IL_0040: ret } "); ; } [Fact] public void ExplicitConversionsSimple02() { var source = @" using System; class C { static void Main() { var x = (a:1, b:2); var y = ((C2, C2))x; System.Console.WriteLine(y); var z = ((C2, C2))((object)null, 4); System.Console.WriteLine(z); } private class C2 { private int x; public static explicit operator C2(int arg) { var result = new C2(); result.x = arg + 1; return result; } public override string ToString() { return x.ToString(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {2, 3} {, 5}"); comp.VerifyIL("C.Main", @" { // Code size 68 (0x44) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: call ""C.C2 C.C2.op_Explicit(int)"" IL_0013: ldloc.0 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0019: call ""C.C2 C.C2.op_Explicit(int)"" IL_001e: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0023: box ""System.ValueTuple<C.C2, C.C2>"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldnull IL_002e: ldc.i4.4 IL_002f: call ""C.C2 C.C2.op_Explicit(int)"" IL_0034: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0039: box ""System.ValueTuple<C.C2, C.C2>"" IL_003e: call ""void System.Console.WriteLine(object)"" IL_0043: ret } "); ; } [Fact] [WorkItem(11804, "https://github.com/dotnet/roslyn/issues/11804")] public void ExplicitConversionsSimple02Expr() { var source = @" class C { static void Main() { var x = (a:1, b:2); var y = ((C2, C2))x; System.Console.WriteLine(y); var z = ((C2, C2))(null, 4); System.Console.WriteLine(z); } private class C2 { private int x; public static explicit operator C2(int arg) { var result = new C2(); result.x = arg + 1; return result; } public override string ToString() { return x.ToString(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" {2, 3} {, 5}"); comp.VerifyIL("C.Main", @" { // Code size 68 (0x44) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: call ""C.C2 C.C2.op_Explicit(int)"" IL_0013: ldloc.0 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0019: call ""C.C2 C.C2.op_Explicit(int)"" IL_001e: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0023: box ""System.ValueTuple<C.C2, C.C2>"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldnull IL_002e: ldc.i4.4 IL_002f: call ""C.C2 C.C2.op_Explicit(int)"" IL_0034: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0039: box ""System.ValueTuple<C.C2, C.C2>"" IL_003e: call ""void System.Console.WriteLine(object)"" IL_0043: ret } "); } [WorkItem(12064, "https://github.com/dotnet/roslyn/issues/12064")] [Fact] public void ExplicitConversionsPreference01() { var source = @" using System; class B { static void Main() { C<int> x = new D<int>(""original""); D<int> y = (D<int>)x; // explicit builtin downcast is preferred Console.WriteLine(""explicit""); Console.WriteLine(y); Console.WriteLine(); y = x; // implicit user defined implicit conversion Console.WriteLine(""implicit""); Console.WriteLine(y); Console.WriteLine(); Console.WriteLine(); (C<int>, C<int>) xt = (new D<int>(""original1""), new D<int>(""original2"")); var xtxt = (xt, xt); Console.WriteLine(""explicit""); (D<int>, D<int>) yt = ((D<int>, D<int>))xt; // explicit builtin downcast is preferred Console.WriteLine(yt); ((D<int>, D<int>),(D<int>, D<int>)) ytyt = (((D<int>, D<int>),(D<int>, D<int>)))(xt, xt); // explicit builtin downcast is preferred Console.WriteLine(ytyt); ytyt = (((D<int>, D<int>),(D<int>, D<int>)))xtxt; // explicit builtin downcast is preferred Console.WriteLine(ytyt); (D<int>, D<int>)? ytn = ((D<int>, D<int>)?)xt; // explicit builtin downcast is preferred (nullable) Console.WriteLine(ytn); Console.WriteLine(); Console.WriteLine(""implicit""); yt = xt; // implicit user defined implicit conversion Console.WriteLine(yt); ytyt = xtxt; // implicit user defined implicit conversion Console.WriteLine(ytyt); ytyt = (xt, xt); // implicit user defined implicit conversion Console.WriteLine(ytyt); ytn = xt; // implicit user defined implicit conversion Console.WriteLine(ytn); } } class C<T> { } class D<T> : C<T> { private readonly string val; public D(string val) { this.val = val; } public override string ToString() { return val; } public static implicit operator D<T>(C<int> x) { return new D<T>(""converted""); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" explicit original implicit converted explicit {original1, original2} {{original1, original2}, {original1, original2}} {{original1, original2}, {original1, original2}} {original1, original2} implicit {converted, converted} {{converted, converted}, {converted, converted}} {{converted, converted}, {converted, converted}} {converted, converted} "); } [Fact] public void ExplicitConversionsPreference02() { var source = @" using System; class A { public static implicit operator A(int d) { return null; } } class B : A { public static implicit operator B(long d) { return null; } } class C { static void Main() { var x = 1; var xt = (x, x); // implicit conversions are unambiguous B b = x; (B, B) bt = xt; // the following is an error for compat reasons // explicit conversion is ambiguous and implicit conversion exists, but ignored b = (B)x; // SHOULD THIS BE AN ERROR TOO? bt = ((B, B))xt; // SHOULD THIS BE AN ERROR TOO? bt = ((B, B)?)xt; } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (28,13): error CS0457: Ambiguous user defined conversions 'B.implicit operator B(long)' and 'A.implicit operator A(int)' when converting from 'int' to 'B' // b = (B)x; Diagnostic(ErrorCode.ERR_AmbigUDConv, "(B)x").WithArguments("B.implicit operator B(long)", "A.implicit operator A(int)", "int", "B").WithLocation(28, 13), // (31,14): error CS0030: Cannot convert type '(int, int)' to '(B, B)' // bt = ((B, B))xt; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((B, B))xt").WithArguments("(int, int)", "(B, B)").WithLocation(31, 14), // (34,14): error CS0030: Cannot convert type '(int, int)' to '(B, B)?' // bt = ((B, B)?)xt; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((B, B)?)xt").WithArguments("(int, int)", "(B, B)?").WithLocation(34, 14) ); } [Fact] public void ConversionsOverload02() { var source = @" using System; class C { static void Main() { (long, long) x = (1,1); Test(x); (int, int) y = (1,1); Test(y); Test((1, 1)); } static void Test((long, long) x) { System.Console.WriteLine(""first""); } static void Test((long?, long?) x) { System.Console.WriteLine(""second""); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first first first "); } [Fact] public void ConversionsOverload03() { var source = @" using System; class C { static void Main() { Test((1, 1)); (int, int)? y = (1,1); Test(y); (long, long)? x = (1,1); Test(x); } static void Test((long?, long?)? x) { System.Console.WriteLine(""second""); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" second second second "); } [Fact] public void ConversionsOverload04() { var source = @" using System; class C { static void Main() { Test((1, 1)); (int, int)? y = (1,1); Test(y); (long, long)? x = (1,1); Test(x); } static void Test((long, long) x) { System.Console.WriteLine(""first""); } static void Test((long?, long?)? x) { System.Console.WriteLine(""second""); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first second second "); } [Fact] public void ConversionsOverload05() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Program { static void Main(string[] args) { Action<IEnumerable> x = null; Action<IEnumerable<int>> x1 = null; // valid and T is IEnumerable<int> // Action<in T> is introducing upper bound on T Test(x, x1); (Action<IEnumerable> x, Action<IEnumerable> y) z = (null, null); (Action<IEnumerable<int>> x, Action<IEnumerable<int>> y) z1 = (null, null); // inference fails // (T, T) is introducing exact bound on T even in an 'in' param position Test(z, z1); // evidently, this is an error. Test<(IEnumerable<int>, IEnumerable <int>)> (z, z1); } public static void Test<T>(Action<T> x, Action<T> y) { System.Console.WriteLine(typeof(T)); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,9): error CS0411: The type arguments for method 'Program.Test<T>(Action<T>, Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test(z, z1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test").WithArguments("Program.Test<T>(System.Action<T>, System.Action<T>)").WithLocation(22, 9), // (25,54): error CS1503: Argument 1: cannot convert from '(System.Action<System.Collections.IEnumerable> x, System.Action<System.Collections.IEnumerable> y)' to 'System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>' // Test<(IEnumerable<int>, IEnumerable <int>)> (z, z1); Diagnostic(ErrorCode.ERR_BadArgType, "z").WithArguments("1", "(System.Action<System.Collections.IEnumerable> x, System.Action<System.Collections.IEnumerable> y)", "System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>").WithLocation(25, 54), // (25,57): error CS1503: Argument 2: cannot convert from '(System.Action<System.Collections.Generic.IEnumerable<int>> x, System.Action<System.Collections.Generic.IEnumerable<int>> y)' to 'System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>' // Test<(IEnumerable<int>, IEnumerable <int>)> (z, z1); Diagnostic(ErrorCode.ERR_BadArgType, "z1").WithArguments("2", "(System.Action<System.Collections.Generic.IEnumerable<int>> x, System.Action<System.Collections.Generic.IEnumerable<int>> y)", "System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>").WithLocation(25, 57) ); } [Fact] public void ClassifyConversionIdentity01() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var int_string1 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_stringNamed = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("a", "b")); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_stringNamed).Kind); } [Fact] public void ClassifyConversionIdentity02() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var int_string1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_string2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_stringNamed = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("a", "b")); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_stringNamed).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_stringNamed, int_string1).Kind); } [Fact] public void ClassifyConversionNone01() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var int_int = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType)); var int_int_int = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType, intType)); var string_string = comp.CreateTupleTypeSymbol(ImmutableArray.Create(stringType, stringType)); var int_int1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int, int_int_int).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int, string_string).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int1, string_string).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int1, int_int_int).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(string_string, int_int1).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int_int, int_int1).Kind); } [Fact] public void ClassifyConversionImplicit01() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); TypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string).Kind); } [Fact] public void ClassifyConversionImplicit02() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object1 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); var int_string2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_object2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, objectType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object2).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object2, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object1, int_string2).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object2, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03u() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Null(int_string1.TupleUnderlyingType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03uu() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Null(int_string1.TupleUnderlyingType); Assert.Null(int_string2.TupleUnderlyingType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03uuu() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Null(int_string1.TupleUnderlyingType); Assert.Null(int_string2.TupleUnderlyingType); Assert.Null(int_object.TupleUnderlyingType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit04() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, ""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilationWithMscorlib40(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { (MetadataReference)Net40.mscorlib, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); var int_object_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType, objectType)); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.ImplicitTuple, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void ClassifyConversionImplicit05() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, (object)""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilationWithMscorlib40(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { (MetadataReference)Net40.mscorlib, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); var int_object_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType, objectType)); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void ClassifyConversionImplicit06() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, ""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { MscorlibRef, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, objectType); var int_object_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, objectType, objectType); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.ImplicitTuple, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void ClassifyConversionImplicit07() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, (object)""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { MscorlibRef, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, objectType); var int_object_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, objectType, objectType); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void TernaryTypeInferenceWithDynamicAndTupleNames() { var source = @" public class C { public void M() { bool flag = true; var x1 = flag ? (a: 1, b: 2) : (a: 1, c: 2); dynamic d = null; var t1 = (a: 1, b: 2); var t2 = (a: 1, c: d); var x2 = flag ? t1 : t2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,32): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int a, int)'. // var x1 = flag ? (a: 1, b: 2) : (a: 1, c: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(7, 32), // (7,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int)'. // var x1 = flag ? (a: 1, b: 2) : (a: 1, c: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 2").WithArguments("c", "(int a, int)").WithLocation(7, 47) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First()); Assert.Equal("(System.Int32 a, System.Int32) x1", x1.ToTestDisplayString()); var x2 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(5).First()); Assert.Equal("(System.Int32 a, dynamic c) x2", x2.ToTestDisplayString()); } [Fact] [WorkItem(16825, "https://github.com/dotnet/roslyn/issues/16825")] public void NullCoalescingOperatorWithTupleNames() { // See section 7.13 of the spec, regarding the null-coalescing operator var source = @" public class C { public void M() { (int a, int b)? nab = (1, 2); (int a, int c)? nac = (1, 3); var x1 = nab ?? nac; // (a, b)? var x2 = nab ?? nac.Value; // (a, b) var x3 = new C() ?? nac; // C var x4 = new D() ?? nac; // (a, c)? var x5 = nab != null ? nab : nac; // (a, )? var x6 = nab ?? (a: 1, c: 3); // (a, b) var x7 = nab ?? (a: 1, c: 3); // (a, b) var x8 = new C() ?? (a: 1, c: 3); // C var x9 = new D() ?? (a: 1, c: 3); // (a, c) var x6double = nab ?? (d: 1.1, c: 3); // (a, c) } public static implicit operator C((int, int) x) { throw null; } } public class D { public static implicit operator (int d1, int d2) (D x) { throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,32): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int b)'. // var x6 = nab ?? (a: 1, c: 3); // (a, b)? Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int b)").WithLocation(16, 32), // (17,32): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int b)'. // var x7 = nab ?? (a: 1, c: 3); // (a, b) Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int b)").WithLocation(17, 32), // (18,30): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(int, int)'. // var x8 = new C() ?? (a: 1, c: 3); // C Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(int, int)").WithLocation(18, 30), // (18,36): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int, int)'. // var x8 = new C() ?? (a: 1, c: 3); // C Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int, int)").WithLocation(18, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2)); Assert.Equal("(System.Int32 a, System.Int32 b)? x1", x1.ToTestDisplayString()); var x2 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(3)); Assert.Equal("(System.Int32 a, System.Int32 b) x2", x2.ToTestDisplayString()); var x3 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(4)); Assert.Equal("C x3", x3.ToTestDisplayString()); var x4 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(5)); Assert.Equal("(System.Int32 a, System.Int32 c)? x4", x4.ToTestDisplayString()); var x5 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(6)); Assert.Equal("(System.Int32 a, System.Int32)? x5", x5.ToTestDisplayString()); var x6 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(7)); Assert.Equal("(System.Int32 a, System.Int32 b) x6", x6.ToTestDisplayString()); var x7 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(8)); Assert.Equal("(System.Int32 a, System.Int32 b) x7", x7.ToTestDisplayString()); var x8 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(9)); Assert.Equal("C x8", x8.ToTestDisplayString()); var x9 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(10)); Assert.Equal("(System.Int32 a, System.Int32 c) x9", x9.ToTestDisplayString()); var x6double = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(11)); Assert.Equal("(System.Double d, System.Int32 c) x6double", x6double.ToTestDisplayString()); } [Fact] public void TernaryTypeInferenceWithNoNames() { var source = @" public class C { public void M() { bool flag = true; var x1 = flag ? (a: 1, b: 2) : (1, 2); var x2 = flag ? (1, 2) : (a: 1, b: 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,26): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(int, int)'. // var x1 = flag ? (a: 1, b: 2) : (1, 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(int, int)").WithLocation(7, 26), // (7,32): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int, int)'. // var x1 = flag ? (a: 1, b: 2) : (1, 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int, int)").WithLocation(7, 32), // (8,35): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(int, int)'. // var x2 = flag ? (1, 2) : (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(int, int)").WithLocation(8, 35), // (8,41): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int, int)'. // var x2 = flag ? (1, 2) : (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int, int)").WithLocation(8, 41) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First()); Assert.Equal("(System.Int32, System.Int32) x1", x1.ToTestDisplayString()); var x2 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(2).First()); Assert.Equal("(System.Int32, System.Int32) x2", x2.ToTestDisplayString()); } [Fact] public void TernaryTypeInferenceDropsCandidates() { var source = @" public class C { public void M() { bool flag = true; var x1 = flag ? (a: 1, b: (long)2) : (a: (byte)1, c: 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,59): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, long b)'. // var x1 = flag ? (a: 1, b: (long)2) : (a: (byte)1, c: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 2").WithArguments("c", "(int a, long b)").WithLocation(7, 59) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First()); Assert.Equal("(System.Int32 a, System.Int64 b) x1", x1.ToTestDisplayString()); } [Fact] public void LambdaTypeInferenceWithTupleNames() { var source = @" public class C { public void M() { var x1 = M2(() => { bool flag = true; if (flag) { return (a: 1, b: 2); } else { if (flag) { return (a: 1, c: 3); } else { return (a: 1, d: 4); } } }); } public T M2<T>(System.Func<T> f) { return f(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,43): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int a, int)'. // return (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(11, 43), // (17,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int)'. // return (a: 1, c: 3); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int)").WithLocation(17, 47), // (21,47): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(int a, int)'. // return (a: 1, d: 4); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(int a, int)").WithLocation(21, 47) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("(System.Int32 a, System.Int32) x1", x1.ToTestDisplayString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaTypeInferenceWithDynamic() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @" public class C { public void M() { var x1 = M2(() => { bool flag = true; dynamic d = null; if (flag) { return (a: 1, b: 2); } else { if (flag) { return (a: d, c: 3); } else { return (a: d, d: 4); } } }); } public T M2<T>(System.Func<T> f) { return f(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,43): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(dynamic a, int)'. // return (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(dynamic a, int)").WithLocation(12, 43), // (18,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(dynamic a, int)'. // return (a: d, c: 3); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(dynamic a, int)").WithLocation(18, 47), // (22,47): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(dynamic a, int)'. // return (a: d, d: 4); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(dynamic a, int)").WithLocation(22, 47) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("(dynamic a, System.Int32) x1", x1.ToTestDisplayString()); } [Fact] public void LambdaTypeInferenceFails() { var source = @" public class C { public void M() { var x1 = M2(() => { bool flag = true; dynamic d = null; if (flag) { return (a: 1, b: d); } else { if (flag) { return (a: d, c: 3); } else { return (a: d, d: 4); } } }); } public T M2<T>(System.Func<T> f) { return f(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0411: The type arguments for method 'C.M2<T>(Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var x1 = M2(() => Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(System.Func<T>)").WithLocation(6, 18) ); } [Fact] public void WarnForDroppingNamesInConversion() { var source = @" public class C { public void M() { (int a, int) x1 = (1, b: 2); (int a, string) x2 = (1, b: null); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): warning CS8123: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(int a, int)'. // (int a, int) x1 = (1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(6, 31), // (7,34): warning CS8123: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(int a, string)'. // (int a, string) x2 = (1, b: null); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: null").WithArguments("b", "(int a, string)").WithLocation(7, 34), // (6,22): warning CS0219: The variable 'x1' is assigned but its value is never used // (int a, int) x1 = (1, b: 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 22), // (7,25): warning CS0219: The variable 'x2' is assigned but its value is never used // (int a, string) x2 = (1, b: null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 25) ); } [Fact] public void MethodTypeInferenceMergesTupleNames() { var source = @" public class C { public void M() { var t = M2((a: 1, b: 2), (a: 1, c: 3)); System.Console.Write(t.a); System.Console.Write(t.b); System.Console.Write(t.c); M2((1, 2), (c: 1, d: 3)); M2(new[] { (a: 1, b: 2) }, new[] { (1, 3) }); } public T M2<T>(T x1, T x2) { return x1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,27): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int a, int)'. // var t = M2((a: 1, b: 2), (a: 1, c: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(6, 27), // (6,41): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int)'. // var t = M2((a: 1, b: 2), (a: 1, c: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int)").WithLocation(6, 41), // (8,32): error CS1061: '(int a, int)' does not contain a definition for 'b' and no extension method 'b' accepting a first argument of type '(int a, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(t.b); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b").WithArguments("(int a, int)", "b").WithLocation(8, 32), // (9,32): error CS1061: '(int a, int)' does not contain a definition for 'c' and no extension method 'c' accepting a first argument of type '(int a, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(t.c); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c").WithArguments("(int a, int)", "c").WithLocation(9, 32), // (10,21): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int, int)'. // M2((1, 2), (c: 1, d: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 1").WithArguments("c", "(int, int)").WithLocation(10, 21), // (10,27): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(int, int)'. // M2((1, 2), (c: 1, d: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 3").WithArguments("d", "(int, int)").WithLocation(10, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation1 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().First()); Assert.Equal("(System.Int32 a, System.Int32)", ((IMethodSymbol)invocation1.Symbol).ReturnType.ToTestDisplayString()); var invocation2 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(4).First()); Assert.Equal("(System.Int32, System.Int32)", ((IMethodSymbol)invocation2.Symbol).ReturnType.ToTestDisplayString()); var invocation3 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(5).First()); Assert.Equal("(System.Int32, System.Int32)[]", ((IMethodSymbol)invocation3.Symbol).ReturnType.ToTestDisplayString()); } [Fact] public void MethodTypeInferenceDropsCandidates() { var source = @" public class C { public void M() { M2((a: 1, b: 2), (a: (byte)1, c: (byte)3)); M2(((long)1, b: 2), (c: 1, d: (byte)3)); M2((a: (long)1, b: 2), ((byte)1, 3)); } public T M2<T>(T x1, T x2) { return x1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,39): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int b)'. // M2((a: 1, b: 2), (a: (byte)1, c: (byte)3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: (byte)3").WithArguments("c", "(int a, int b)").WithLocation(6, 39), // (7,30): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, int b)'. // M2(((long)1, b: 2), (c: 1, d: (byte)3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 1").WithArguments("c", "(long, int b)").WithLocation(7, 30), // (7,36): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, int b)'. // M2(((long)1, b: 2), (c: 1, d: (byte)3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: (byte)3").WithArguments("d", "(long, int b)").WithLocation(7, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation1 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().First()); Assert.Equal("(System.Int32 a, System.Int32 b) C.M2<(System.Int32 a, System.Int32 b)>((System.Int32 a, System.Int32 b) x1, (System.Int32 a, System.Int32 b) x2)", invocation1.Symbol.ToTestDisplayString()); var invocation2 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(1).First()); Assert.Equal("(System.Int64, System.Int32 b) C.M2<(System.Int64, System.Int32 b)>((System.Int64, System.Int32 b) x1, (System.Int64, System.Int32 b) x2)", invocation2.Symbol.ToTestDisplayString()); var invocation3 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(2).First()); Assert.Equal("(System.Int64 a, System.Int32 b) C.M2<(System.Int64 a, System.Int32 b)>((System.Int64 a, System.Int32 b) x1, (System.Int64 a, System.Int32 b) x2)", invocation3.Symbol.ToTestDisplayString()); } [Fact] public void MethodTypeInferenceMergesDynamic() { var source = @" public class C { public void M() { (dynamic[] a, object[] b) x1 = (null, null); (object[] a, dynamic[] c) x2 = (null, null); M2(x1, x2); } public void M2<T>(T x1, T x2) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation1 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().First()); Assert.Equal("void C.M2<(dynamic[] a, dynamic[])>((dynamic[] a, dynamic[]) x1, (dynamic[] a, dynamic[]) x2)", invocation1.Symbol.ToTestDisplayString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12267")] [WorkItem(12267, "https://github.com/dotnet/roslyn/issues/12267")] public void ConstraintsAndNames() { var source1 = @" using System.Collections.Generic; public abstract class Base { public abstract void M<T>(T x) where T : IEnumerable<(int a, int b)>; } "; var source2 = @" class Derived : Base { public override void M<T>(T x) { foreach (var y in x) { System.Console.WriteLine(y.a); } } }"; var comp1 = CreateCompilation(source1 + trivial2uple + source2); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib45(source1 + trivial2uple); comp2.VerifyDiagnostics(); // Retargeting (different version of mscorlib) var comp3 = CreateCompilationWithMscorlib46(source2, references: new[] { new CSharpCompilationReference(comp2) }); comp3.VerifyDiagnostics(); // Metadata var comp4 = CreateCompilationWithMscorlib45(source2, references: new[] { comp2.EmitToImageReference() }); comp4.VerifyDiagnostics(); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInReturn() { var source = @" public class Base { public virtual (int a, int b) M1() { return (1, 2); } public virtual (int a, int b) M2() { return (1, 2); } public virtual (int a, int b)[] M3() { return new[] { (1, 2) }; } public virtual System.Nullable<(int a, int b)> M4() { return (1, 2); } public virtual ((int a, int b) c, int d) M5() { return ((1, 2), 3); } public virtual (dynamic a, dynamic b) M6() { return (1, 2); } } public class Derived : Base { public override (int a, int b) M1() { return (1, 2); } public override (int notA, int notB) M2() { return (1, 2); } public override (int notA, int notB)[] M3() { return new[] { (1, 2) }; } public override System.Nullable<(int notA, int notB)> M4() { return (1, 2); } public override ((int notA, int notB) c, int d) M5() { return ((1, 2), 3); } public override (dynamic notA, dynamic) M6() { return (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef, SystemCoreRef }); comp.VerifyDiagnostics( // (14,42): error CS8139: 'Derived.M2()': cannot change tuple element names when overriding inherited member 'Base.M2()' // public override (int notA, int notB) M2() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()").WithLocation(14, 42), // (15,44): error CS8139: 'Derived.M3()': cannot change tuple element names when overriding inherited member 'Base.M3()' // public override (int notA, int notB)[] M3() { return new[] { (1, 2) }; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3()", "Base.M3()").WithLocation(15, 44), // (16,59): error CS8139: 'Derived.M4()': cannot change tuple element names when overriding inherited member 'Base.M4()' // public override System.Nullable<(int notA, int notB)> M4() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()").WithLocation(16, 59), // (17,53): error CS8139: 'Derived.M5()': cannot change tuple element names when overriding inherited member 'Base.M5()' // public override ((int notA, int notB) c, int d) M5() { return ((1, 2), 3); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M5").WithArguments("Derived.M5()", "Base.M5()").WithLocation(17, 53), // (18,45): error CS8139: 'Derived.M6()': cannot change tuple element names when overriding inherited member 'Base.M6()' // public override (dynamic notA, dynamic) M6() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M6").WithArguments("Derived.M6()", "Base.M6()").WithLocation(18, 45) ); var m3 = comp.GetMember<MethodSymbol>("Derived.M3").ReturnType; Assert.Equal("(System.Int32 notA, System.Int32 notB)[]", m3.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IList<(System.Int32 notA, System.Int32 notB)>" }, m3.Interfaces().SelectAsArray(t => t.ToTestDisplayString())); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInReturnUsingTypeArg() { var source = @" public class Base { public virtual (T a, T b) M1<T>() { return (default(T), default(T)); } public virtual (T a, T b) M2<T>() { return (default(T), default(T)); } public virtual (T a, T b)[] M3<T>() { return new[] { (default(T), default(T)) }; } public virtual System.Nullable<(T a, T b)> M4<T>() { return (default(T), default(T)); } public virtual ((T a, T b) c, T d) M5<T>() { return ((default(T), default(T)), default(T)); } public virtual (dynamic a, dynamic b) M6<T>() { return (default(T), default(T)); } } public class Derived : Base { public override (T a, T b) M1<T>() { return (default(T), default(T)); } public override (T notA, T notB) M2<T>() { return (default(T), default(T)); } public override (T notA, T notB)[] M3<T>() { return new[] { (default(T), default(T)) }; } public override System.Nullable<(T notA, T notB)> M4<T>() { return (default(T), default(T)); } public override ((T notA, T notB) c, T d) M5<T>() { return ((default(T), default(T)), default(T)); } public override (dynamic notA, dynamic) M6<T>() { return (default(T), default(T)); } } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (14,38): error CS8139: 'Derived.M2<T>()': cannot change tuple element names when overriding inherited member 'Base.M2<T>()' // public override (T notA, T notB) M2<T>() { return (default(T), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2<T>()", "Base.M2<T>()").WithLocation(14, 38), // (15,40): error CS8139: 'Derived.M3<T>()': cannot change tuple element names when overriding inherited member 'Base.M3<T>()' // public override (T notA, T notB)[] M3<T>() { return new[] { (default(T), default(T)) }; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3<T>()", "Base.M3<T>()").WithLocation(15, 40), // (16,55): error CS8139: 'Derived.M4<T>()': cannot change tuple element names when overriding inherited member 'Base.M4<T>()' // public override System.Nullable<(T notA, T notB)> M4<T>() { return (default(T), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4<T>()", "Base.M4<T>()").WithLocation(16, 55), // (17,47): error CS8139: 'Derived.M5<T>()': cannot change tuple element names when overriding inherited member 'Base.M5<T>()' // public override ((T notA, T notB) c, T d) M5<T>() { return ((default(T), default(T)), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M5").WithArguments("Derived.M5<T>()", "Base.M5<T>()").WithLocation(17, 47), // (18,45): error CS8139: 'Derived.M6<T>()': cannot change tuple element names when overriding inherited member 'Base.M6<T>()' // public override (dynamic notA, dynamic) M6<T>() { return (default(T), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M6").WithArguments("Derived.M6<T>()", "Base.M6<T>()").WithLocation(18, 45) ); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInParameters() { var source = @" public class Base { public virtual void M1((int a, int b) x) { } public virtual void M2((int a, int b)[] x) { } public virtual void M3(System.Nullable<(int a, int b)> x) { } public virtual void M4(((int a, int b) c, int d) x) { } } public class Derived : Base { public override void M1((int notA, int notB) y) { } public override void M2((int notA, int notB)[] x) { } public override void M3(System.Nullable<(int notA, int notB)> x) { } public override void M4(((int notA, int notB) c, int d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,26): error CS8139: 'Derived.M2((int notA, int notB)[])': cannot change tuple element names when overriding inherited member 'Base.M2((int a, int b)[])' // public override void M2((int notA, int notB)[] x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2((int notA, int notB)[])", "Base.M2((int a, int b)[])").WithLocation(12, 26), // (13,26): error CS8139: 'Derived.M3((int notA, int notB)?)': cannot change tuple element names when overriding inherited member 'Base.M3((int a, int b)?)' // public override void M3(System.Nullable<(int notA, int notB)> x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3((int notA, int notB)?)", "Base.M3((int a, int b)?)").WithLocation(13, 26), // (14,26): error CS8139: 'Derived.M4(((int notA, int notB) c, int d))': cannot change tuple element names when overriding inherited member 'Base.M4(((int a, int b) c, int d))' // public override void M4(((int notA, int notB) c, int d) x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4(((int notA, int notB) c, int d))", "Base.M4(((int a, int b) c, int d))").WithLocation(14, 26), // (11,26): error CS8139: 'Derived.M1((int notA, int notB))': cannot change tuple element names when overriding inherited member 'Base.M1((int a, int b))' // public override void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M1").WithArguments("Derived.M1((int notA, int notB))", "Base.M1((int a, int b))").WithLocation(11, 26) ); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInParametersUsingTypeArg() { var source = @" public class Base { public virtual void M1<T>((T a, T b) x) { } public virtual void M2<T>((T a, T b)[] x) { } public virtual void M3<T>(System.Nullable<(T a, T b)> x) { } public virtual void M4<T>(((T a, T b) c, T d) x) { } } public class Derived : Base { public override void M1<T>((T notA, T notB) y) { } public override void M2<T>((T notA, T notB)[] x) { } public override void M3<T>(System.Nullable<(T notA, T notB)> x) { } public override void M4<T>(((T notA, T notB) c, T d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,26): error CS8139: 'Derived.M2<T>((T notA, T notB)[])': cannot change tuple element names when overriding inherited member 'Base.M2<T>((T a, T b)[])' // public override void M2<T>((T notA, T notB)[] x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2<T>((T notA, T notB)[])", "Base.M2<T>((T a, T b)[])").WithLocation(12, 26), // (13,26): error CS8139: 'Derived.M3<T>((T notA, T notB)?)': cannot change tuple element names when overriding inherited member 'Base.M3<T>((T a, T b)?)' // public override void M3<T>(System.Nullable<(T notA, T notB)> x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3<T>((T notA, T notB)?)", "Base.M3<T>((T a, T b)?)").WithLocation(13, 26), // (14,26): error CS8139: 'Derived.M4<T>(((T notA, T notB) c, T d))': cannot change tuple element names when overriding inherited member 'Base.M4<T>(((T a, T b) c, T d))' // public override void M4<T>(((T notA, T notB) c, T d) x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4<T>(((T notA, T notB) c, T d))", "Base.M4<T>(((T a, T b) c, T d))").WithLocation(14, 26), // (11,26): error CS8139: 'Derived.M1<T>((T notA, T notB))': cannot change tuple element names when overriding inherited member 'Base.M1<T>((T a, T b))' // public override void M1<T>((T notA, T notB) y) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M1").WithArguments("Derived.M1<T>((T notA, T notB))", "Base.M1<T>((T a, T b))").WithLocation(11, 26) ); } [Fact] public void OverriddenPropertiesWithDifferentTupleNames() { var source = @" public class Base { public virtual (int a, int b) P1 { get { return (1, 2); } set { } } public virtual (int a, int b)[] P2 { get; set; } public virtual (int a, int b)? P3 { get { return (1, 2); } set { } } public virtual ((int a, int b) c, int d) P4 { get; set; } } public class Derived : Base { public override (int notA, int notB) P1 { get { return (1, 2); } set { } } public override (int notA, int notB)[] P2 { get; set; } public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } public override ((int notA, int notB) c, int d) P4 { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,44): error CS8139: 'Derived.P2': cannot change tuple element names when overriding inherited member 'Base.P2' // public override (int notA, int notB)[] P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P2").WithArguments("Derived.P2", "Base.P2").WithLocation(12, 44), // (12,49): error CS8139: 'Derived.P2.get': cannot change tuple element names when overriding inherited member 'Base.P2.get' // public override (int notA, int notB)[] P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P2.get", "Base.P2.get").WithLocation(12, 49), // (12,54): error CS8139: 'Derived.P2.set': cannot change tuple element names when overriding inherited member 'Base.P2.set' // public override (int notA, int notB)[] P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P2.set", "Base.P2.set").WithLocation(12, 54), // (13,43): error CS8139: 'Derived.P3': cannot change tuple element names when overriding inherited member 'Base.P3' // public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P3").WithArguments("Derived.P3", "Base.P3").WithLocation(13, 43), // (13,48): error CS8139: 'Derived.P3.get': cannot change tuple element names when overriding inherited member 'Base.P3.get' // public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P3.get", "Base.P3.get").WithLocation(13, 48), // (13,71): error CS8139: 'Derived.P3.set': cannot change tuple element names when overriding inherited member 'Base.P3.set' // public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P3.set", "Base.P3.set").WithLocation(13, 71), // (14,53): error CS8139: 'Derived.P4': cannot change tuple element names when overriding inherited member 'Base.P4' // public override ((int notA, int notB) c, int d) P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P4").WithArguments("Derived.P4", "Base.P4").WithLocation(14, 53), // (14,58): error CS8139: 'Derived.P4.get': cannot change tuple element names when overriding inherited member 'Base.P4.get' // public override ((int notA, int notB) c, int d) P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P4.get", "Base.P4.get").WithLocation(14, 58), // (14,63): error CS8139: 'Derived.P4.set': cannot change tuple element names when overriding inherited member 'Base.P4.set' // public override ((int notA, int notB) c, int d) P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P4.set", "Base.P4.set").WithLocation(14, 63), // (11,42): error CS8139: 'Derived.P1': cannot change tuple element names when overriding inherited member 'Base.P1' // public override (int notA, int notB) P1 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P1").WithArguments("Derived.P1", "Base.P1").WithLocation(11, 42), // (11,47): error CS8139: 'Derived.P1.get': cannot change tuple element names when overriding inherited member 'Base.P1.get' // public override (int notA, int notB) P1 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P1.get", "Base.P1.get").WithLocation(11, 47), // (11,70): error CS8139: 'Derived.P1.set': cannot change tuple element names when overriding inherited member 'Base.P1.set' // public override (int notA, int notB) P1 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P1.set", "Base.P1.set").WithLocation(11, 70) ); } [Fact] public void OverriddenEventsWithDifferentTupleNames() { var source = @" using System; public class Base { public virtual event Func<(int a, int b)> E1; public virtual event Func<(int a, int b)> E2; public virtual event Func<(int a, int b)[]> E3; public virtual event Func<((int a, int b) c, int d)> E4; void M() { E1(); E2(); E3(); E4(); } } public class Derived : Base { public override event Func<(int a, int b)> E1; public override event Func<(int notA, int notB)> E2; public override event Func<(int notA, int notB)[]> E3; public override event Func<((int notA, int) c, int d)> E4; void M() { E1(); E2(); E3(); E4(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,54): error CS8139: 'Derived.E2': cannot change tuple element names when overriding inherited member 'Base.E2' // public override event Func<(int notA, int notB)> E2; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E2").WithArguments("Derived.E2", "Base.E2").WithLocation(15, 54), // (15,54): error CS8139: 'Derived.E2.add': cannot change tuple element names when overriding inherited member 'Base.E2.add' // public override event Func<(int notA, int notB)> E2; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E2").WithArguments("Derived.E2.add", "Base.E2.add").WithLocation(15, 54), // (15,54): error CS8139: 'Derived.E2.remove': cannot change tuple element names when overriding inherited member 'Base.E2.remove' // public override event Func<(int notA, int notB)> E2; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E2").WithArguments("Derived.E2.remove", "Base.E2.remove").WithLocation(15, 54), // (16,56): error CS8139: 'Derived.E3': cannot change tuple element names when overriding inherited member 'Base.E3' // public override event Func<(int notA, int notB)[]> E3; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E3").WithArguments("Derived.E3", "Base.E3").WithLocation(16, 56), // (16,56): error CS8139: 'Derived.E3.add': cannot change tuple element names when overriding inherited member 'Base.E3.add' // public override event Func<(int notA, int notB)[]> E3; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E3").WithArguments("Derived.E3.add", "Base.E3.add").WithLocation(16, 56), // (16,56): error CS8139: 'Derived.E3.remove': cannot change tuple element names when overriding inherited member 'Base.E3.remove' // public override event Func<(int notA, int notB)[]> E3; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E3").WithArguments("Derived.E3.remove", "Base.E3.remove").WithLocation(16, 56), // (17,60): error CS8139: 'Derived.E4': cannot change tuple element names when overriding inherited member 'Base.E4' // public override event Func<((int notA, int) c, int d)> E4; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E4").WithArguments("Derived.E4", "Base.E4").WithLocation(17, 60), // (17,60): error CS8139: 'Derived.E4.add': cannot change tuple element names when overriding inherited member 'Base.E4.add' // public override event Func<((int notA, int) c, int d)> E4; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E4").WithArguments("Derived.E4.add", "Base.E4.add").WithLocation(17, 60), // (17,60): error CS8139: 'Derived.E4.remove': cannot change tuple element names when overriding inherited member 'Base.E4.remove' // public override event Func<((int notA, int) c, int d)> E4; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E4").WithArguments("Derived.E4.remove", "Base.E4.remove").WithLocation(17, 60) ); } [Fact] public void HiddenMethodsWithDifferentTupleNames() { var source = @" public class Base { public virtual int M0() { return 0; } public virtual (int a, int b) M1() { return (1, 2); } public virtual (int a, int b)[] M2() { return new[] { (1, 2) }; } public virtual System.Nullable<(int a, int b)> M3() { return null; } public virtual ((int a, int b) c, int d) M4() { return ((1, 2), 3); } } public class Derived : Base { public string M0() { return null; } public (int a, int b) M1() { return (1, 2); } public (int notA, int notB)[] M2() { return new[] { (1, 2) }; } public System.Nullable<(int notA, int notB)> M3() { return null; } public ((int notA, int notB) c, int d) M4() { return ((1, 2), 3); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,27): warning CS0114: 'Derived.M1()' hides inherited member 'Base.M1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public (int a, int b) M1() { return (1, 2); } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M1").WithArguments("Derived.M1()", "Base.M1()").WithLocation(13, 27), // (14,35): warning CS0114: 'Derived.M2()' hides inherited member 'Base.M2()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public (int notA, int notB)[] M2() { return new[] { (1, 2) }; } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M2").WithArguments("Derived.M2()", "Base.M2()").WithLocation(14, 35), // (15,50): warning CS0114: 'Derived.M3()' hides inherited member 'Base.M3()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public System.Nullable<(int notA, int notB)> M3() { return null; } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M3").WithArguments("Derived.M3()", "Base.M3()").WithLocation(15, 50), // (16,44): warning CS0114: 'Derived.M4()' hides inherited member 'Base.M4()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public ((int notA, int notB) c, int d) M4() { return ((1, 2), 3); } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M4").WithArguments("Derived.M4()", "Base.M4()").WithLocation(16, 44), // (12,19): warning CS0114: 'Derived.M0()' hides inherited member 'Base.M0()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public string M0() { return null; } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M0").WithArguments("Derived.M0()", "Base.M0()").WithLocation(12, 19) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void HiddenMethodsWithNoNames() { var source = @" public class Base { public virtual (int a, int b) M1() { return (1, 2); } } public class Derived : Base { public (int, int) M1() { return (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,23): warning CS0114: 'Derived.M1()' hides inherited member 'Base.M1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public (int, int) M1() { return (1, 2); } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M1").WithArguments("Derived.M1()", "Base.M1()").WithLocation(8, 23) ); } [Fact] public void DuplicateMethodDetectionWithDifferentTupleNames() { var source = @" public class C { public void M1((int a, int b) x) { } public void M1((int notA, int notB) x) { } public void M2((int a, int b)[] x) { } public void M2((int notA, int notB)[] x) { } public void M3(System.Nullable<(int a, int b)> x) { } public void M3(System.Nullable<(int notA, int notB)> x) { } public void M4(((int a, int b) c, int d) x) { } public void M4(((int notA, int notB) c, int d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0111: Type 'C' already defines a member called 'M1' with the same parameter types // public void M1((int notA, int notB) x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C").WithLocation(5, 17), // (8,17): error CS0111: Type 'C' already defines a member called 'M2' with the same parameter types // public void M2((int notA, int notB)[] x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C").WithLocation(8, 17), // (11,17): error CS0111: Type 'C' already defines a member called 'M3' with the same parameter types // public void M3(System.Nullable<(int notA, int notB)> x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M3").WithArguments("M3", "C").WithLocation(11, 17), // (14,17): error CS0111: Type 'C' already defines a member called 'M4' with the same parameter types // public void M4(((int notA, int notB) c, int d) x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M4").WithArguments("M4", "C").WithLocation(14, 17) ); } [Fact] public void HiddenMethodParametersWithDifferentTupleNames() { var source = @" public class Base { public virtual void M1((int a, int b) x) { } public virtual void M2((int a, int b)[] x) { } public virtual void M3(System.Nullable<(int a, int b)> x) { } public virtual void M4(((int a, int b) c, int d) x) { } } public class Derived : Base { public void M1((int notA, int notB) y) { } public void M2((int notA, int notB)[] x) { } public void M3(System.Nullable<(int notA, int notB)> x) { } public void M4(((int notA, int notB) c, int d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS0114: 'Derived.M2((int notA, int notB)[])' hides inherited member 'Base.M2((int a, int b)[])'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M2((int notA, int notB)[] x) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M2").WithArguments("Derived.M2((int notA, int notB)[])", "Base.M2((int a, int b)[])").WithLocation(12, 17), // (13,17): warning CS0114: 'Derived.M3((int notA, int notB)?)' hides inherited member 'Base.M3((int a, int b)?)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M3(System.Nullable<(int notA, int notB)> x) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M3").WithArguments("Derived.M3((int notA, int notB)?)", "Base.M3((int a, int b)?)").WithLocation(13, 17), // (14,17): warning CS0114: 'Derived.M4(((int notA, int notB) c, int d))' hides inherited member 'Base.M4(((int a, int b) c, int d))'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M4(((int notA, int notB) c, int d) x) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M4").WithArguments("Derived.M4(((int notA, int notB) c, int d))", "Base.M4(((int a, int b) c, int d))").WithLocation(14, 17), // (11,17): warning CS0114: 'Derived.M1((int notA, int notB))' hides inherited member 'Base.M1((int a, int b))'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M1").WithArguments("Derived.M1((int notA, int notB))", "Base.M1((int a, int b))").WithLocation(11, 17) ); } [Fact] public void ExplicitInterfaceImplementationWithDifferentTupleNames() { var source = @" public interface I0 { void M1((int, int b) x); void M2((int a, int b) x); (int, int b) MR1(); (int a, int b) MR2(); } public class C : I0 { void I0.M1((int notMissing, int b) z) { } void I0.M2((int notA, int notB) z) { } (int notMissing, int b) I0.MR1() { return (1, 2); } (int notA, int notB) I0.MR2() { return (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,13): error CS8141: The tuple element names in the signature of method 'C.I0.M2((int notA, int notB))' must match the tuple element names of interface method 'I0.M2((int a, int b))' (including on the return type). // void I0.M2((int notA, int notB) z) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M2").WithArguments("C.I0.M2((int notA, int notB))", "I0.M2((int a, int b))").WithLocation(12, 13), // (13,32): error CS8141: The tuple element names in the signature of method 'C.I0.MR1()' must match the tuple element names of interface method 'I0.MR1()' (including on the return type). // (int notMissing, int b) I0.MR1() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "MR1").WithArguments("C.I0.MR1()", "I0.MR1()").WithLocation(13, 32), // (14,29): error CS8141: The tuple element names in the signature of method 'C.I0.MR2()' must match the tuple element names of interface method 'I0.MR2()' (including on the return type). // (int notA, int notB) I0.MR2() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "MR2").WithArguments("C.I0.MR2()", "I0.MR2()").WithLocation(14, 29), // (11,13): error CS8141: The tuple element names in the signature of method 'C.I0.M1((int notMissing, int b))' must match the tuple element names of interface method 'I0.M1((int, int b))' (including on the return type). // void I0.M1((int notMissing, int b) z) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M1").WithArguments("C.I0.M1((int notMissing, int b))", "I0.M1((int, int b))").WithLocation(11, 13) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ExplicitInterfaceImplementationWithNoNames() { var source = @" public interface I0 { void M1((int, int b) x); void M2((int a, int b) x); (int, int b) MR1(); (int a, int b) MR2(); (int a, int b) P { get; set; } } public class C : I0 { void I0.M1((int, int) z) { } void I0.M2((int, int) z) { } (int, int) I0.MR1() { return (1, 2); } (int, int) I0.MR2() { return (1, 2); } (int, int) I0.P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void InterfaceHidingAnotherInterfaceWithDifferentTupleNames() { var source = @" public interface I0 { void M2((int a, int b) x); (int a, int b) MR2(); } public interface I1 : I0 { void M2((int notA, int notB) z); (int notA, int notB) MR2(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,26): warning CS0108: 'I1.MR2()' hides inherited member 'I0.MR2()'. Use the new keyword if hiding was intended. // (int notA, int notB) MR2(); Diagnostic(ErrorCode.WRN_NewRequired, "MR2").WithArguments("I1.MR2()", "I0.MR2()").WithLocation(10, 26), // (9,10): warning CS0108: 'I1.M2((int notA, int notB))' hides inherited member 'I0.M2((int a, int b))'. Use the new keyword if hiding was intended. // void M2((int notA, int notB) z); Diagnostic(ErrorCode.WRN_NewRequired, "M2").WithArguments("I1.M2((int notA, int notB))", "I0.M2((int a, int b))").WithLocation(9, 10) ); } [Fact] public void HidingInterfaceMethodsWithDifferentTupleNames() { var source = @" public interface I0 { void M1((int a, int b) x); void M2((int a, int b) x); void M3((int a, int b) x); void M4((int a, int b) x); (int a, int b) M5(); (int a, int b) M6(); } public interface I1 : I0 { void M1((int notA, int notB) x); void M2((int a, int b) x); new void M3((int a, int b) x); new void M4((int notA, int notB) x); (int notA, int notB) M5(); (int a, int b) M6(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,20): warning CS0108: 'I1.M6()' hides inherited member 'I0.M6()'. Use the new keyword if hiding was intended. // (int a, int b) M6(); Diagnostic(ErrorCode.WRN_NewRequired, "M6").WithArguments("I1.M6()", "I0.M6()").WithLocation(18, 20), // (14,10): warning CS0108: 'I1.M2((int a, int b))' hides inherited member 'I0.M2((int a, int b))'. Use the new keyword if hiding was intended. // void M2((int a, int b) x); Diagnostic(ErrorCode.WRN_NewRequired, "M2").WithArguments("I1.M2((int a, int b))", "I0.M2((int a, int b))").WithLocation(14, 10), // (17,26): warning CS0108: 'I1.M5()' hides inherited member 'I0.M5()'. Use the new keyword if hiding was intended. // (int notA, int notB) M5(); Diagnostic(ErrorCode.WRN_NewRequired, "M5").WithArguments("I1.M5()", "I0.M5()").WithLocation(17, 26), // (13,10): warning CS0108: 'I1.M1((int notA, int notB))' hides inherited member 'I0.M1((int a, int b))'. Use the new keyword if hiding was intended. // void M1((int notA, int notB) x); Diagnostic(ErrorCode.WRN_NewRequired, "M1").WithArguments("I1.M1((int notA, int notB))", "I0.M1((int a, int b))").WithLocation(13, 10) ); } [Fact] public void DuplicateInterfaceDetectionWithDifferentTupleNames_01() { var source = @" public interface I0<T> { } public class C1 : I0<(int a, int b)>, I0<(int notA, int notB)> { } public class C2 : I0<(int a, int b)>, I0<(int a, int b)> { } public class C3 : I0<int>, I0<int> { } public class C4<T, U> : I0<(int a, int b)>, I0<(T a, U b)> { } public class C5<T, U> : I0<(int a, int b)>, I0<(T notA, U notB)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0528: 'I0<int>' is already listed in interface list // public class C3 : I0<int>, I0<int> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "I0<int>").WithArguments("I0<int>").WithLocation(5, 28), // (4,39): error CS0528: 'I0<(int a, int b)>' is already listed in interface list // public class C2 : I0<(int a, int b)>, I0<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "I0<(int a, int b)>").WithArguments("I0<(int a, int b)>").WithLocation(4, 39), // (3,14): error CS8140: 'I0<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I0<(int a, int b)>'. // public class C1 : I0<(int a, int b)>, I0<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I0<(int notA, int notB)>", "I0<(int a, int b)>", "C1").WithLocation(3, 14), // (6,14): error CS0695: 'C4<T, U>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T a, U b)>' because they may unify for some type parameter substitutions // public class C4<T, U> : I0<(int a, int b)>, I0<(T a, U b)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I0<(int a, int b)>", "I0<(T a, U b)>").WithLocation(6, 14), // (7,14): error CS0695: 'C5<T, U>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T notA, U notB)>' because they may unify for some type parameter substitutions // public class C5<T, U> : I0<(int a, int b)>, I0<(T notA, U notB)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C5").WithArguments("C5<T, U>", "I0<(int a, int b)>", "I0<(T notA, U notB)>").WithLocation(7, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var c1 = nodes.OfType<ClassDeclarationSyntax>().First(); Assert.Equal(2, model.GetDeclaredSymbol(c1).AllInterfaces.Count()); Assert.Equal("I0<(System.Int32 a, System.Int32 b)>", model.GetDeclaredSymbol(c1).AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I0<(System.Int32 notA, System.Int32 notB)>", model.GetDeclaredSymbol(c1).AllInterfaces[1].ToTestDisplayString()); var c2 = nodes.OfType<ClassDeclarationSyntax>().Skip(1).First(); Assert.Equal(1, model.GetDeclaredSymbol(c2).AllInterfaces.Count()); Assert.Equal("I0<(System.Int32 a, System.Int32 b)>", model.GetDeclaredSymbol(c2).AllInterfaces[0].ToTestDisplayString()); var c3 = nodes.OfType<ClassDeclarationSyntax>().Skip(2).First(); Assert.Equal(1, model.GetDeclaredSymbol(c3).AllInterfaces.Count()); Assert.Equal("I0<System.Int32>", model.GetDeclaredSymbol(c3).AllInterfaces[0].ToTestDisplayString()); } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_02() { var source = @" public interface I1<T> { void M(); } public interface I2 : I1<(int a, int b)> { } public interface I3 : I1<(int c, int d)> { } public class C1 : I2, I1<(int c, int d)> { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } public class C2 : I1<(int c, int d)>, I2 { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } public class C3 : I1<(int a, int b)>, I1<(int c, int d)> { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } public class C4 : I2, I3 { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): error CS8140: 'I1<(int c, int d)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I1<(int a, int b)>'. // public class C1 : I2, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I1<(int c, int d)>", "I1<(int a, int b)>", "C1").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(int a, int b)>.M()").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(int c, int d)>.M()").WithLocation(10, 14), // (16,14): error CS8140: 'I1<(int a, int b)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I1<(int c, int d)>'. // public class C2 : I1<(int c, int d)>, I2 Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I1<(int a, int b)>", "I1<(int c, int d)>", "C2").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C2 : I1<(int c, int d)>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(int c, int d)>.M()").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C2 : I1<(int c, int d)>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(int a, int b)>.M()").WithLocation(16, 14), // (22,14): error CS8140: 'I1<(int c, int d)>' is already listed in the interface list on type 'C3' with different tuple element names, as 'I1<(int a, int b)>'. // public class C3 : I1<(int a, int b)>, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C3").WithArguments("I1<(int c, int d)>", "I1<(int a, int b)>", "C3").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C3 : I1<(int a, int b)>, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(int a, int b)>.M()").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C3 : I1<(int a, int b)>, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(int c, int d)>.M()").WithLocation(22, 14), // (28,14): error CS8140: 'I1<(int c, int d)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I1<(int a, int b)>'. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I1<(int c, int d)>", "I1<(int a, int b)>", "C4").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(int a, int b)>.M()").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(int c, int d)>.M()").WithLocation(28, 14) ); var c1 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C1"); var c1Interfaces = c1.Interfaces; var c1AllInterfaces = c1.AllInterfaces; Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2", c1Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c1Interfaces[1].ToTestDisplayString()); Assert.Equal("I2", c1AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c1AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c1AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c1); var c2 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C2"); var c2Interfaces = c2.Interfaces; var c2AllInterfaces = c2.AllInterfaces; Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2Interfaces[0].ToTestDisplayString()); Assert.Equal("I2", c2Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I2", c2AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c2AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c2); var c3 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C3"); var c3Interfaces = c3.Interfaces; var c3AllInterfaces = c3.AllInterfaces; Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c3Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c3AllInterfaces[1].ToTestDisplayString()); assertExplicitInterfaceImplementations(c3); var c4 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C4"); var c4Interfaces = c4.Interfaces; var c4AllInterfaces = c4.AllInterfaces; Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2", c4Interfaces[0].ToTestDisplayString()); Assert.Equal("I3", c4Interfaces[1].ToTestDisplayString()); Assert.Equal("I2", c4AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c4AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I3", c4AllInterfaces[2].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c4AllInterfaces[3].ToTestDisplayString()); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(INamedTypeSymbol c) { var cMabImplementations = ((IMethodSymbol)c.GetMember("I1<(System.Int32a,System.Int32b)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<(System.Int32 a, System.Int32 b)>.M()", cMabImplementations[0].ToTestDisplayString()); var cMcdImplementations = ((IMethodSymbol)c.GetMember("I1<(System.Int32c,System.Int32d)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<(System.Int32 c, System.Int32 d)>.M()", cMcdImplementations[0].ToTestDisplayString()); } } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_03() { var source = @" public interface I1<T> { void M1(); void M2(); } public class C1 : I1<(int a, int b)> { public void M1() => System.Console.WriteLine(""C1.M1""); void I1<(int a, int b)>.M2() => System.Console.WriteLine(""C1.M2""); } public class C2 : C1, I1<(int c, int d)> { new public void M1() => System.Console.WriteLine(""C2.M1""); void I1<(int c, int d)>.M2() => System.Console.WriteLine(""C2.M2""); static void Main() { var x = (C1)new C2(); var y = (I1<(int a, int b)>)x; y.M1(); y.M2(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); Action<ModuleSymbol> validate = (m) => { bool isMetadata = m is PEModuleSymbol; var c1 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(1, c1Interfaces.Length); Assert.Equal(1, c1AllInterfaces.Length); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c1Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c1AllInterfaces[0].ToTestDisplayString()); var c2 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(1, c2Interfaces.Length); Assert.Equal(2, c2AllInterfaces.Length); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c2AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2AllInterfaces[1].ToTestDisplayString()); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M1")).ToTestDisplayString()); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M1")).ToTestDisplayString()); var m2 = (MethodSymbol)((TypeSymbol)c2).GetMember("I1<(System.Int32c,System.Int32d)>.M2"); var m2Implementations = m2.ExplicitInterfaceImplementations; Assert.Equal(1, m2Implementations.Length); Assert.Equal(isMetadata ? "void I1<(System.Int32, System.Int32)>.M2()" : "void I1<(System.Int32 c, System.Int32 d)>.M2()", m2Implementations[0].ToTestDisplayString()); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M2"))); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M2"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C2.M1 C2.M2 "); } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_04() { var source = @" public interface I1<T> { void M(); } public interface I2<I2T> : I1<(I2T a, I2T b)> { } public interface I3<I3T> : I1<(I3T c, I3T d)> { } public class C1<T> : I2<T>, I1<(T c, T d)> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } public class C2<T> : I1<(T c, T d)>, I2<T> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } public class C4<T> : I2<T>, I3<T> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): error CS8140: 'I1<(T c, T d)>' is already listed in the interface list on type 'C1<T>' with different tuple element names, as 'I1<(T a, T b)>'. // public class C1<T> : I2<T>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I1<(T c, T d)>", "I1<(T a, T b)>", "C1<T>").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(T a, T b)>.M()").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(T c, T d)>.M()").WithLocation(10, 14), // (16,14): error CS8140: 'I1<(T a, T b)>' is already listed in the interface list on type 'C2<T>' with different tuple element names, as 'I1<(T c, T d)>'. // public class C2<T> : I1<(T c, T d)>, I2<T> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I1<(T a, T b)>", "I1<(T c, T d)>", "C2<T>").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C2<T> : I1<(T c, T d)>, I2<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(T c, T d)>.M()").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C2<T> : I1<(T c, T d)>, I2<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(T a, T b)>.M()").WithLocation(16, 14), // (22,14): error CS8140: 'I1<(T c, T d)>' is already listed in the interface list on type 'C3<T>' with different tuple element names, as 'I1<(T a, T b)>'. // public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C3").WithArguments("I1<(T c, T d)>", "I1<(T a, T b)>", "C3<T>").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(T a, T b)>.M()").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(T c, T d)>.M()").WithLocation(22, 14), // (28,14): error CS8140: 'I1<(T c, T d)>' is already listed in the interface list on type 'C4<T>' with different tuple element names, as 'I1<(T a, T b)>'. // public class C4<T> : I2<T>, I3<T> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I1<(T c, T d)>", "I1<(T a, T b)>", "C4<T>").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(T a, T b)>.M()").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(T c, T d)>.M()").WithLocation(28, 14) ); var c1 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C1`1"); var c1Interfaces = c1.Interfaces; var c1AllInterfaces = c1.AllInterfaces; Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2<T>", c1Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c1Interfaces[1].ToTestDisplayString()); Assert.Equal("I2<T>", c1AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c1AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c1AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c1); var c2 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C2`1"); var c2Interfaces = c2.Interfaces; var c2AllInterfaces = c2.AllInterfaces; Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<(T c, T d)>", c2Interfaces[0].ToTestDisplayString()); Assert.Equal("I2<T>", c2Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c2AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I2<T>", c2AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c2AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c2); var c3 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C3`1"); var c3Interfaces = c3.Interfaces; var c3AllInterfaces = c3.AllInterfaces; Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<(T a, T b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c3Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c3AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c3AllInterfaces[1].ToTestDisplayString()); assertExplicitInterfaceImplementations(c3); var c4 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C4`1"); var c4Interfaces = c4.Interfaces; var c4AllInterfaces = c4.AllInterfaces; Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2<T>", c4Interfaces[0].ToTestDisplayString()); Assert.Equal("I3<T>", c4Interfaces[1].ToTestDisplayString()); Assert.Equal("I2<T>", c4AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c4AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I3<T>", c4AllInterfaces[2].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c4AllInterfaces[3].ToTestDisplayString()); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(INamedTypeSymbol c) { var cMabImplementations = ((IMethodSymbol)c.GetMember("I1<(Ta,Tb)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<(T a, T b)>.M()", cMabImplementations[0].ToTestDisplayString()); var cMcdImplementations = ((IMethodSymbol)c.GetMember("I1<(Tc,Td)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<(T c, T d)>.M()", cMcdImplementations[0].ToTestDisplayString()); } } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_05() { var source = @" public interface I1<T> { void M(); } public class C3<T, U> : I1<(T a, T b)>, I1<(U c, U d)> { void I1<(T a, T b)>.M(){} void I1<(U c, U d)>.M(){} } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS0695: 'C3<T, U>' cannot implement both 'I1<(T a, T b)>' and 'I1<(U c, U d)>' because they may unify for some type parameter substitutions // public class C3<T, U> : I1<(T a, T b)>, I1<(U c, U d)> Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I1<(T a, T b)>", "I1<(U c, U d)>").WithLocation(7, 14) ); var c3 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C3`2"); var c3Interfaces = c3.Interfaces; var c3AllInterfaces = c3.AllInterfaces; Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<(T a, T b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(U c, U d)>", c3Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c3AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(U c, U d)>", c3AllInterfaces[1].ToTestDisplayString()); assertExplicitInterfaceImplementations(c3); void assertExplicitInterfaceImplementations(INamedTypeSymbol c) { var cMabImplementations = ((IMethodSymbol)c.GetMember("I1<(Ta,Tb)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<(T a, T b)>.M()", cMabImplementations[0].ToTestDisplayString()); var cMcdImplementations = ((IMethodSymbol)c.GetMember("I1<(Uc,Ud)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<(U c, U d)>.M()", cMcdImplementations[0].ToTestDisplayString()); } } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_06() { var source = @" public interface I1<T> { void M(); } public class C3 : I1<(int a, int b)> { void I1<(int c, int d)>.M(){} } public class C4 : I1<(int c, int d)> { void I1<(int c, int d)>.M(){} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,10): error CS0540: 'C3.I1<(int c, int d)>.M()': containing type does not implement interface 'I1<(int c, int d)>' // void I1<(int c, int d)>.M(){} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<(int c, int d)>").WithArguments("C3.I1<(int c, int d)>.M()", "I1<(int c, int d)>").WithLocation(9, 10) ); var c3 = comp.GetTypeByMetadataName("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3AllInterfaces[0].ToTestDisplayString()); var mImplementations = ((MethodSymbol)c3.GetMember("I1<(System.Int32c,System.Int32d)>.M")).GetPublicSymbol().ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal("void I1<(System.Int32 c, System.Int32 d)>.M()", mImplementations[0].ToTestDisplayString()); Assert.Equal("void C3.I1<(System.Int32 c, System.Int32 d)>.M()", c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M")).ToTestDisplayString()); Assert.Equal("void C3.I1<(System.Int32 c, System.Int32 d)>.M()", c3.FindImplementationForInterfaceMember(comp.GetTypeByMetadataName("C4").InterfacesNoUseSiteDiagnostics()[0].GetMember("M")).ToTestDisplayString()); } [Fact] public void AccessCheckLooksInsideTuples() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } public class C { (C2.C3, int) M() { throw new System.Exception(); } } public class C2 { private class C3 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0122: 'C2.C3' is inaccessible due to its protection level // (C2.C3, int) M() { throw new System.Exception(); } Diagnostic(ErrorCode.ERR_BadAccess, "C3").WithArguments("C2.C3").WithLocation(11, 9) ); } [Fact] public void AccessCheckLooksInsideTuples2() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } public class C { public (C2, int) M() { throw new System.Exception(); } private class C2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,22): error CS0050: Inconsistent accessibility: return type '(C.C2, int)' is less accessible than method 'C.M()' // public (C2, int) M() { throw new System.Exception(); } Diagnostic(ErrorCode.ERR_BadVisReturnType, "M").WithArguments("C.M()", "(C.C2, int)").WithLocation(11, 22) ); } [Fact] public void ImplicitInterfaceImplementationWithDifferentTupleNames() { var source = @" public interface I0<T> { T get(); void set(T x); } public class C : I0<(int a, int b)> { public (int notA, int notB) get() { return (1, 2); } public void set((int notA, int notB) y) { } } public class D : I0<(int a, int b)> { public (int a, int b) get() { return (1, 2); } public void set((int a, int b) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): error CS8141: The tuple element names in the signature of method 'C.set((int notA, int notB))' must match the tuple element names of interface method 'I0<(int a, int b)>.set((int a, int b))'. // public void set((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "set").WithArguments("C.set((int notA, int notB))", "I0<(int a, int b)>.set((int a, int b))").WithLocation(10, 17), // (9,33): error CS8141: The tuple element names in the signature of method 'C.get()' must match the tuple element names of interface method 'I0<(int a, int b)>.get()'. // public (int notA, int notB) get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "get").WithArguments("C.get()", "I0<(int a, int b)>.get()").WithLocation(9, 33) ); } [Fact] public void ImplicitAndExplicitInterfaceImplementationWithDifferentTupleNames() { var source = @" public interface I0<T> { T get(); void set(T x); } public class C1 : I0<(int a, int b)> { public (int a, int b) get() { return (1, 2); } public void set((int a, int b) y) { } } public class C2 : C1, I0<(int a, int b)> { (int a, int b) I0<(int a, int b)>.get() { return (1, 2); } void I0<(int a, int b)>.set((int a, int b) y) { } } public class D1 : I0<(int a, int b)> { public (int notA, int notB) get() { return (1, 2); } public void set((int notA, int notB) y) { } } public class D2 : D1, I0<(int notA, int notB)> { (int a, int b) I0<(int a, int b)>.get() { return (1, 2); } void I0<(int a, int b)>.set((int a, int b) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,17): error CS8141: The tuple element names in the signature of method 'D1.set((int notA, int notB))' must match the tuple element names of interface method 'I0<(int a, int b)>.set((int a, int b))' (including on the return type). // public void set((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "set").WithArguments("D1.set((int notA, int notB))", "I0<(int a, int b)>.set((int a, int b))").WithLocation(20, 17), // (19,33): error CS8141: The tuple element names in the signature of method 'D1.get()' must match the tuple element names of interface method 'I0<(int a, int b)>.get()' (including on the return type). // public (int notA, int notB) get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "get").WithArguments("D1.get()", "I0<(int a, int b)>.get()").WithLocation(19, 33), // (25,10): error CS0540: 'D2.I0<(int a, int b)>.set((int a, int b))': containing type does not implement interface 'I0<(int a, int b)>' // void I0<(int a, int b)>.set((int a, int b) y) { } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int a, int b)>").WithArguments("D2.I0<(int a, int b)>.set((int a, int b))", "I0<(int a, int b)>").WithLocation(25, 10), // (24,20): error CS0540: 'D2.I0<(int a, int b)>.get()': containing type does not implement interface 'I0<(int a, int b)>' // (int a, int b) I0<(int a, int b)>.get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int a, int b)>").WithArguments("D2.I0<(int a, int b)>.get()", "I0<(int a, int b)>").WithLocation(24, 20) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ImplicitAndExplicitInterfaceImplementationWithNoNames() { var source = @" public interface I0<T> { T get(); void set(T x); } public class C1 : I0<(int a, int b)> { public (int a, int b) get() { return (1, 2); } public void set((int a, int b) y) { } } public class C2 : C1, I0<(int a, int b)> { (int, int) I0<(int, int)>.get() { return (1, 2); } void I0<(int, int)>.set((int, int) y) { } } public class D1 : I0<(int, int)> { public (int, int) get() { return (1, 2); } public void set((int, int) y) { } } public class D2 : D1, I0<(int, int)> { (int, int) I0<(int, int)>.get() { return (1, 2); } void I0<(int, int)>.set((int, int) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,10): error CS0540: 'C2.I0<(int, int)>.set((int, int))': containing type does not implement interface 'I0<(int, int)>' // void I0<(int, int)>.set((int, int) y) { } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int, int)>").WithArguments("C2.I0<(int, int)>.set((int, int))", "I0<(int, int)>").WithLocation(15, 10), // (14,16): error CS0540: 'C2.I0<(int, int)>.get()': containing type does not implement interface 'I0<(int, int)>' // (int, int) I0<(int, int)>.get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int, int)>").WithArguments("C2.I0<(int, int)>.get()", "I0<(int, int)>").WithLocation(14, 16) ); } [Fact] public void PartialMethodsWithDifferentTupleNames() { var source = @" public partial class C { partial void M1((int a, int b) x); partial void M2((int a, int b) x); partial void M3((int a, int b) x); } public partial class C { partial void M1((int notA, int notB) y) { } partial void M2((int, int) y) { } partial void M3((int a, int b) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS8142: Both partial method declarations, 'C.M1((int a, int b))' and 'C.M1((int notA, int notB))', must use the same tuple element names. // partial void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentTupleNames, "M1").WithArguments("C.M1((int a, int b))", "C.M1((int notA, int notB))").WithLocation(10, 18), // (10,18): warning CS8826: Partial method declarations 'void C.M1((int a, int b) x)' and 'void C.M1((int notA, int notB) y)' have signature differences. // partial void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M1").WithArguments("void C.M1((int a, int b) x)", "void C.M1((int notA, int notB) y)").WithLocation(10, 18), // (11,18): error CS8142: Both partial method declarations, 'C.M2((int a, int b))' and 'C.M2((int, int))', must use the same tuple element names. // partial void M2((int, int) y) { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentTupleNames, "M2").WithArguments("C.M2((int a, int b))", "C.M2((int, int))").WithLocation(11, 18), // (11,18): warning CS8826: Partial method declarations 'void C.M2((int a, int b) x)' and 'void C.M2((int, int) y)' have signature differences. // partial void M2((int, int) y) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M2").WithArguments("void C.M2((int a, int b) x)", "void C.M2((int, int) y)").WithLocation(11, 18), // (12,18): warning CS8826: Partial method declarations 'void C.M3((int a, int b) x)' and 'void C.M3((int a, int b) y)' have signature differences. // partial void M3((int a, int b) y) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M3").WithArguments("void C.M3((int a, int b) x)", "void C.M3((int a, int b) y)").WithLocation(12, 18) ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseInterfaces() { var source = @" public interface I0<T> { } public partial class C : I0<(int a, int b)> { } public partial class C : I0<(int notA, int notB)> { } public partial class C : I0<(int, int)> { } public partial class D : I0<(int a, int b)> { } public partial class D : I0<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,22): error CS8140: 'I0<(int notA, int notB)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I0<(int a, int b)>'. // public partial class C : I0<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I0<(int notA, int notB)>", "I0<(int a, int b)>", "C").WithLocation(3, 22), // (3,22): error CS8140: 'I0<(int, int)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I0<(int a, int b)>'. // public partial class C : I0<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I0<(int, int)>", "I0<(int a, int b)>", "C").WithLocation(3, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseTypes() { var source = @" public class Base<T> { } public partial class C1 : Base<(int a, int b)> { } public partial class C1 : Base<(int notA, int notB)> { } public partial class C2 : Base<(int a, int b)> { } public partial class C2 : Base<(int, int)> { } public partial class C3 : Base<(int a, int b)> { } public partial class C3 : Base<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,22): error CS0263: Partial declarations of 'C2' must not specify different base classes // public partial class C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 22), // (3,22): error CS0263: Partial declarations of 'C1' must not specify different base classes // public partial class C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 22) ); } [Fact] public void IndirectInterfaceBasesWithDifferentTupleNames() { var source = @" public interface I0<T> { } public interface I1 : I0<(int a, int b)> { } public interface I2 : I0<(int notA, int notB)> { } public interface I3 : I0<(int a, int b)> { } public class C : I1, I2 { } public class D : I1, I3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8140: 'I0<(int notA, int notB)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I0<(int a, int b)>'. // public class C : I1, I2 { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I0<(int notA, int notB)>", "I0<(int a, int b)>", "C").WithLocation(7, 14) ); } [Fact] public void InterfaceUnification() { var source = @" public interface I0<T1> { } public class C1<T2> : I0<(int, int)>, I0<(T2, T2)> { } public class C2<T2> : I0<(int, int)>, I0<System.ValueTuple<T2, T2>> { } public class C3<T2> : I0<(int a, int b)>, I0<(T2, T2)> { } public class C4<T2> : I0<(int a, int b)>, I0<(T2 a, T2 b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS0695: 'C4<T2>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T2 a, T2 b)>' because they may unify for some type parameter substitutions // public class C4<T2> : I0<(int a, int b)>, I0<(T2 a, T2 b)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T2>", "I0<(int a, int b)>", "I0<(T2 a, T2 b)>").WithLocation(6, 14), // (3,14): error CS0695: 'C1<T2>' cannot implement both 'I0<(int, int)>' and 'I0<(T2, T2)>' because they may unify for some type parameter substitutions // public class C1<T2> : I0<(int, int)>, I0<(T2, T2)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T2>", "I0<(int, int)>", "I0<(T2, T2)>").WithLocation(3, 14), // (5,14): error CS0695: 'C3<T2>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T2, T2)>' because they may unify for some type parameter substitutions // public class C3<T2> : I0<(int a, int b)>, I0<(T2, T2)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T2>", "I0<(int a, int b)>", "I0<(T2, T2)>").WithLocation(5, 14), // (4,14): error CS0695: 'C2<T2>' cannot implement both 'I0<(int, int)>' and 'I0<(T2, T2)>' because they may unify for some type parameter substitutions // public class C2<T2> : I0<(int, int)>, I0<System.ValueTuple<T2, T2>> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T2>", "I0<(int, int)>", "I0<(T2, T2)>").WithLocation(4, 14) ); } [Fact] public void ConversionToBase() { var source = @" public class Base<T> { } public class Derived : Base<(int a, int b)> { public static explicit operator Base<(int, int)>(Derived x) { return null; } public static explicit operator Derived(Base<(int, int)> x) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed // public static explicit operator Derived(Base<(int, int)> x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37), // (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed // public static explicit operator Base<(int, int)>(Derived x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37) ); } [Fact] public void InterfaceUnification2() { var source = @" public interface I0<T1> { } public class Derived<T> : I0<Derived<(T, T)>>, I0<T> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); // Didn't run out of memory in trying to substitute T with Derived<(T, T)> in a loop } [Fact] public void AmbiguousExtensionMethodWithDifferentTupleNames() { var source = @" public static class C1 { public static void M(this string self, (int, int) x) { System.Console.Write($""C1.M({x}) ""); } } public static class C2 { public static void M(this string self, (int a, int b) x) { System.Console.Write($""C2.M({x}) ""); } } public static class C3 { public static void M(this string self, (int c, int d) x) { System.Console.Write($""C3.M({x}) ""); } } public class D { public static void Main() { ""string"".M((1, 1)); ""string"".M((a: 1, b: 1)); ""string"".M((c: 1, d: 1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,18): error CS0121: The call is ambiguous between the following methods or properties: 'C1.M(string, (int, int))' and 'C2.M(string, (int a, int b))' // "string".M((1, 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C1.M(string, (int, int))", "C2.M(string, (int a, int b))").WithLocation(18, 18), // (19,18): error CS0121: The call is ambiguous between the following methods or properties: 'C1.M(string, (int, int))' and 'C2.M(string, (int a, int b))' // "string".M((a: 1, b: 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C1.M(string, (int, int))", "C2.M(string, (int a, int b))").WithLocation(19, 18), // (20,18): error CS0121: The call is ambiguous between the following methods or properties: 'C1.M(string, (int, int))' and 'C2.M(string, (int a, int b))' // "string".M((c: 1, d: 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C1.M(string, (int, int))", "C2.M(string, (int a, int b))").WithLocation(20, 18) ); } [Fact] public void InheritFromMetadataWithDifferentNames() { const string ilSource = @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] // = (int a, int b) .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base::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 [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Base::.ctor } // end of class Base .class public auto ansi beforefieldinit Base2 extends Base { .method public hidebysig virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] // = (int notA, int notB) .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 04 6e 6f 74 41 04 6e 6f 74 42 00 00 ) // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base2::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 Base::.ctor() IL_0006: nop IL_0007: ret } // end of method Base2::.ctor } // end of class Base2 "; string sourceWithMatchingNames = @" public class C : Base2 { public override (int notA, int notB) M() { return (1, 2); } }"; var compMatching = CreateCompilationWithILAndMscorlib40(sourceWithMatchingNames, ilSource, targetFramework: TargetFramework.Mscorlib46Extended, options: TestOptions.DebugDll); compMatching.VerifyEmitDiagnostics(); string sourceWithDifferentNames1 = @" public class C : Base2 { public override (int a, int b) M() { return (1, 2); } }"; var compDifferent1 = CreateCompilationWithILAndMscorlib40(sourceWithDifferentNames1, ilSource, targetFramework: TargetFramework.Mscorlib46Extended, options: TestOptions.DebugDll); compDifferent1.VerifyDiagnostics( // (4,36): error CS8139: 'C.M()': cannot change tuple element names when overriding inherited member 'Base2.M()' // public override (int a, int b) M() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("C.M()", "Base2.M()").WithLocation(4, 36) ); string sourceWithDifferentNames2 = @" public class C : Base2 { public override (int, int) M() { return (1, 2); } }"; var compDifferent2 = CreateCompilationWithILAndMscorlib40(sourceWithDifferentNames2, ilSource, targetFramework: TargetFramework.Mscorlib46Extended, options: TestOptions.DebugDll); compDifferent2.VerifyDiagnostics(); } [Fact] public void TupleNamesInAnonymousTypes() { var source = @" public class C { public static void Main() { var x1 = new { Tuple = (a: 1, b: 2) }; var x2 = new { Tuple = (c: 1, 2) }; x2 = x1; System.Console.Write(x1.Tuple.a); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("<anonymous type: (System.Int32 a, System.Int32 b) Tuple> x1", model.GetDeclaredSymbol(x1).ToTestDisplayString()); var x2 = nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First(); Assert.Equal("<anonymous type: (System.Int32 c, System.Int32) Tuple> x2", model.GetDeclaredSymbol(x2).ToTestDisplayString()); } [Fact] public void OverriddenPropertyWithDifferentTupleNamesInReturn() { var source = @" public class Base { public virtual (int a, int b) P1 { get; set; } public virtual (int a, int b) P2 { get; set; } public virtual (int a, int b)[] P3 { get; set; } public virtual System.Nullable<(int a, int b)> P4 { get; set; } public virtual ((int a, int b) c, int d) P5 { get; set; } public virtual (dynamic a, dynamic b) P6 { get; set; } } public class Derived : Base { public override (int a, int b) P1 { get; set; } public override (int notA, int notB) P2 { get; set; } public override (int notA, int notB)[] P3 { get; set; } public override System.Nullable<(int notA, int notB)> P4 { get; set; } public override ((int notA, int notB) c, int d) P5 { get; set; } public override (dynamic notA, dynamic) P6 { get; set; } } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (14,42): error CS8139: 'Derived.P2': cannot change tuple element names when overriding inherited member 'Base.P2' // public override (int notA, int notB) P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P2").WithArguments("Derived.P2", "Base.P2").WithLocation(14, 42), // (14,47): error CS8139: 'Derived.P2.get': cannot change tuple element names when overriding inherited member 'Base.P2.get' // public override (int notA, int notB) P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P2.get", "Base.P2.get").WithLocation(14, 47), // (14,52): error CS8139: 'Derived.P2.set': cannot change tuple element names when overriding inherited member 'Base.P2.set' // public override (int notA, int notB) P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P2.set", "Base.P2.set").WithLocation(14, 52), // (15,44): error CS8139: 'Derived.P3': cannot change tuple element names when overriding inherited member 'Base.P3' // public override (int notA, int notB)[] P3 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P3").WithArguments("Derived.P3", "Base.P3").WithLocation(15, 44), // (15,49): error CS8139: 'Derived.P3.get': cannot change tuple element names when overriding inherited member 'Base.P3.get' // public override (int notA, int notB)[] P3 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P3.get", "Base.P3.get").WithLocation(15, 49), // (15,54): error CS8139: 'Derived.P3.set': cannot change tuple element names when overriding inherited member 'Base.P3.set' // public override (int notA, int notB)[] P3 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P3.set", "Base.P3.set").WithLocation(15, 54), // (16,59): error CS8139: 'Derived.P4': cannot change tuple element names when overriding inherited member 'Base.P4' // public override System.Nullable<(int notA, int notB)> P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P4").WithArguments("Derived.P4", "Base.P4").WithLocation(16, 59), // (16,64): error CS8139: 'Derived.P4.get': cannot change tuple element names when overriding inherited member 'Base.P4.get' // public override System.Nullable<(int notA, int notB)> P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P4.get", "Base.P4.get").WithLocation(16, 64), // (16,69): error CS8139: 'Derived.P4.set': cannot change tuple element names when overriding inherited member 'Base.P4.set' // public override System.Nullable<(int notA, int notB)> P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P4.set", "Base.P4.set").WithLocation(16, 69), // (17,53): error CS8139: 'Derived.P5': cannot change tuple element names when overriding inherited member 'Base.P5' // public override ((int notA, int notB) c, int d) P5 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P5").WithArguments("Derived.P5", "Base.P5").WithLocation(17, 53), // (17,58): error CS8139: 'Derived.P5.get': cannot change tuple element names when overriding inherited member 'Base.P5.get' // public override ((int notA, int notB) c, int d) P5 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P5.get", "Base.P5.get").WithLocation(17, 58), // (17,63): error CS8139: 'Derived.P5.set': cannot change tuple element names when overriding inherited member 'Base.P5.set' // public override ((int notA, int notB) c, int d) P5 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P5.set", "Base.P5.set").WithLocation(17, 63), // (18,45): error CS8139: 'Derived.P6': cannot change tuple element names when overriding inherited member 'Base.P6' // public override (dynamic notA, dynamic) P6 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P6").WithArguments("Derived.P6", "Base.P6").WithLocation(18, 45), // (18,50): error CS8139: 'Derived.P6.get': cannot change tuple element names when overriding inherited member 'Base.P6.get' // public override (dynamic notA, dynamic) P6 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P6.get", "Base.P6.get").WithLocation(18, 50), // (18,55): error CS8139: 'Derived.P6.set': cannot change tuple element names when overriding inherited member 'Base.P6.set' // public override (dynamic notA, dynamic) P6 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P6.set", "Base.P6.set").WithLocation(18, 55) ); } [Fact] public void DefiniteAssignment001() { var source = @" using System; class C { static void Main(string[] args) { (string A, string B) ss; ss.A = ""q""; ss.Item2 = ""w""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, w) "); } [Fact] public void DefiniteAssignment002() { var source = @" using System; class C { static void Main(string[] args) { (string A, string B) ss; ss.A = ""q""; ss.B = ""q""; ss.Item1 = ""w""; ss.Item2 = ""w""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(w, w)"); } [Fact] public void DefiniteAssignment003() { var source = @" using System; class C { static void Main(string[] args) { (string A, (string B, string C) D) ss; ss.A = ""q""; ss.D.B = ""w""; ss.D.C = ""e""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, (w, e)) "); } [Fact] public void DefiniteAssignment004() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.I8 = ""q""; ss.I9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, q, q, q) "); } [Fact] public void DefiniteAssignment005() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.Item1 = ""q""; ss.Item2 = ""q""; ss.Item3 = ""q""; ss.Item4 = ""q""; ss.Item5 = ""q""; ss.Item6 = ""q""; ss.Item7 = ""q""; ss.Item8 = ""q""; ss.Item9 = ""q""; ss.Item10 = ""q""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, q, q, q) "); } [Fact] public void DefiniteAssignment006() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.Item1 = ""q""; ss.I2 = ""q""; ss.Item3 = ""q""; ss.I4 = ""q""; ss.Item5 = ""q""; ss.I6 = ""q""; ss.Item7 = ""q""; ss.I8 = ""q""; ss.Item9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, q, q, q) "); } [Fact] public void DefiniteAssignment007() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.Item1 = ""q""; ss.I2 = ""q""; ss.Item3 = ""q""; ss.I4 = ""q""; ss.Item5 = ""q""; ss.I6 = ""q""; ss.Item7 = ""q""; ss.I8 = ""q""; ss.Item9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss.Rest); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q) "); } [Fact] public void DefiniteAssignment008() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.I8 = ""q""; ss.Item9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss.Rest); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q) "); } [Fact] public void DefiniteAssignment009() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; Assign(out ss.Rest); System.Console.WriteLine(ss); } static void Assign<T>(out T v) { v = default(T); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, , , ) "); } [Fact] public void DefiniteAssignment010() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; Assign(out ss.Rest, (""q"", ""w"", ""e"")); System.Console.WriteLine(ss.I9); } static void Assign<T>(out T r, T v) { r = v; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"w"); } [Fact] public void DefiniteAssignment011() { var source = @" class C { static void Main(string[] args) { if (1.ToString() == 2.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); } else if (1.ToString() == 3.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; // ss.I8 = ""q""; System.Console.WriteLine(ss); } else { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; // ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); // should fail } } } namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { this.Item1 = item1; } } public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; // public TRest Rest; oops, Rest is missing public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; // Rest = rest; } } } " + TestResources.NetFX.ValueTuple.tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "comp", parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (8,13): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (string I1, Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, @"(string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 13), // (30,13): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (string I1, Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, @"(string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(30, 13), // (52,13): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (string I1, Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, @"(string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(52, 13), // (70,38): error CS0165: Use of unassigned local variable 'ss' // System.Console.WriteLine(ss); // should fail Diagnostic(ErrorCode.ERR_UseDefViolation, "ss").WithArguments("ss").WithLocation(70, 38) ); } [Fact] public void DefiniteAssignment012() { var source = @" class C { static void Main(string[] args) { if (1.ToString() == 2.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); } else if (1.ToString() == 3.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; // ss.I8 = ""q""; System.Console.WriteLine(ss); // should fail1 } else { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; // ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); // should fail2 } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (48,38): error CS0165: Use of unassigned local variable 'ss' // System.Console.WriteLine(ss); // should fail1 Diagnostic(ErrorCode.ERR_UseDefViolation, "ss").WithArguments("ss").WithLocation(48, 38), // (70,38): error CS0165: Use of unassigned local variable 'ss' // System.Console.WriteLine(ss); // should fail2 Diagnostic(ErrorCode.ERR_UseDefViolation, "ss").WithArguments("ss").WithLocation(70, 38) ); } [Fact] public void DefiniteAssignment013() { var source = @" class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.Item1 = ""q""; ss.Item2 = ""q""; ss.Item3 = ""q""; ss.Item4 = ""q""; ss.Item5 = ""q""; ss.Item6 = ""q""; ss.Item7 = ""q""; System.Console.WriteLine(ss.Rest); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (31,34): error CS0170: Use of possibly unassigned field 'Rest' // System.Console.WriteLine(ss.Rest); Diagnostic(ErrorCode.ERR_UseDefViolationField, "ss.Rest").WithArguments("Rest").WithLocation(31, 34) ); } [Fact] public void DefiniteAssignment014() { var source = @" class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.Item2 = ""aa""; System.Console.WriteLine(ss.Item1); System.Console.WriteLine(ss.I2); System.Console.WriteLine(ss.I3); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (21,34): error CS0170: Use of possibly unassigned field 'I3' // System.Console.WriteLine(ss.I3); Diagnostic(ErrorCode.ERR_UseDefViolationField, "ss.I3").WithArguments("I3").WithLocation(21, 34) ); } [Fact] public void DefiniteAssignment015() { var source = @" using System; using System.Threading.Tasks; class C { static void Main(string[] args) { var v = Test().Result; } static async Task<long> Test() { (long a, int b) v1; (byte x, int y) v2; v1.a = 5; v2.x = 5; // no need to persist across await since it is unused after it. System.Console.WriteLine(v2.Item1); await Task.Yield(); // this is assigned and persisted across await return v1.Item1; } } " + trivial2uple + tupleattributes_cs; var verifier = CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib46, expectedOutput: @"5", options: TestOptions.ReleaseExe); // NOTE: !!! There should be NO IL local for " (long a, int b) v1 " , it should be captured instead // NOTE: !!! There should be an IL local for " (byte x, int y) v2 " , it should not be captured verifier.VerifyIL("C.<Test>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 193 (0xc1) .maxstack 3 .locals init (int V_0, long V_1, System.ValueTuple<byte, int> V_2, //v2 System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3, System.Runtime.CompilerServices.YieldAwaitable V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: ldarg.0 IL_000b: ldflda ""System.ValueTuple<long, int> C.<Test>d__1.<v1>5__2"" IL_0010: ldc.i4.5 IL_0011: conv.i8 IL_0012: stfld ""long System.ValueTuple<long, int>.Item1"" IL_0017: ldloca.s V_2 IL_0019: ldc.i4.5 IL_001a: stfld ""byte System.ValueTuple<byte, int>.Item1"" IL_001f: ldloc.2 IL_0020: ldfld ""byte System.ValueTuple<byte, int>.Item1"" IL_0025: call ""void System.Console.WriteLine(int)"" IL_002a: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_002f: stloc.s V_4 IL_0031: ldloca.s V_4 IL_0033: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0038: stloc.3 IL_0039: ldloca.s V_3 IL_003b: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int C.<Test>d__1.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.3 IL_004d: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long> C.<Test>d__1.<>t__builder"" IL_0058: ldloca.s V_3 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1)"" IL_0060: leave.s IL_00c0 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1.<>u__1"" IL_0068: stloc.3 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int C.<Test>d__1.<>1__state"" IL_007e: ldloca.s V_3 IL_0080: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0085: ldarg.0 IL_0086: ldflda ""System.ValueTuple<long, int> C.<Test>d__1.<v1>5__2"" IL_008b: ldfld ""long System.ValueTuple<long, int>.Item1"" IL_0090: stloc.1 IL_0091: leave.s IL_00ac } catch System.Exception { IL_0093: stloc.s V_5 IL_0095: ldarg.0 IL_0096: ldc.i4.s -2 IL_0098: stfld ""int C.<Test>d__1.<>1__state"" IL_009d: ldarg.0 IL_009e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long> C.<Test>d__1.<>t__builder"" IL_00a3: ldloc.s V_5 IL_00a5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long>.SetException(System.Exception)"" IL_00aa: leave.s IL_00c0 } IL_00ac: ldarg.0 IL_00ad: ldc.i4.s -2 IL_00af: stfld ""int C.<Test>d__1.<>1__state"" IL_00b4: ldarg.0 IL_00b5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long> C.<Test>d__1.<>t__builder"" IL_00ba: ldloc.1 IL_00bb: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long>.SetResult(long)"" IL_00c0: ret } "); } [Fact] public void StructInStruct() { var source = @" public struct S { public (S, S) field; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,19): error CS0523: Struct member 'S.field' of type '(S, S)' causes a cycle in the struct layout // public (S, S) field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("S.field", "(S, S)").WithLocation(4, 19) ); } [Fact] public void RetargetTupleErrorType() { var lib_cs = @" public class A { public static (int, int) M() { return (1, 2); } } "; var source = @" public class B { void M2() { return A.M(); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: s_valueTupleRefs); lib.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, references: new[] { lib.ToMetadataReference() }); comp.VerifyDiagnostics( // (4,24): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. // void M2() { return A.M(); } Diagnostic(ErrorCode.ERR_NoTypeDef, "A.M").WithArguments("(, )", "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").WithLocation(4, 24) ); var methodM = comp.GetMember<MethodSymbol>("A.M"); Assert.IsType<RetargetingMethodSymbol>(methodM); Assert.Equal("(System.Int32, System.Int32)[missing]", methodM.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.IsType<ConstructedErrorTypeSymbol>(methodM.ReturnType); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>(methodM.ReturnType.OriginalDefinition); Assert.True(methodM.ReturnType.IsTupleType); Assert.True(methodM.ReturnType.IsErrorType()); foreach (var item in methodM.ReturnType.TupleElements) { Assert.IsType<TupleErrorFieldSymbol>(item); Assert.False(item.IsExplicitlyNamedTupleElement); } } [Fact] public void RetargetTupleErrorType_WithNames() { var lib_cs = @" public class A { public static (int Item1, int Bob) M() { return (1, 2); } } "; var source = @" public class B { void M2() { return A.M(); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: s_valueTupleRefs); lib.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, references: new[] { lib.ToMetadataReference() }); comp.VerifyDiagnostics( // (4,24): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. // void M2() { return A.M(); } Diagnostic(ErrorCode.ERR_NoTypeDef, "A.M").WithArguments("(, )", "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").WithLocation(4, 24) ); var methodM = comp.GetMember<MethodSymbol>("A.M"); Assert.IsType<RetargetingMethodSymbol>(methodM); Assert.Equal("(System.Int32 Item1, System.Int32 Bob)[missing]", methodM.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.IsType<ConstructedErrorTypeSymbol>(methodM.ReturnType); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>(methodM.ReturnType.OriginalDefinition); Assert.True(methodM.ReturnType.IsTupleType); Assert.True(methodM.ReturnType.IsErrorType()); foreach (var item in methodM.ReturnType.TupleElements) { Assert.IsType<TupleErrorFieldSymbol>(item); Assert.True(item.IsExplicitlyNamedTupleElement); } } [Fact, WorkItem(13088, "https://github.com/dotnet/roslyn/issues/13088")] public void AssignNullWithMissingValueTuple() { var source = @" public class S { (int, int) t = null; } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (4,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) t = null; Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(4, 5) ); } [Fact, WorkItem(11302, "https://github.com/dotnet/roslyn/issues/11302")] public void CrashInVisitCallReceiverOnBadTupleSyntax() { var source1 = @" public static class C1 { public void M1(this int x, (int, int))) { System.Console.WriteLine(""M1""); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public static class C2 { public void M1(this int x, (int, int))) { System.Console.WriteLine(""M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1", parseOptions: TestOptions.Regular.WithTuplesFeature()); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2", parseOptions: TestOptions.Regular.WithTuplesFeature()); var source = @" class C3 { public static void Main() { int x = 0; x.M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular.WithTuplesFeature(), options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,14): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // x.M1((1, 1)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) ); } [Fact, WorkItem(12952, "https://github.com/dotnet/roslyn/issues/12952")] public void DropTupleNamesFromArray() { var source = @" public class C { public (int c, int d)[] M() { return new[] { (d: 1, 2) }; } public (int c, int d)[] M2() { return new[] { (d: 1, 2), (d: 1, e: 3), TupleDE() }; } public (int d, int e) TupleDE() { return (1, 3); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(int d, int)'. // return new[] { (d: 1, 2), (d: 1, e: 3), TupleDE() }; Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 3").WithArguments("e", "(int d, int)").WithLocation(10, 42) ); } [Fact, WorkItem(10951, "https://github.com/dotnet/roslyn/issues/10951")] public void ObsoleteValueTuple() { var lib_cs = @" namespace System { [Obsolete] public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) { } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { } } [Obsolete] public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { } public TRest Rest; } } public class D { public static void M2((int, int) x) { } public static void M3((int, string) x) { } } "; var source = @" public class C { void M() { (int, int) x1 = (1, 2); var x2 = (1, 2); var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); var x10 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); D.M2((1, 2)); D.M3((1, null)); System.Console.Write($""{x1} {x2} {x9} {x10}""); } } "; var compLib = CreateCompilationWithMscorlib40(lib_cs, options: TestOptions.ReleaseDll); var comp = CreateCompilationWithMscorlib40(source, references: new[] { compLib.ToMetadataReference() }); comp.VerifyDiagnostics( // (6,9): warning CS0612: '(T1, T2)' is obsolete // (int, int) x1 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(T1, T2)").WithLocation(6, 9), // (6,9): warning CS0612: '(int, int)' is obsolete // (int, int) x1 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(int, int)").WithLocation(6, 9), // (6,25): warning CS0612: '(T1, T2)' is obsolete // (int, int) x1 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2)").WithArguments("(T1, T2)").WithLocation(6, 25), // (7,18): warning CS0612: '(T1, T2)' is obsolete // var x2 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2)").WithArguments("(T1, T2)").WithLocation(7, 18), // (8,18): warning CS0612: '(T1, T2)' is obsolete // var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("(T1, T2)").WithLocation(8, 18), // (8,18): warning CS0612: 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' is obsolete // var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>").WithLocation(8, 18), // (9,19): warning CS0612: 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' is obsolete // var x10 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>").WithLocation(9, 19), // (10,14): warning CS0612: '(T1, T2)' is obsolete // D.M2((1, 2)); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2)").WithArguments("(T1, T2)").WithLocation(10, 14), // (11,14): warning CS0612: '(T1, T2)' is obsolete // D.M3((1, null)); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, null)").WithArguments("(T1, T2)").WithLocation(11, 14) ); } [Fact, WorkItem(10951, "https://github.com/dotnet/roslyn/issues/10951")] public void ObsoleteValueTuple2() { var source = @" public class C { void M() { var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); System.Console.Write(x9); } } namespace System { [Obsolete] public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Rest = rest; } public TRest Rest; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): warning CS0612: '(T1, T2)' is obsolete // var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("(T1, T2)").WithLocation(6, 18) ); } [Fact, WorkItem(13365, "https://github.com/dotnet/roslyn/issues/13365")] public void Bug13365() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } namespace System.Runtime.CompilerServices { public class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } public class C { public (int, int) GetCoordinates() => (0, 0); public (int x, int y) GetCoordinates2() => (0, 0); public void PrintCoordinates() { (int x1, int y1) = GetCoordinates(); (int x2, int y2) = GetCoordinates2(); } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (25,28): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x1, int y1) = GetCoordinates(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates()").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(25, 28), // (25,28): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x1, int y1) = GetCoordinates(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates()").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(25, 28), // (26,28): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x2, int y2) = GetCoordinates2(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates2()").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(26, 28), // (26,28): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x2, int y2) = GetCoordinates2(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates2()").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(26, 28) ); } [Fact, WorkItem(13494, "https://github.com/dotnet/roslyn/issues/13494")] public static void Bug13494() { var source1 = @" class Program { static void Main(string[] args) { var(a, ) } } "; var text = SourceText.From(source1); var startTree = SyntaxFactory.ParseSyntaxTree(text); var finalString = startTree.GetCompilationUnitRoot().ToFullString(); var pos = source1.IndexOf("var(a, )") + 8; var newText = text.WithChanges(new TextChange(new TextSpan(pos, 0), " ")); // add space before closing-paren var newTree = startTree.WithChangedText(newText); var finalText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(newText.ToString(), finalText); // no crash } [Fact] [WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")] public void BadOverloadWithTupleLiteralWithNaturalType() { var source = @" class Program { static void M(int i) { } static void M(string i) { } static void Main() { M((1, 2)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from '(int, int)' to 'int' // M((1, 2)); Diagnostic(ErrorCode.ERR_BadArgType, "(1, 2)").WithArguments("1", "(int, int)", "int").WithLocation(9, 11)); } [Fact] [WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")] public void BadOverloadWithTupleLiteralWithNoNaturalType() { var source = @" class Program { static void M(int i) { } static void M(string i) { } static void Main() { M((1, null)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from '(int, <null>)' to 'int' // M((1, null)); Diagnostic(ErrorCode.ERR_BadArgType, "(1, null)").WithArguments("1", "(int, <null>)", "int").WithLocation(9, 11)); } [Fact] [WorkItem(261049, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/261049")] public void DevDiv261049RegressionTest() { var source = @" class Program { static void Main(string[] args) { var (a,b) = Get(out int x, out int y); Console.WriteLine($""({a.first}, {a.second})""); } static (string first,string second) Get(out int a, out int b) { a = 0; b = 1; return (""a"",""b""); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1061: 'string' does not contain a definition for 'first' and no extension method 'first' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // Console.WriteLine($"({a.first}, {a.second})"); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "first").WithArguments("string", "first").WithLocation(7, 37), // (7,48): error CS1061: 'string' does not contain a definition for 'second' and no extension method 'second' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // Console.WriteLine($"({a.first}, {a.second})"); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "second").WithArguments("string", "second").WithLocation(7, 48), // (7,13): error CS0103: The name 'Console' does not exist in the current context // Console.WriteLine($"({a.first}, {a.second})"); Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console").WithLocation(7, 13) ); } [Fact, WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")] public static void TupleCoVariance() { var source = @" public interface I<out T> { System.ValueTuple<bool, T> M(); } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T>.M()'. 'T' is covariant. // System.ValueTuple<bool, T> M(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "System.ValueTuple<bool, T>").WithArguments("I<T>.M()", "T", "covariant", "invariantly").WithLocation(4, 5) ); } [Fact, WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")] public static void TupleCoVariance2() { var source = @" public interface I<out T> { (bool, T)[] M(); } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T>.M()'. 'T' is covariant. // (bool, T)[] M(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "(bool, T)[]").WithArguments("I<T>.M()", "T", "covariant", "invariantly").WithLocation(4, 5) ); } [Fact, WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")] public static void TupleContraVariance() { var source = @" public interface I<in T> { void M((bool, T)[] x); } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (4,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T>.M((bool, T)[])'. 'T' is contravariant. // void M((bool, T)[] x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "(bool, T)[]").WithArguments("I<T>.M((bool, T)[])", "T", "contravariant", "invariantly").WithLocation(4, 12) ); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(13767, "https://github.com/dotnet/roslyn/issues/13767")] public void TupleInConstant() { var source = @" class C<T> { } class C { static void Main() { const C<(int, int)> c = null; System.Console.Write(c); } }"; var comp = CreateCompilation(source, assemblyName: "comp", options: TestOptions.DebugExe); // emit without pdb using (ModuleMetadata block = ModuleMetadata.CreateFromStream(comp.EmitToStream())) { var reader = block.MetadataReader; AssertEx.SetEqual(new[] { "mscorlib 4.0", "System.ValueTuple 4.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ValueTuple`2, System, AssemblyReference:System.ValueTuple", reader.DumpTypeReferences()); } // emit with pdb comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "", validator: (assembly) => { var reader = assembly.GetMetadataReader(); AssertEx.SetEqual(new[] { "mscorlib 4.0", "System.ValueTuple 4.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ValueTuple`2, System, AssemblyReference:System.ValueTuple", reader.DumpTypeReferences()); }); // no assertion in MetadataWriter } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(13767, "https://github.com/dotnet/roslyn/issues/13767")] public void ConstantTypeFromReferencedAssembly() { var libSource = @" public class ReferencedType { } "; var source = @" class C { static void Main() { const ReferencedType c = null; System.Console.Write(c); } }"; var libComp = CreateCompilationWithMscorlib40(libSource, assemblyName: "lib"); libComp.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, assemblyName: "comp", references: new[] { libComp.EmitToImageReference() }, options: TestOptions.DebugExe); // emit without pdb using (ModuleMetadata block = ModuleMetadata.CreateFromStream(comp.EmitToStream())) { var reader = block.MetadataReader; AssertEx.SetEqual(new[] { "mscorlib 4.0", "lib 0.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ReferencedType, , AssemblyReference:lib", reader.DumpTypeReferences()); } // emit with pdb comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "", validator: (assembly) => { var reader = assembly.GetMetadataReader(); AssertEx.SetEqual(new[] { "mscorlib 4.0", "lib 0.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ReferencedType, , AssemblyReference:lib", reader.DumpTypeReferences()); }); // no assertion in MetadataWriter } [Fact] [WorkItem(13661, "https://github.com/dotnet/roslyn/issues/13661")] public void LongTupleWithPartialNames_Bug13661() { var source = @" using System; class C { static void Main() { var o = (A: 1, 2, C: 3, D: 4, E: 5, F: 6, G: 7, 8, I: 9); Console.Write(o.I); } } "; CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"9", sourceSymbolValidator: (module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = ((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; AssertEx.SetEqual(xSymbol.GetMembers().OfType<IFieldSymbol>().Select(f => f.Name), "A", "C", "D", "E", "F", "G", "I", "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Rest"); }); // no assert hit } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct0() { var source = @" class C { static void Main() { (int a, int b) x; x.Item1 = 1; x.b = 2; // by the language rules tuple x is definitely assigned // since all its elements are definitely assigned System.Console.WriteLine(x); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,9): error CS0165: Use of unassigned local variable 'x' // x.Item1 = 1; Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(7, 9), // (23,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(23, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct1() { var source = @" class C { static void Main() { var x = (1,2,3,4,5,6,7,8,9); System.Console.WriteLine(x); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } public class ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override string ToString() { return base.ToString(); } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (6,13): error CS8182: Predefined type 'ValueTuple`8' must be a struct. // var x = (1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "x = (1,2,3,4,5,6,7,8,9)").WithArguments("ValueTuple`8").WithLocation(6, 13), // (6,13): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // var x = (1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "x = (1,2,3,4,5,6,7,8,9)").WithArguments("ValueTuple`2").WithLocation(6, 13), // (19,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, @"public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(19, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct2() { var source = @" class C { static void Main() { } static void Test2((int a, int b) arg) { } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (20,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(20, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct2i() { var source = @" class C { static void Main() { } static void Test2((int a, int b) arg) { } } namespace System { public interface ValueTuple<T1, T2> { } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1), // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct3() { var source = @" class C { static void Main() { } static void Test1() { (int, int)[] x = null; System.Console.WriteLine(x); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (10,22): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // (int, int)[] x = null; Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "x = null").WithArguments("ValueTuple`2").WithLocation(10, 22), // (23,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(23, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct4() { var source = @" class C { static void Main() { } static (int a, int b) Test2() { return (1, 1); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (8,35): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // static (int a, int b) Test2() { return (1, 1); } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "{ return (1, 1); }").WithArguments("ValueTuple`2").WithLocation(8, 35), // (8,44): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // static (int a, int b) Test2() { return (1, 1); } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "(1, 1)").WithArguments("ValueTuple`2").WithLocation(8, 44), // (18,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(18, 9) ); } [Fact] public void ValueTupleBaseError_NoSystemRuntime() { var source = @"interface I { ((int, int), (int, int)) F(); }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef }); comp.VerifyEmitDiagnostics( // (3,6): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // ((int, int), (int, int)) F(); Diagnostic(ErrorCode.ERR_NoTypeDef, "(int, int)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(3, 6), // (3,18): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // ((int, int), (int, int)) F(); Diagnostic(ErrorCode.ERR_NoTypeDef, "(int, int)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(3, 18), // (3,5): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // ((int, int), (int, int)) F(); Diagnostic(ErrorCode.ERR_NoTypeDef, "((int, int), (int, int))").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(3, 5)); } [WorkItem(16879, "https://github.com/dotnet/roslyn/issues/16879")] [Fact] public void ValueTupleBaseError_MissingReference() { var source0 = @"public class A { } public class B { }"; var comp0 = CreateCompilationWithMscorlib40(source0, assemblyName: "92872377-08d1-4723-8906-a43b03e56ed3"); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"public class C<T> { } namespace System { public class ValueTuple<T1, T2> : A { public ValueTuple(T1 _1, T2 _2) { } } public class ValueTuple<T1, T2, T3> : C<B> { public ValueTuple(T1 _1, T2 _2, T3 _3) { } } }"; var comp1 = CreateCompilationWithMscorlib40(source1, references: new[] { ref0 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"interface I { (int, (int, int), (int, int)) F(); }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ref1 }); comp.VerifyEmitDiagnostics( // error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("B", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("B", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("A", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("A", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); } [Fact] public void ValueTupleBase_AssemblyUnification() { var source0v1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { }"; var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile); var comp0v1 = CreateCompilationWithMscorlib40(source0v1, assemblyName: "A", options: signedDllOptions); comp0v1.VerifyDiagnostics(); var ref0v1 = comp0v1.EmitToImageReference(); var source0v2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A { }"; var comp0v2 = CreateCompilationWithMscorlib40(source0v2, assemblyName: "A", options: signedDllOptions); comp0v2.VerifyDiagnostics(); var ref0v2 = comp0v2.EmitToImageReference(); var source1 = @"public class B : A { }"; var comp1 = CreateCompilationWithMscorlib40(source1, references: new[] { ref0v1 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source2 = @"namespace System { public class ValueTuple<T1, T2> : B { public ValueTuple(T1 _1, T2 _2) { } } }"; var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { ref1, ref0v1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); var source = @"interface I { (int, int) F(); }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ref0v2, ref1, ref2 }); comp.VerifyEmitDiagnostics( // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1), // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1)); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(13472, "https://github.com/dotnet/roslyn/issues/13472")] public void InvalidCastRef() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 _1, T2 _2) { Item1 = _1; Item2 = _2; } } } namespace System.Runtime.CompilerServices { public class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] names) { } } } class C { static void Main() { (int A, int B) x = (1, 2); ref (int, int) y = ref x; } }"; var comp = CompileAndVerify(source); comp.EmitAndVerify(); } [Fact] [WorkItem(14166, "https://github.com/dotnet/roslyn/issues/14166")] public void RefTuple001() { var source = @" class Program { static (int Alice, int Bob)[] arr = new(int Alice, int Bob)[1]; static void Main(string[] args) { RefParam(ref arr[0]); System.Console.WriteLine(arr[0]); RefReturn().Item2 = 42; System.Console.WriteLine(arr[0]); ref (int, int) x = ref arr[0]; x.Item1 = 33; System.Console.WriteLine(arr[0]); } static void RefParam(ref (int, int) p) { p.Item1 = 42; } static ref (int, int) RefReturn() { return ref arr[0]; } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(42, 0) (42, 42) (33, 42)"); comp.VerifyIL("Program.Main", @" { // Code size 110 (0x6e) .maxstack 2 IL_0000: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0005: ldc.i4.0 IL_0006: ldelema ""System.ValueTuple<int, int>"" IL_000b: call ""void Program.RefParam(ref System.ValueTuple<int, int>)"" IL_0010: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0015: ldc.i4.0 IL_0016: ldelem ""System.ValueTuple<int, int>"" IL_001b: box ""System.ValueTuple<int, int>"" IL_0020: call ""void System.Console.WriteLine(object)"" IL_0025: call ""ref System.ValueTuple<int, int> Program.RefReturn()"" IL_002a: ldc.i4.s 42 IL_002c: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0031: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0036: ldc.i4.0 IL_0037: ldelem ""System.ValueTuple<int, int>"" IL_003c: box ""System.ValueTuple<int, int>"" IL_0041: call ""void System.Console.WriteLine(object)"" IL_0046: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_004b: ldc.i4.0 IL_004c: ldelema ""System.ValueTuple<int, int>"" IL_0051: ldc.i4.s 33 IL_0053: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0058: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_005d: ldc.i4.0 IL_005e: ldelem ""System.ValueTuple<int, int>"" IL_0063: box ""System.ValueTuple<int, int>"" IL_0068: call ""void System.Console.WriteLine(object)"" IL_006d: ret } "); comp.VerifyIL("Program.RefReturn", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0005: ldc.i4.0 IL_0006: ldelema ""System.ValueTuple<int, int>"" IL_000b: ret } "); } [Fact] public static void OperatorOverloadingWithDifferentTupleNames() { var source = @" public class B1 { public static bool operator >=((B1 a, B1 b) x1, B1 x2) { return true; } public static bool operator <=((B1 notA, B1 notB) x1, B1 x2) { return true; } } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics(); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [ConditionalFact(typeof(DesktopOnly))] public void RefTupleDynamicDecode001() { string lib = @" namespace ClassLibrary1 { public class C1 { public virtual ref (int, dynamic) Goo(int arg) { return ref new (int, dynamic)[]{(1, arg)}[0]; } } } "; var libComp = CreateCompilationWithMscorlib45AndCSharp(lib, references: s_valueTupleRefs, options: TestOptions.DebugDll); libComp.VerifyDiagnostics(); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo(42); System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, object) Goo(int arg) { return ref base.Goo(arg); } } } "; var comp = CompileAndVerify(source, expectedOutput: "42qq", references: new[] { libComp.ToMetadataReference() }, options: TestOptions.DebugExe, verify: Verification.Fails); var m = (MethodSymbol)(((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo(System.Int32 arg)", m.ToTestDisplayString()); var b = m.OverriddenMethod; Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo(System.Int32 arg)", b.ToTestDisplayString()); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [Fact] public void RefTupleDynamicDecode002() { string lib = @" namespace ClassLibrary1 { public class C1 { public virtual ref (int, dynamic) Goo(int arg) { return ref new (int, dynamic)[]{(1, arg)}[0]; } } } "; var libComp = CreateCompilationWithMscorlib45AndCSharp(lib, options: TestOptions.DebugDll, references: s_valueTupleRefs); libComp.VerifyDiagnostics(); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo(42); System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, object) Goo(int arg) { return ref base.Goo(arg); } } } "; var libCompRef = AssemblyMetadata.CreateFromImage(libComp.EmitToArray()).GetReference(); var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "42qq", references: s_valueTupleRefs.Concat(new[] { libCompRef }).ToArray(), options: TestOptions.DebugExe, verify: Verification.Fails); var m = (IMethodSymbol)(comp.Compilation.GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo(System.Int32 arg)", m.ToTestDisplayString()); var b = m.OverriddenMethod; Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo(System.Int32 arg)", b.ToTestDisplayString()); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_01() { var source = @" partial class C { public static void Main() { Test((X1:1, Y1:2)); var t1 = (X1:3, Y1:4); Test(t1); Test((5, 6)); var t2 = (7, 8); Test(t2); } public static void Test(AA val) { } } class AA { public static implicit operator AA ((int X1, int Y1) x) { System.Console.WriteLine(x); return new AA(); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2) (3, 4) (5, 6) (7, 8)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_02() { var source = @" partial class C { public static void Main() { Test((X1:1, Y1:2)); var t1 = (X1:3, Y1:4); Test(t1); Test((5, 6)); var t2 = (7, 8); Test(t2); } public static void Test(AA? val) { } } struct AA { public static implicit operator AA ((int X1, int Y1) x) { System.Console.WriteLine(x); return new AA(); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2) (3, 4) (5, 6) (7, 8)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_03() { var source = @" partial class C { public static void Main() { (int X1, int Y1)? t1 = (X1:3, Y1:4); Test(t1); (int, int)? t2 = (7, 8); Test(t2); System.Console.WriteLine(""--""); t1 = null; Test(t1); t2 = null; Test(t2); System.Console.WriteLine(""--""); } public static void Test(AA? val) { } } struct AA { public static implicit operator AA ((int X1, int Y1) x) { System.Console.WriteLine(x); return new AA(); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(3, 4) (7, 8) -- --"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_04() { var source = @" partial class C { public static void Main() { Test(new AA()); } public static void Test((int X1, int Y1) val) { System.Console.WriteLine(val); } } class AA { public static implicit operator (int, int) (AA x) { return (1, 2); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_05() { var source = @" partial class C { public static void Main() { Test(new AA()); } public static void Test((int X1, int Y1) val) { System.Console.WriteLine(val); } } class AA { public static implicit operator (int X1, int Y1) (AA x) { return (1, 2); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_06() { var source = @" partial class C { public static void Main() { BB<(int X1, int Y1)>? t1 = new BB<(int X1, int Y1)>(); Test(t1); BB<(int, int)>? t2 = new BB<(int, int)>(); Test(t2); System.Console.WriteLine(""--""); t1 = null; Test(t1); t2 = null; Test(t2); System.Console.WriteLine(""--""); } public static void Test(AA? val) { } } struct AA { public static implicit operator AA (BB<(int X1, int Y1)> x) { System.Console.WriteLine(""implicit operator AA""); return new AA(); } } struct BB<T> { } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"implicit operator AA implicit operator AA -- --"); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [Fact] public void RefTupleDynamicDecode003() { string lib = @" // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System.Core { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) // .{...-.Q .ver 4:0:1:0 } // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit ClassLibrary1.C1 extends [mscorlib]System.Object { .method public hidebysig newslot virtual instance valuetype [System.ValueTuple]System.ValueTuple`2<int32,object>& Goo(int32 arg) cil managed { .param [0] // the dynamic flags array is too short - decoder expects a flag matching ""ref"", but it is missing here. .custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 00 01 00 00 ) // Code size 37 (0x25) .maxstack 5 .locals init (valuetype [System.ValueTuple]System.ValueTuple`2<int32,object>& V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr valuetype [System.ValueTuple]System.ValueTuple`2<int32,object> IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: ldarg.1 IL_000b: box [mscorlib]System.Int32 IL_0010: newobj instance void valuetype [System.ValueTuple]System.ValueTuple`2<int32,object>::.ctor(!0, !1) IL_0015: stelem valuetype [System.ValueTuple]System.ValueTuple`2<int32,object> IL_001a: ldc.i4.0 IL_001b: ldelema valuetype [System.ValueTuple]System.ValueTuple`2<int32,object> IL_0020: stloc.0 IL_0021: br.s IL_0023 IL_0023: ldloc.0 IL_0024: ret } // end of method C1::Goo .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 } // end of class ClassLibrary1.C1 "; var libCompRef = CompileIL(lib); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo(42); System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, dynamic) Goo(int arg) { return ref base.Goo(arg); } } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: (new[] { libCompRef }).Concat(s_valueTupleRefs).ToArray(), options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "42qq", verify: Verification.Fails); var m = (MethodSymbol)(comp.GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, dynamic) ConsoleApplication5.C2.Goo(System.Int32 arg)", m.ToTestDisplayString()); var b = m.OverriddenMethod; // not (int, dynamic), // since dynamic flags were not aligned, we have ignored the flags Assert.Equal("ref (System.Int32, System.Object) ClassLibrary1.C1.Goo(System.Int32 arg)", b.ToTestDisplayString()); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [ConditionalFact(typeof(DesktopOnly))] public void RefTupleDynamicDecode004() { string lib = @" namespace ClassLibrary1 { public class C1 { public virtual ref (int, dynamic) Goo => ref new (int, dynamic)[]{(1, 42)}[0]; } } "; var libComp = CreateCompilationWithMscorlib45AndCSharp(lib, references: s_valueTupleRefs, options: TestOptions.DebugDll); libComp.VerifyDiagnostics(); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo; System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, object) Goo => ref base.Goo; } } "; var libCompRef = AssemblyMetadata.CreateFromImage(libComp.EmitToArray()).GetReference(); var comp = CompileAndVerify(source, expectedOutput: "42qq", references: new[] { libCompRef }, options: TestOptions.DebugExe, verify: Verification.Passes); var m = (PropertySymbol)(((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo { get; }", m.ToTestDisplayString()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo.get", m.GetMethod.ToTestDisplayString()); var b = m.OverriddenProperty; Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo { get; }", b.ToTestDisplayString()); Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo.get", b.GetMethod.ToTestDisplayString()); } [Fact] [WorkItem(14267, "https://github.com/dotnet/roslyn/issues/14267")] public void NoSystemRuntimeFacade() { var source = @" class C { static void M() { var o = (1, 2); } } "; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef }); Assert.Equal(TypeKind.Class, compilation.GetWellKnownType(WellKnownType.System_ValueTuple_T2).TypeKind); compilation.VerifyDiagnostics( // (6,17): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // var o = (1, 2); Diagnostic(ErrorCode.ERR_NoTypeDef, "(1, 2)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(6, 17) ); } [Fact] [WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")] public void Iterator_01() { var source = @" using System; using System.Collections.Generic; public class C { static void Main(string[] args) { foreach (var x in entries()) { Console.WriteLine(x); } } static public IEnumerable<(int, int)> entries() { yield return (1, 2); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2)"); } [Fact] [WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")] public void Iterator_02() { var source = @" using System; using System.Collections.Generic; public class C { public IEnumerable<(int, int)> entries() { yield return (1, 2); } } "; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef }); compilation.VerifyEmitDiagnostics( // (7,24): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // public IEnumerable<(int, int)> entries() Diagnostic(ErrorCode.ERR_NoTypeDef, "(int, int)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(7, 24), // (9,22): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // yield return (1, 2); Diagnostic(ErrorCode.ERR_NoTypeDef, "(1, 2)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(9, 22) ); } [Fact] [WorkItem(14649, "https://github.com/dotnet/roslyn/issues/14649")] public void ParseLongLambda() { string filler = string.Join("\r\n", Enumerable.Range(1, 1000).Select(i => $"int y{i};")); string parameters = string.Join(", ", Enumerable.Range(1, 2000).Select(i => $"int x{i}")); string text = @" class C { " + filler + @" public void M() { N((" + parameters + @") => 1); } } "; // This is designed to trigger a shift of the array of lexed tokens (see AddLexedTokenSlot) while // parsing lambda parameters var tree = SyntaxFactory.ParseSyntaxTree(text, CSharpParseOptions.Default); // no assertion } [Fact] public void UnusedTuple() { string source = @" public class C { void M(int x) { // Warnings int[] array = new int[] { 42 }; unsafe { fixed (int* p = &array[0]) { (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type (string, int*) t2 = (null, p); // implicit tuple literal conversion on a converted tuple literal with a pointer type (string, (int*, int*)) t3 = (null, (p, p)); } } (int, int) t4 = default((int, int)); (int, int) t5 = (1, 2); (string, string) t6 = (null, null); (string, string) t7 = (""hello"", ""world""); (S, (S, S)) t8 = (new S(), (new S(), new S())); (int, int) t9 = ((C, int))(new C(), 2); // implicit tuple conversion with a user conversion on an element (int, int) t10 = (new C(), 2); // implicit tuple literal conversion with a user conversion on an element (int, int) t11 = ((int, int))(((C, int))(new C(), 2)); // explicit tuple conversion with a user conversion on an element (C, C) t12 = (new C(), new C()); (C, (C, C)) t13 = (new C(), (new C(), new C())); (S, (S, S)) t14 = (new S(), (new S() { /* object initializer */ }, new S())); // No warnings (C, int) tuple = (new C(), 2); (int, int) t20 = ((C, int))tuple; (int, int) t21 = tuple; (int, int) t22 = ((int, int))tuple; C c1 = (1, 2); (int, int) intTuple = (1, 2); C c2 = intTuple; int i1 = 1; int i2 = i1; } public static implicit operator int(C c) { return 0; } public static implicit operator C((int, int) t) { return new C(); } } public struct S { } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: s_valueTupleRefs, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (13,18): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(13, 18), // (13,24): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(13, 24), // (13,36): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(13, 36), // (13,39): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(13, 39), // (14,26): error CS0306: The type 'int*' may not be used as a type argument // (string, int*) t2 = (null, p); // implicit tuple literal conversion on a converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(14, 26), // (15,27): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(15, 27), // (15,33): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(15, 33), // (15,53): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(15, 53), // (15,56): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(15, 56), // (13,30): warning CS0219: The variable 't1' is assigned but its value is never used // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t1").WithArguments("t1").WithLocation(13, 30), // (14,32): warning CS0219: The variable 't2' is assigned but its value is never used // (string, int*) t2 = (null, p); // implicit tuple literal conversion on a converted tuple literal with a pointer type Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2").WithLocation(14, 32), // (15,40): warning CS0219: The variable 't3' is assigned but its value is never used // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t3").WithArguments("t3").WithLocation(15, 40), // (19,20): warning CS0219: The variable 't4' is assigned but its value is never used // (int, int) t4 = default((int, int)); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t4").WithArguments("t4").WithLocation(19, 20), // (20,20): warning CS0219: The variable 't5' is assigned but its value is never used // (int, int) t5 = (1, 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t5").WithArguments("t5").WithLocation(20, 20), // (22,26): warning CS0219: The variable 't6' is assigned but its value is never used // (string, string) t6 = (null, null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t6").WithArguments("t6").WithLocation(22, 26), // (23,26): warning CS0219: The variable 't7' is assigned but its value is never used // (string, string) t7 = ("hello", "world"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t7").WithArguments("t7").WithLocation(23, 26), // (24,21): warning CS0219: The variable 't8' is assigned but its value is never used // (S, (S, S)) t8 = (new S(), (new S(), new S())); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t8").WithArguments("t8").WithLocation(24, 21), // (26,20): warning CS0219: The variable 't9' is assigned but its value is never used // (int, int) t9 = ((C, int))(new C(), 2); // implicit tuple conversion with a user conversion on an element Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t9").WithArguments("t9").WithLocation(26, 20), // (27,20): warning CS0219: The variable 't10' is assigned but its value is never used // (int, int) t10 = (new C(), 2); // implicit tuple literal conversion with a user conversion on an element Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t10").WithArguments("t10").WithLocation(27, 20), // (28,20): warning CS0219: The variable 't11' is assigned but its value is never used // (int, int) t11 = ((int, int))(((C, int))(new C(), 2)); // explicit tuple conversion with a user conversion on an element Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t11").WithArguments("t11").WithLocation(28, 20), // (30,16): warning CS0219: The variable 't12' is assigned but its value is never used // (C, C) t12 = (new C(), new C()); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t12").WithArguments("t12").WithLocation(30, 16), // (31,21): warning CS0219: The variable 't13' is assigned but its value is never used // (C, (C, C)) t13 = (new C(), (new C(), new C())); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t13").WithArguments("t13").WithLocation(31, 21), // (32,21): warning CS0219: The variable 't14' is assigned but its value is never used // (S, (S, S)) t14 = (new S(), (new S() { /* object initializer */ }, new S())); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t14").WithArguments("t14").WithLocation(32, 21) ); } [Fact] [WorkItem(14881, "https://github.com/dotnet/roslyn/issues/14881")] [WorkItem(15476, "https://github.com/dotnet/roslyn/issues/15476")] public void TupleElementVsLocal() { var source = @" using System; static class Program { static void Main() { (int elem1, int elem2) tuple; int elem2; tuple = (5, 6); tuple.elem2 = 23; elem2 = 10; Console.WriteLine(tuple.elem2); Console.WriteLine(elem2); } } "; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "elem2").ToArray(); Assert.Equal(4, nodes.Length); Assert.Equal("tuple.elem2 = 23", nodes[0].Parent.Parent.ToString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetSymbolInfo(nodes[0]).Symbol.ToTestDisplayString()); Assert.Equal("elem2 = 10", nodes[1].Parent.ToString()); Assert.Equal("System.Int32 elem2", model.GetSymbolInfo(nodes[1]).Symbol.ToTestDisplayString()); Assert.Equal("(tuple.elem2)", nodes[2].Parent.Parent.Parent.ToString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetSymbolInfo(nodes[2]).Symbol.ToTestDisplayString()); Assert.Equal("(elem2)", nodes[3].Parent.Parent.ToString()); Assert.Equal("System.Int32 elem2", model.GetSymbolInfo(nodes[3]).Symbol.ToTestDisplayString()); var type = tree.GetRoot().DescendantNodes().OfType<TupleTypeSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(type); Assert.Equal("(System.Int32 elem1, System.Int32 elem2)", symbolInfo.Symbol.ToTestDisplayString()); var typeInfo = model.GetTypeInfo(type); Assert.Equal("(System.Int32 elem1, System.Int32 elem2)", typeInfo.Type.ToTestDisplayString()); Assert.Equal(symbolInfo.Symbol, typeInfo.Type); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem1", model.GetDeclaredSymbol(type.Elements.First()).ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetDeclaredSymbol(type.Elements.Last()).ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem1", model.GetDeclaredSymbol((SyntaxNode)type.Elements.First()).ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetDeclaredSymbol((SyntaxNode)type.Elements.Last()).ToTestDisplayString()); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ImplicitIEnumerableImplementationWithDifferentTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { public IEnumerator<(int a, int b)> GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived : Base, IEnumerable<(int notA, int notB)> { public new IEnumerator<(int notA, int notB)> GetEnumerator() { return new DerivedEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<(int notA, int notB)> { bool done = false; public (int notA, int notB) Current { get { return (2, 2); } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { foreach (var x in new Derived()) { Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.Int32 notA, System.Int32 notB)>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var xSymbol = model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single()); Assert.Equal("(System.Int32 notA, System.Int32 notB)", xSymbol.Type.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitIEnumerableImplementationWithDifferentTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { IEnumerator<(int a, int b)> IEnumerable<(int a, int b)>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived : Base, IEnumerable<(int notA, int notB)> { IEnumerator<(int notA, int notB)> IEnumerable<(int notA, int notB)>.GetEnumerator() { return new DerivedEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<(int notA, int notB)> { bool done = false; public (int notA, int notB) Current { get { return (2, 2); } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { foreach (var x in new Derived()) { System.Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.Int32 notA, System.Int32 notB)>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var xSymbol = model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single()); Assert.Equal("(System.Int32 notA, System.Int32 notB)", xSymbol.Type.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericImplicitIEnumerableImplementationUsedWithDifferentTypesAndTupleNames() { var source = @" using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int, int)> { public IEnumerator<(int, int)> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class Derived<T> : Base, IEnumerable<T> { public T state; public new IEnumerator<T> GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { return null; } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { return null; } } } } class C { static void Main() { var collection = new Derived<(string a, string b)>() { state = (""hello"", ""world"") }; foreach (var x in collection) { System.Console.WriteLine(x.a); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32, System.Int32)>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<(System.String a, System.String b)>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32, System.Int32)>", "System.Collections.Generic.IEnumerable<(System.String a, System.String b)>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); CompileAndVerify(comp, expectedOutput: "hello"); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericExplicitIEnumerableImplementationUsedWithDifferentTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { IEnumerator<(int a, int b)> IEnumerable<(int a, int b)>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived<T> : Base, IEnumerable<T> { public T state; IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { var collection = new Derived<(int notA, int notB)>() { state = (42, 43) }; foreach (var x in collection) { System.Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived) as INamedTypeSymbol; Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<(System.Int32 notA, System.Int32 notB)>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.Int32 notA, System.Int32 notB)>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); Assert.Empty(derivedSymbol.GetSymbol().AsUnboundGenericType().AllInterfaces()); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericExplicitIEnumerableImplementationUsedWithoutTuples() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived<T> : Base, IEnumerable<T> { public T state; IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { var collection = new Derived<int>() { state = 42 }; foreach (var x in collection) { System.Console.WriteLine(x); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<System.Int32>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericExplicitIEnumerableImplementationUsedWithDifferentTypesAndTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { IEnumerator<(int a, int b)> IEnumerable<(int a, int b)>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived<T> : Base, IEnumerable<T> { public T state; IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { var collection = new Derived<(string notA, string notB)>() { state = (""hello"", ""world"") }; foreach (var x in collection) { System.Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (35,27): error CS1640: foreach statement cannot operate on variables of type 'Derived<(string notA, string notB)>' because it implements multiple instantiations of 'IEnumerable<T>'; try casting to a specific interface instantiation // foreach (var x in collection) Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "collection").WithArguments("Derived<(string notA, string notB)>", "System.Collections.Generic.IEnumerable<T>").WithLocation(35, 27) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<(System.String notA, System.String notB)>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.String notA, System.String notB)>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); } [Fact] [WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")] public void TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion() { var source = @" interface I1<T> {} class Base<U> where U : I1<(int a, int b)> {} class Derived : Base<I1<(int notA, int notB)>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")] public void TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion2() { var source = @" interface I1<T> {} interface I2<T> : I1<T> {} class Base<U> where U : I1<(int a, int b)> {} class Derived : Base<I2<(int notA, int notB)>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void CanReImplementInterfaceWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } // explicit implementation } class Derived : Base, I<(int notA, int notB)> { public (int notA, int notB) M() { return (3, 4); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void CannotOverrideWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public virtual (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { public override (int notA, int notB) M() { return (3, 4); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,42): error CS8139: 'Derived.M()': cannot change tuple element names when overriding inherited member 'Base.M()' // public override (int notA, int notB) M() { return (3, 4); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("Derived.M()", "Base.M()").WithLocation(12, 42) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void CanShadowWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { public new (int notA, int notB) M() { return (3, 4); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_01() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } // explicit implementation } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(10, 24) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_02() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } // explicit implementation public (int notA, int notB) M() { return (1, 2); } } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(11, 24) ); } [Fact] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_03() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS0535: 'Base' does not implement interface member 'I<(int a, int b)>.M()' // class Base : I<(int a, int b)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int a, int b)>").WithArguments("Base", "I<(int a, int b)>.M()").WithLocation(6, 14), // (9,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(9, 24) ); } [Fact] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_04() { var source1 = @" public interface I<T> { T M(); } public class Base : I<(int a, int b)> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (6,21): error CS0535: 'Base' does not implement interface member 'I<(int a, int b)>.M()' // public class Base : I<(int a, int b)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int a, int b)>").WithArguments("Base", "I<(int a, int b)>.M()").WithLocation(6, 21) ); var source2 = @" class Derived1 : Base, I<(int notA, int notB)> { } class Derived2 : Base, I<(int a, int b)> { } "; var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }); comp2.VerifyDiagnostics( // (2,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(2, 24) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_05() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int notA, int notB)>.M()' (including on the return type). // class Derived1 : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int notA, int notB)>").WithArguments("Base.M()", "I<(int notA, int notB)>.M()").WithLocation(10, 24) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ImplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { // error } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,23): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int notA, int notB)>.M()' (including on the return type). // class Derived : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int notA, int notB)>").WithArguments("Base.M()", "I<(int notA, int notB)>.M()").WithLocation(10, 23) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ImplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames2() { var source = @" interface I<T> { T M(); } class Base { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { // error } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,23): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int notA, int notB)>.M()' (including on the return type). // class Derived : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int notA, int notB)>").WithArguments("Base.M()", "I<(int notA, int notB)>.M()").WithLocation(10, 23) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ImplicitBaseImplementationNotConsideredImplementationForInterfaceWithNoNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int, int)> { // error } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,23): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int, int)>.M()' (including on the return type). // class Derived : Base, I<(int, int)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int, int)>").WithArguments("Base.M()", "I<(int, int)>.M()").WithLocation(10, 23) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ImplicitBaseImplementationWithNoNamesConsideredImplementationForInterface() { var source = @" interface I<T> { T M(); } class Base : I<(int, int)> { public (int, int) M() { return (1, 2); } } class Derived : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ReImplementationAndInference() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { public (int notA, int notB) M() { return (3, 4); } } class C { static void Main() { Base b = new Derived(); var x = Test(b); // tuple names from Base, implementation from Derived System.Console.Write(x.a); } static T Test<T>(I<T> t) { return t.M(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "3"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); Assert.Equal("x", x.Identifier.ToString()); var xSymbol = ((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; Assert.Equal("(System.Int32 a, System.Int32 b)", xSymbol.ToTestDisplayString()); } [Fact] [WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")] public void TupleTypeWithTooFewElements() { var source = @" class C { void M(int x, () y, (int a) z) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,20): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 20), // (4,31): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 31) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var y = tree.GetRoot().DescendantNodes().OfType<TupleTypeSyntax>().ElementAt(0); Assert.Equal("()", y.ToString()); var yType = model.GetTypeInfo(y); Assert.Equal("(?, ?)", yType.Type.ToTestDisplayString()); var z = tree.GetRoot().DescendantNodes().OfType<TupleTypeSyntax>().ElementAt(1); Assert.Equal("(int a)", z.ToString()); var zType = model.GetTypeInfo(z); Assert.Equal("(System.Int32 a, ?)", zType.Type.ToTestDisplayString()); } [Fact] [WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")] public void TupleExpressionWithTooFewElements() { var source = @" class C { object x = (Alice: 1); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8124: Tuple must contain at least two elements. // object x = (Alice: 1); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 25) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(Alice: 1)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int32 Alice, ?)", tupleType.Type.ToTestDisplayString()); } [Fact] [WorkItem(16159, "https://github.com/dotnet/roslyn/issues/16159")] public void ExtensionMethodOnConvertedTuple001() { var source = @" using System; using System.Linq; using System.Collections.Generic; static class C { static IEnumerable<(T, U)> Zip<T, U>(this(IEnumerable<T> xs, IEnumerable<U> ys) source) => source.xs.Zip(source.ys, (x, y) => (x, y)); static void Main() { foreach (var t in Zip((new int[] { 1, 2 }, new byte[] { 3, 4 }))) { System.Console.WriteLine(t); } foreach (var t in (new int[] { 1, 2 }, new byte[] { 3, 4 }).Zip()) { System.Console.WriteLine(t); } var notALiteral = (new int[] { 1, 2 }, new byte[] { 3, 4 }); foreach (var (x, y) in notALiteral.Zip()) { System.Console.WriteLine((x, y)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, 3) (2, 4) (1, 3) (2, 4) (1, 3) (2, 4) "); } [Fact] public void ExtensionMethodOnConvertedTuple002() { var source = @" using System; using System.Collections; static class C { static string M(this(object x, (ValueType, IStructuralComparable) y) self) => self.ToString(); static string M1(this (dynamic x, System.Exception y) self) => self.ToString(); static void Main() { System.Console.WriteLine((""qq"", (Alice: 1, (2, 3))).M()); (dynamic Alice, NullReferenceException Bob) arg = (123, null); System.Console.WriteLine(arg.M1()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (qq, (1, (2, 3))) (123, ) "); } [Fact] public void ExtensionMethodOnConvertedTuple002Err() { var source = @" using System; using System.Collections; static class C { static string M(this(object x, (ValueType, IStructuralComparable) y) self) => self.ToString(); static string GetAwaiter(this (object x, Func<int> y) self) => self.ToString(); static void Main() { System.Console.WriteLine((""qq"", (Alice: 1, (null, 3))).M()); System.Console.WriteLine((""qq"", ()=>1 ).GetAwaiter()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,64): error CS0117: '(string, (int, (<null>, int)))' does not contain a definition for 'M' // System.Console.WriteLine(("qq", (Alice: 1, (null, 3))).M()); Diagnostic(ErrorCode.ERR_NoSuchMember, "M").WithArguments("(string, (int, (<null>, int)))", "M").WithLocation(13, 64), // (15,49): error CS0117: '(string, lambda expression)' does not contain a definition for 'GetAwaiter' // System.Console.WriteLine(("qq", ()=>1 ).GetAwaiter()); Diagnostic(ErrorCode.ERR_NoSuchMember, "GetAwaiter").WithArguments("(string, lambda expression)", "GetAwaiter").WithLocation(15, 49) ); } [Fact] public void ExtensionMethodOnConvertedTuple003() { var source = @" static class C { static string M(this (int x, long y) self) => self.ToString(); static string M1(this (int x, long? y) self) => self.ToString(); static void Main() { // implicit constant conversion System.Console.WriteLine((1, 2).M()); // identity conversion (this one is OK) System.Console.WriteLine((1, 2L).M()); // implicit nullable conversion System.Console.WriteLine((First: 1, Second: 2L).M1()); // null literal conversion System.Console.WriteLine((1, null).M1()); // implicit numeric conversion var notAliteral = (A: 1, B: 2); System.Console.WriteLine(notAliteral.M()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,34): error CS1929: '(int, int)' does not contain a definition for 'M' and the best extension method overload 'C.M((int x, long y))' requires a receiver of type '(int x, long y)' // System.Console.WriteLine((1, 2).M()); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(1, 2)").WithArguments("(int, int)", "M", "C.M((int x, long y))", "(int x, long y)").WithLocation(10, 34), // (16,34): error CS1929: '(int, long)' does not contain a definition for 'M1' and the best extension method overload 'C.M1((int x, long? y))' requires a receiver of type '(int x, long? y)' // System.Console.WriteLine((First: 1, Second: 2L).M1()); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(First: 1, Second: 2L)").WithArguments("(int, long)", "M1", "C.M1((int x, long? y))", "(int x, long? y)").WithLocation(16, 34), // (19,44): error CS0117: '(int, <null>)' does not contain a definition for 'M1' // System.Console.WriteLine((1, null).M1()); Diagnostic(ErrorCode.ERR_NoSuchMember, "M1").WithArguments("(int, <null>)", "M1"), // (23,34): error CS1929: '(int A, int B)' does not contain a definition for 'M' and the best extension method overload 'C.M((int x, long y))' requires a receiver of type '(int x, long y)' // System.Console.WriteLine(notAliteral.M()); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "notAliteral").WithArguments("(int A, int B)", "M", "C.M((int x, long y))", "(int x, long y)").WithLocation(23, 34) ); } [ConditionalFact(typeof(DesktopOnly))] public void Serialization() { var source = @" using System; class C { public static void Main() { VerifySerialization(new ValueTuple()); VerifySerialization(ValueTuple.Create(1)); VerifySerialization((1, 2, 3, 4, 5, 6, 7, 8)); Console.WriteLine(""DONE""); } public static void VerifySerialization<T>(T tuple) { var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); var writer = new System.IO.StringWriter(); serializer.Serialize(writer, tuple); string xml = writer.ToString(); object output = serializer.Deserialize(new System.IO.StringReader(xml)); if (!tuple.Equals(output)) { throw new Exception(""Deserialization output didn't match""); } } }"; var comp = CreateCompilationWithMscorlib40(new[] { source, tuplelib_cs }, references: new[] { SystemXmlRef }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "DONE"); } [Fact] public void GetWellKnownTypeWithAmbiguities() { var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]"; var corlib_cs = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class ValueType { } public struct Void { } public class Attribute { } } namespace System.Reflection { public class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(String version) { } } }"; string valuetuple_cs = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2); } }"; var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib"); corlibWithoutVT.VerifyDiagnostics(); var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference(); var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib"); corlibWithVT.VerifyDiagnostics(); var corlibWithVTRef = corlibWithVT.EmitToImageReference(); var libWithVT = CreateEmptyCompilation(valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll); libWithVT.VerifyDiagnostics(); var libWithVTRef = libWithVT.EmitToImageReference(); var comp = CSharpCompilation.Create("test", references: new[] { libWithVTRef, corlibWithVTRef }); var found = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.False(found.IsErrorType()); Assert.Equal("corlib", found.ContainingAssembly.Name); var comp2 = comp.WithOptions(comp.Options.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); var tuple2 = comp2.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.False(tuple2.IsErrorType()); Assert.Equal(libWithVTRef.Display, tuple2.ContainingAssembly.MetadataName.ToString()); var comp3 = CSharpCompilation.Create("test", references: new[] { corlibWithVTRef, libWithVTRef }) // order reversed .WithOptions(comp.Options.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); var tuple3 = comp3.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.False(tuple3.IsErrorType()); Assert.Equal(libWithVTRef.Display, tuple3.ContainingAssembly.MetadataName.ToString()); var libWithVTRef2 = CreateEmptyCompilation(valuetuple_cs, references: new[] { corlibWithoutVTRef }).EmitToImageReference(); var comp4 = CreateEmptyCompilation("", references: new[] { libWithVTRef, libWithVTRef2, corlibWithoutVTRef }); var tuple4 = comp4.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.True(tuple4.IsErrorType()); } [Fact] [WorkItem(17962, "https://github.com/dotnet/roslyn/issues/17962")] public void TupleWithAsOperator() { var source = @" class C { void M<T>() { var x = (0, null) as (int, T)?; System.Console.WriteLine(x == null); } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,17): error CS8304: The first operand of an 'as' operator may not be a tuple literal without a natural type. // var x = (0, null) as (int, T)?; Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(0, null) as (int, T)?").WithLocation(6, 17) ); } [Fact] public void CheckedConstantConversions() { var source = @"#pragma warning disable 219 class C { static void Main() { unchecked { var u = ((byte, byte))(0, -1); var (a, b) = ((byte, byte))(0, -2); } checked { var c = ((byte, byte))(0, -1); var (a, b) = ((byte, byte))(0, -2); } } }"; var comp = CreateCompilationWithMscorlib40( source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (13,39): error CS0221: Constant value '-1' cannot be converted to a 'byte' (use 'unchecked' syntax to override) // var c = ((byte, byte))(0, -1); Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "-1").WithArguments("-1", "byte").WithLocation(13, 39), // (14,44): error CS0221: Constant value '-2' cannot be converted to a 'byte' (use 'unchecked' syntax to override) // var (a, b) = ((byte, byte))(0, -2); Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "-2").WithArguments("-2", "byte").WithLocation(14, 44)); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInAsOperator() { var source = @" using System; class P { static void Main() { var x1 = (1, 1) as (int, int a)?; var x2 = (1, 1) as (int, int)?; var x3 = (1, new object()) as (int, dynamic)?; Console.Write($""{x1} {x2} {x3}""); } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(1, 1) (1, 1) (1, System.Object)"); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInAsOperator2() { var source = @" class P { static void M() { var x = (a: 1, b: 1) as (int c, int d)?; var y = (1, 1) as (int, long)?; } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,17): warning CS0458: The result of the expression is always 'null' of type '(int, long)?' // var y = (1, 1) as (int, long)?; Diagnostic(ErrorCode.WRN_AlwaysNull, "(1, 1) as (int, long)?").WithArguments("(int, long)?").WithLocation(7, 17) ); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInIsOperator() { var source = @" class P { static void M() { var x1 = (1, 1) is (int, int a)?; } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,29): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(6, 29), // (6,41): error CS1525: Invalid expression term ';' // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 41), // (6,41): error CS1003: Syntax error, ':' expected // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(6, 41), // (6,41): error CS1525: Invalid expression term ';' // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 41) ); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInIsOperator2() { var source = @" class P { static void M() { var x1 = (1, 1) is System.Nullable<(int, int a)>; } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,18): warning CS0183: The given expression is always of the provided ('(int, int a)?') type // var x1 = (1, 1) is System.Nullable<(int, int a)>; Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "(1, 1) is System.Nullable<(int, int a)>").WithArguments("(int, int a)?").WithLocation(6, 18) ); } [Fact] [WorkItem(18459, "https://github.com/dotnet/roslyn/issues/18459")] public void CheckedConversions() { var source = @"using System; class C { static (long, byte) Default((int, int) t) { return ((long, byte))t; } static (long, byte) Unchecked((int, int) t) { unchecked { return ((long, byte))t; } } static (long, byte) Checked((int, int) t) { checked { return ((long, byte))t; } } static void Main() { var d = Default((-1, -1)); Console.Write(d); var u = Unchecked((-1, -1)); Console.Write(u); try { var c = Checked((-1, -1)); Console.Write(c); } catch (OverflowException) { Console.Write(""overflow""); } } }"; var comp = CreateCompilationWithMscorlib40( source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"(-1, 255)(-1, 255)overflow"); verifier.VerifyIL("C.Default", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_000f: conv.u1 IL_0010: newobj ""System.ValueTuple<long, byte>..ctor(long, byte)"" IL_0015: ret }"); verifier.VerifyIL("C.Unchecked", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_000f: conv.u1 IL_0010: newobj ""System.ValueTuple<long, byte>..ctor(long, byte)"" IL_0015: ret }"); verifier.VerifyIL("C.Checked", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_000f: conv.ovf.u1 IL_0010: newobj ""System.ValueTuple<long, byte>..ctor(long, byte)"" IL_0015: ret }"); } [Fact] [WorkItem(19434, "https://github.com/dotnet/roslyn/issues/19434")] public void ExplicitTupleLiteralConversionWithNullable01() { var source = @" class C { static void Main() { int x = 1; var y = ((byte, byte)?)(x, x); System.Console.WriteLine(y.Value); } } "; var comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"(1, 1)"); comp.VerifyIL("C.Main()", @" { // Code size 38 (0x26) .maxstack 3 .locals init (int V_0, //x System.ValueTuple<byte, byte>? V_1) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldloc.0 IL_0006: conv.u1 IL_0007: ldloc.0 IL_0008: conv.u1 IL_0009: newobj ""System.ValueTuple<byte, byte>..ctor(byte, byte)"" IL_000e: call ""System.ValueTuple<byte, byte>?..ctor(System.ValueTuple<byte, byte>)"" IL_0013: ldloca.s V_1 IL_0015: call ""System.ValueTuple<byte, byte> System.ValueTuple<byte, byte>?.Value.get"" IL_001a: box ""System.ValueTuple<byte, byte>"" IL_001f: call ""void System.Console.WriteLine(object)"" IL_0024: nop IL_0025: ret } "); comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"(1, 1)"); comp.VerifyIL("C.Main()", @" { // Code size 36 (0x24) .maxstack 3 .locals init (int V_0, //x System.ValueTuple<byte, byte>? V_1) //y IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldloc.0 IL_0005: conv.u1 IL_0006: ldloc.0 IL_0007: conv.u1 IL_0008: newobj ""System.ValueTuple<byte, byte>..ctor(byte, byte)"" IL_000d: call ""System.ValueTuple<byte, byte>?..ctor(System.ValueTuple<byte, byte>)"" IL_0012: ldloca.s V_1 IL_0014: call ""System.ValueTuple<byte, byte> System.ValueTuple<byte, byte>?.Value.get"" IL_0019: box ""System.ValueTuple<byte, byte>"" IL_001e: call ""void System.Console.WriteLine(object)"" IL_0023: ret } "); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion_01() { var source = @" class C { void M() { int? e = 5; (int, string) y = (e, null); // the only conversion we find is an explicit conversion System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,28): error CS0029: Cannot implicitly convert type 'int?' to 'int' // (int, string) y = (e, null); Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("int?", "int").WithLocation(7, 28) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion(comp); } private static void VerifySemanticModelTypelessTupleWithNoImplicitConversion(CSharpCompilation comp) { var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(tuple).Kind); var first = tuple.Arguments[0].Expression; Assert.Equal("System.Int32?", model.GetTypeInfo(first).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(first).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(first).Kind); var second = tuple.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(second).Type); Assert.Equal("System.String", model.GetTypeInfo(second).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(second).Kind); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion_02() { var source = @" class C { (int, string) M() { int? e = 5; return (e, null); // the only conversion we find is an explicit conversion } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,17): error CS0029: Cannot implicitly convert type 'int?' to 'int' // return (e, null); // the only conversion we find is an explicit conversion Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("int?", "int").WithLocation(7, 17) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion(comp); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion2_01() { var source = @" class C { void M() { int? e = 5; (int, string)? y = (e, null); // the only conversion we find is an explicit conversion System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,28): error CS8135: Tuple with 2 elements cannot be converted to type '(int, string)?'. // (int, string)? y = (e, null); // the only conversion we find is an explicit conversion Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(e, null)").WithArguments("2", "(int, string)?").WithLocation(7, 28) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion2(comp); } private static void VerifySemanticModelTypelessTupleWithNoImplicitConversion2(CSharpCompilation comp) { var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Equal("(System.Int32, System.String)?", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(tuple).Kind); var first = tuple.Arguments[0].Expression; Assert.Equal("System.Int32?", model.GetTypeInfo(first).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(first).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(first).Kind); var second = tuple.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(second).Type); Assert.Equal("System.String", model.GetTypeInfo(second).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(second).Kind); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion2_02() { var source = @" class C { (int, string)? M() { int? e = 5; return (e, null); // the only conversion we find is an explicit conversion } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,16): error CS8135: Tuple with 2 elements cannot be converted to type '(int, string)?'. // return (e, null); // the only conversion we find is an explicit conversion Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(e, null)").WithArguments("2", "(int, string)?").WithLocation(7, 16) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion2(comp); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion3() { var source = @" class C { void M() { int? e = 5; (int, string, int) y = (e, null); // no conversion found System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,32): error CS8135: Tuple with 2 elements cannot be converted to type '(int, string, int)'. // (int, string, int) y = (e, null); // no conversion found Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(e, null)").WithArguments("2", "(int, string, int)").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, model.GetConversion(tuple).Kind); var first = tuple.Arguments[0].Expression; Assert.Equal("System.Int32?", model.GetTypeInfo(first).Type.ToTestDisplayString()); Assert.Equal("System.Int32?", model.GetTypeInfo(first).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(first).Kind); var second = tuple.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(second).Type); Assert.Null(model.GetTypeInfo(second).ConvertedType); Assert.Equal(ConversionKind.Identity, model.GetConversion(second).Kind); } [Fact] [WorkItem(20208, "https://github.com/dotnet/roslyn/issues/20208")] public void UnusedTupleAssignedToVar() { var source = @" class C { public static void Main () { (int, int) t1 = (1, 2); var t2 = (3, 4); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,20): warning CS0219: The variable 't1' is assigned but its value is never used // (int, int) t1 = (1, 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t1").WithArguments("t1").WithLocation(6, 20), // (7,13): warning CS0219: The variable 't2' is assigned but its value is never used // var t2 = (3, 4); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2").WithLocation(7, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(tuple).Kind); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypedTupleWithNoConversion() { var source = @" class C { void M() { int? e = 5; (int, string, int) y = (e, """"); // no conversion found System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,32): error CS0029: Cannot implicitly convert type '(int? e, string)' to '(int, string, int)' // (int, string, int) y = (e, ""); // no conversion found Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(e, """")").WithArguments("(int? e, string)", "(int, string, int)").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32? e, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, model.GetConversion(tuple).Kind); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_01() { var source = @"using System; public class C { public static void Main() { A<A<int>> a = null; M1(a); // ok, selects M1<T>(A<A<T>> a) var b = default(ValueTuple<ValueTuple<int, int>, int>); M2(b); // ok, should select M2<T>(ValueTuple<ValueTuple<T, int>, int> a) } public static void M1<T>(A<T> a) { Console.Write(1); } public static void M1<T>(A<A<T>> a) { Console.Write(2); } public static void M2<T>(ValueTuple<T, int> a) { Console.Write(3); } public static void M2<T>(ValueTuple<ValueTuple<T, int>, int> a) { Console.Write(4); } } public class A<T> {}"; var comp = CompileAndVerify(source, expectedOutput: "24"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_01b() { var source = @"using System; public class C { public static void Main() { var b = ((0, 0), 0); M2(b); // ok, should select M2<T>(((T, int), int) a) } public static void M2<T>((T, int) a) { Console.Write(3); } public static void M2<T>(((T, int), int) a) { Console.Write(4); } }"; var comp = CompileAndVerify(source, expectedOutput: "4"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a1() { var source = @"using System; public class C { public static void Main() { // var b = (1, 2, 3, 4, 5, 6, 7, 8); var b = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple<int>(8)); M1(b); M2(b); // ok, should select M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a2() { var source = @"using System; public class C { public static void Main() { // var b = (1, 2, 3, 4, 5, 6, 7, 8); var b = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple<int>(8)); M1(ref b); M2(ref b); // ok, should select M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ref ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ref ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ref ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a3() { var source = @"using System; public class C { public static void Main() { I<ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>> b = null; M1(b); M2(b); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(3); } } public interface I<in T>{} "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a4() { var source = @"using System; public class C { public static void Main() { I<ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>> b = null; M1(b); M2(b); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(3); } } public interface I<out T>{} "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a5() { var source = @"using System; public class C { public static void Main() { M1((1, 2, 3, 4, 5, 6, 7, 8)); M2((1, 2, 3, 4, 5, 6, 7, 8)); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a6() { var source = @"using System; public class C { public static void Main() { M2((()=>1, ()=>2, ()=>3, ()=>4, ()=>5, ()=>6, ()=>7, ()=>8)); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, ValueTuple<Func<T8>>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"2"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a7() { var source = @"using System; public class C { public static void Main() { M1((()=>1, ()=>2, ()=>3, ()=>4, ()=>5, ()=>6, ()=>7, ()=>8)); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, TRest> a) where TRest : struct { Console.Write(1); } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'C.M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, TRest>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1((()=>1, ()=>2, ()=>3, ()=>4, ()=>5, ()=>6, ()=>7, ()=>8)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("C.M1<T1, T2, T3, T4, T5, T6, T7, TRest>(System.ValueTuple<System.Func<T1>, System.Func<T2>, System.Func<T3>, System.Func<T4>, System.Func<T5>, System.Func<T6>, System.Func<T7>, TRest>)").WithLocation(6, 9) ); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02b() { var source = @"using System; public class C { public static void Main() { var b = (1, 2, 3, 4, 5, 6, 7, 8); M1(b); M2(b); // ok, should select M2<T1, T2, T3, T4, T5, T6, T7, T8>((T1, T2, T3, T4, T5, T6, T7, T8) a) } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>((T1, T2, T3, T4, T5, T6, T7, T8) a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_03() { var source = @"using System; public class C { public static void Main() { var b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, (10, 10), (11, 11)); M1(b); // ok, should select M2<T, U, V>(((T, int), int, int, int, int, int, int, int, int, (U, int), V) a) } public static void M1<T, U, V>(((T, int), int, int, int, int, int, int, int, int, (U, int), V) a) { Console.Write(3); } public static void M1<T, U, V>((T, int, int, int, int, int, int, int, int, U, (V, int)) a) { Console.Write(4); } }"; var comp = CompileAndVerify(source, expectedOutput: "3"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_04() { var source = @"using System; public class C { public static void Main() { var b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, (20, 20)); M1(b); // error: ambiguous } public static void M1<T, U>((T, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, (U, int)) a) { Console.Write(3); } public static void M1<T, U>(((T, int), int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, U) a) { Console.Write(4); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1<T, U>((T, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, (U, int)))' and 'C.M1<T, U>(((T, int), int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, U))' // M1(b); // error: ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1<T, U>((T, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, (U, int)))", "C.M1<T, U>(((T, int), int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, U))").WithLocation(7, 9) ); } [Fact] [WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")] void TypelessTupleInArrayInitializer() { string source = @" class C { static (int A, object B)[] mTupleArray = { (A: 0, B: null) }; private static void Main() { System.Console.Write(mTupleArray[0].B == null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(A: 0, B: null)", node.ToString()); var tupleSymbol = model.GetTypeInfo(node); Assert.Null(tupleSymbol.Type); Assert.Equal("(System.Int32 A, System.Object B)", tupleSymbol.ConvertedType.ToTestDisplayString()); } [Fact] public void SettingMembersOfReadOnlyTuple() { var text = @" public class C { public static void Main() { var tuple = (1, 2); tuple.Item1 = 3; } } namespace System { public readonly struct ValueTuple<T1, T2> { public readonly T1 Item1; public readonly T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // tuple.Item1 = 3; Diagnostic(ErrorCode.ERR_AssgReadonly, "tuple.Item1").WithLocation(8, 9)); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithTuple_AddingNames() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<(int, int)> impl) { var case3 = impl.Do(((int x, int y) a) => a.x * a.y); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do(((int x, int y) a) => a.x * a.y)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithTuple_DifferentNames() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<(int a, int b)> impl) { var case3 = impl.Do(((int x, int y) a) => a.x * a.y); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do(((int x, int y) a) => a.x * a.y)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithTuple_DroppingNames() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<(int a, int b)> impl) { var case3 = impl.Do(((int, int) a) => a.Item1 * a.Item2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do(((int, int) a) => a.Item1 * a.Item2)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithDynamic() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<object> impl) { var case3 = impl.Do((dynamic a) => 1); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do((dynamic a) => 1)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase_ValueTuple(bool useImageReference) { var lib_cs = @" public class C2<T1, T2> { } public class SelfReferencing : C2<SelfReferencing, (string A, int B)> { public SelfReferencing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: s_valueTupleRefs); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class Program { public static void M() { _ = new SelfReferencing(); } } "; var comp = CreateCompilationWithMscorlib40(source_cs, references: new[] { libRef }); comp.VerifyEmitDiagnostics(); var executable_cs = @" public class C { public static void Main() { Program.M(); } }"; var executeComp = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase_ValueTupleInContainer(bool useImageReference, bool missingValueTuple) { var missingContainer_cs = @" public class MissingContainer<T> { } "; var missingContainer = CreateCompilationWithMscorlib40(missingContainer_cs, references: s_valueTupleRefs); missingContainer.VerifyDiagnostics(); var missingContainerRef = useImageReference ? missingContainer.EmitToImageReference() : missingContainer.ToMetadataReference(); var lib_cs = @" public class C2<T1, T2> { } public class SelfReferencing : C2<SelfReferencing, MissingContainer<(string A, int B)>> { public SelfReferencing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: new[] { missingContainerRef, SystemRuntimeFacadeRef, ValueTupleRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class Program { public static void M() { _ = new SelfReferencing(); } } "; // Compile without System.ValueTuple and/or MissingContainer var references = missingValueTuple ? new[] { libRef } : new[] { libRef, SystemRuntimeFacadeRef, ValueTupleRef }; var comp = CreateCompilationWithMscorlib40(source_cs, references: references); comp.VerifyEmitDiagnostics(); // Execute with all the references present var executable_cs = @" public class C { public static void Main() { Program.M(); } }"; var executeComp = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, SystemRuntimeFacadeRef, ValueTupleRef, missingContainerRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase_ValueTupleAndContainer(bool useImageReference) { var missingContainer_cs = @" public class MissingContainer<T> { } "; var missingContainer = CreateCompilationWithMscorlib40(missingContainer_cs, references: s_valueTupleRefs); missingContainer.VerifyDiagnostics(); var missingContainerRef = useImageReference ? missingContainer.EmitToImageReference() : missingContainer.ToMetadataReference(); var lib_cs = @" public class C : MissingContainer<(string A, int B)> { public C() { System.Console.Write(""ran""); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef, missingContainerRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class C2 { public static void M() { _ = new C(); } } "; var executable_cs = @" public class C3 { public static void Main() { C2.M(); } }"; var comp = CreateCompilationWithMscorlib40(source_cs, references: new[] { libRef }); // missing System.ValueTuple and MissingContainer comp.VerifyEmitDiagnostics(); var executeComp = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, missingContainerRef, SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); var comp2 = CreateCompilationWithMscorlib40(source_cs, references: new[] { libRef, missingContainerRef }); // missing System.ValueTuple comp2.VerifyEmitDiagnostics(); var executeComp2 = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, missingContainerRef, SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp2, expectedOutput: "ran"); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase(bool useImageReference) { var missing_cs = @"public class Missing { }"; var missing = CreateCompilation(missing_cs); missing.VerifyDiagnostics(); var missingRef = useImageReference ? missing.EmitToImageReference() : missing.ToMetadataReference(); var lib_cs = @" public class C2<T1, T2> { } public class SelfReferencingClassWithMissing : C2<SelfReferencingClassWithMissing, Missing> { public SelfReferencingClassWithMissing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilation(lib_cs, references: new[] { missingRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class C { public static void M() { _ = new SelfReferencingClassWithMissing(); } } "; var comp = CreateCompilation(source_cs, references: new[] { libRef }); comp.VerifyEmitDiagnostics(); var executable_cs = @" public class C2 { public static void Main() { C.M(); } }"; var executeComp = CreateCompilation(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, missingRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Fact] [WorkItem(41699, "https://github.com/dotnet/roslyn/issues/41699")] public void MissingBaseType_TupleTypeArgumentWithNames() { var sourceA = @"public class A<T> { }"; var comp = CreateCompilation(sourceA, assemblyName: "A"); var refA = comp.EmitToImageReference(); var sourceB = @"public class B : A<(object X, B Y)> { }"; comp = CreateCompilation(sourceB, references: new[] { refA }); var refB = comp.EmitToImageReference(); var sourceC = @"class Program { static void Main() { var b = new B(); b.ToString(); } }"; comp = CreateCompilation(sourceC, references: new[] { refB }); comp.VerifyDiagnostics( // (6,11): error CS0012: The type 'A<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // b.ToString(); Diagnostic(ErrorCode.ERR_NoTypeDef, "ToString").WithArguments("A<>", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 11)); } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfTupleNamesWhenMissingValueTupleType() { var vtLib = CreateEmptyCompilation(trivial2uple + tupleattributes_cs, references: new[] { MscorlibRef }, assemblyName: "vt"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<(int alice, int bob)> { public void Add(int alice, int bob) => throw null; public IEnumerator<(int alice, int bob)> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs, references: new[] { MscorlibRef, vtLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client_cs = @" public class ClassB { public ClassB() { new ClassA { { 42, 10 } }; } }"; var comp = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to vt comp.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(comp, decodingSuccessful: false); var compWithMetadataReference = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.ToMetadataReference() }); // missing reference to vt compWithMetadataReference.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithMetadataReference, decodingSuccessful: true); var fakeVtLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "vt"); var compWithFakeVt = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeVtLib.EmitToImageReference() }); // reference to fake vt compWithFakeVt.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithFakeVt, decodingSuccessful: false); var client2_cs = @" public class ClassB { public ClassB() { var collectionA = new ClassA { { 42, 10 } }; foreach (var i in collectionA) { } } }"; var comp2 = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to vt comp2.VerifyDiagnostics( // (7,27): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("(, )", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27), // (7,27): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("(, )", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(comp2, decodingSuccessful: false); var comp2WithFakeVt = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeVtLib.EmitToImageReference() }); // reference to fake vt comp2WithFakeVt.VerifyDiagnostics( // (7,27): error CS7069: Reference to type '(, )' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("(, )", "vt").WithLocation(7, 27), // (7,27): error CS7069: Reference to type '(, )' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("(, )", "vt").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(comp2WithFakeVt, decodingSuccessful: false); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation, bool decodingSuccessful) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; if (decodingSuccessful) { Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 alice, System.Int32 bob)[missing]>", iEnumerable.ToTestDisplayString()); } else { Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32, System.Int32)[missing]>", iEnumerable.ToTestDisplayString()); } var tuple = iEnumerable.TypeArguments()[0]; if (decodingSuccessful) { Assert.Equal("(System.Int32 alice, System.Int32 bob)[missing]", tuple.ToTestDisplayString()); Assert.True(tuple.IsTupleType); Assert.True(tuple.IsErrorType()); } else { Assert.Equal("(System.Int32, System.Int32)[missing]", tuple.ToTestDisplayString()); Assert.True(tuple.IsTupleType); Assert.True(tuple.IsErrorType()); } } } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfLongTupleNamesWhenMissingValueTupleType() { var vtLib = CreateEmptyCompilation(tuplelib_cs + tupleattributes_cs, references: new[] { MscorlibRef }, assemblyName: "vt"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8)> { public void Add(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8) => throw null; public IEnumerator<(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8)> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs, references: new[] { MscorlibRef, vtLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client2_cs = @" public class ClassB { public ClassB() { var collectionA = new ClassA { { 1, 2, 3, 4, 5, 6, 7, 8 } }; foreach (var i in collectionA) { } } }"; var fakeVtLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "vt"); var comp = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to vt comp.VerifyDiagnostics( // (7,27): error CS0012: The type 'ValueTuple<,,,,,,,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27), // (7,27): error CS0012: The type 'ValueTuple<,,,,,,,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(comp); var compWithFakeVt = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeVtLib.EmitToImageReference() }); // reference to fake vt compWithFakeVt.VerifyDiagnostics( // (7,27): error CS7069: Reference to type 'ValueTuple<,,,,,,,>' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt").WithLocation(7, 27), // (7,27): error CS7069: Reference to type 'ValueTuple<,,,,,,,>' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(compWithFakeVt); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; var tuple = iEnumerable.TypeArguments()[0]; AssertEx.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.ValueTuple<System.Int32>[missing]>[missing]", tuple.ToTestDisplayString()); Assert.True(tuple.IsErrorType()); Assert.True(tuple.IsTupleType); } } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfTupleNamesWhenMissingNonTupleType() { var containerLib = CreateEmptyCompilation("public class Container<T> { }", references: new[] { MscorlibRef }, assemblyName: "container"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<Container<(int alice, int bob)>> { public void Add(int alice, int bob) => throw null; public IEnumerator<Container<(int alice, int bob)>> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs + tuplelib_cs + tupleattributes_cs, references: new[] { MscorlibRef, containerLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client_cs = @" public class ClassB { public ClassB() { new ClassA { { 42, 10 } }; } }"; var comp = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to container comp.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(comp, decodingSuccessful: false); var compWithMetadataReference = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.ToMetadataReference() }); // missing reference to container compWithMetadataReference.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithMetadataReference, decodingSuccessful: true); var fakeContainerLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "container"); var compWithFakeContainer = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeContainerLib.EmitToImageReference() }); // reference to fake container compWithFakeContainer.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithFakeContainer, decodingSuccessful: false); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation, bool decodingSuccessful) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; if (decodingSuccessful) { AssertEx.Equal("System.Collections.Generic.IEnumerable<Container<(System.Int32 alice, System.Int32 bob)>[missing]>", iEnumerable.ToTestDisplayString()); } else { Assert.Equal("System.Collections.Generic.IEnumerable<Container<(System.Int32, System.Int32)>[missing]>", iEnumerable.ToTestDisplayString()); } var container = (NamedTypeSymbol)iEnumerable.TypeArguments()[0]; Assert.True(container.IsErrorType()); var tuple = (NamedTypeSymbol)container.TypeArguments()[0]; if (decodingSuccessful) { Assert.Equal("(System.Int32 alice, System.Int32 bob)", tuple.ToTestDisplayString()); } else { Assert.Equal("(System.Int32, System.Int32)", tuple.ToTestDisplayString()); } Assert.True(tuple.IsTupleType); Assert.False(tuple.TupleUnderlyingType.IsErrorType()); Assert.False(tuple.IsErrorType()); } } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfTupleNamesWhenMissingContainerType() { var containerLib = CreateEmptyCompilation("public class Container<T> { public class Contained<U> { } }", references: new[] { MscorlibRef }, assemblyName: "container"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<Container<(int alice, int bob)>.Contained<(int charlie, int dylan)>> { public void Add(int alice, int bob) => throw null; public IEnumerator<Container<(int alice, int bob)>.Contained<(int charlie, int dylan)>> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs + tuplelib_cs + tupleattributes_cs, references: new[] { MscorlibRef, containerLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client_cs = @" public class ClassB { public ClassB() { new ClassA { { 42, 10 } }; } }"; var comp = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to container comp.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(comp, decodingSuccessful: false); var compWithMetadataReference = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.ToMetadataReference() }); // missing reference to container compWithMetadataReference.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithMetadataReference, decodingSuccessful: true); var fakeContainerLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "container"); var compWithFakeContainer = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeContainerLib.EmitToImageReference() }); // reference to fake container compWithFakeContainer.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithFakeContainer, decodingSuccessful: false); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation, bool decodingSuccessful) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; AssertEx.Equal(decodingSuccessful ? "System.Collections.Generic.IEnumerable<Container<(System.Int32 alice, System.Int32 bob)>[missing].Contained<(System.Int32 charlie, System.Int32 dylan)>[missing]>" : "System.Collections.Generic.IEnumerable<Container<(System.Int32, System.Int32)>[missing].Contained<(System.Int32, System.Int32)>[missing]>", iEnumerable.ToTestDisplayString()); var contained = (NamedTypeSymbol)iEnumerable.TypeArguments()[0]; Assert.Equal(decodingSuccessful ? "Container<(System.Int32 alice, System.Int32 bob)>[missing].Contained<(System.Int32 charlie, System.Int32 dylan)>[missing]" : "Container<(System.Int32, System.Int32)>[missing].Contained<(System.Int32, System.Int32)>[missing]", contained.ToTestDisplayString()); Assert.True(contained.IsErrorType()); var tuple1 = (NamedTypeSymbol)contained.TypeArguments()[0]; Assert.Equal(decodingSuccessful ? "(System.Int32 charlie, System.Int32 dylan)" : "(System.Int32, System.Int32)", tuple1.ToTestDisplayString()); Assert.True(tuple1.IsTupleType); Assert.False(tuple1.TupleUnderlyingType.IsErrorType()); Assert.False(tuple1.IsErrorType()); var container = contained.ContainingType; Assert.Equal(decodingSuccessful ? "Container<(System.Int32 alice, System.Int32 bob)>[missing]" : "Container<(System.Int32, System.Int32)>[missing]", container.ToTestDisplayString()); Assert.True(container.IsErrorType()); var tuple2 = (NamedTypeSymbol)container.TypeArguments()[0]; Assert.Equal(decodingSuccessful ? "(System.Int32 alice, System.Int32 bob)" : "(System.Int32, System.Int32)", tuple2.ToTestDisplayString()); Assert.True(tuple2.IsTupleType); Assert.False(tuple2.TupleUnderlyingType.IsErrorType()); Assert.False(tuple2.IsErrorType()); } } [Fact] [WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")] [WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_01() { var source0 = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public static int F1 = 123; public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return F1.ToString(); } } } "; var source1 = @" class Program { public static void Main() { System.Console.WriteLine((1,2).ToString()); } } "; var source2 = @" class Program { public static void Main() { System.Console.WriteLine(System.ValueTuple<int, int>.F1); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "123"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "123"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "123"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "123"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "123"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Where(f => f.Name == "F1").Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")] [WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_02() { var source0 = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public int F1; public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; F1 = 123; } public override string ToString() { return F1.ToString(); } } } "; var source1 = @" class Program { public static void Main() { System.Console.WriteLine((1,2).ToString()); } } "; var source2 = @" class Program { public static void Main() { System.Console.WriteLine((1,2).F1); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "123"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "123"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "123"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "123"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "123"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Where(f => f.Name == "F1").Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")] [WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_03() { var source0 = @" namespace System { public struct ValueTuple { public static readonly int F1 = 4; public static int CombineHashCodes(int h1, int h2) { return F1 + h1 + h2; } } } "; var source1 = @" class Program { static void Main() { System.Console.WriteLine(System.ValueTuple.CombineHashCodes(2, 3)); } } "; var source2 = @" class Program { public static void Main() { System.Console.WriteLine(System.ValueTuple.F1 + 2 + 3); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "9"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "9"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "9"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "9"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "9"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")] [WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_04() { var source0 = @" namespace System { public struct ValueTuple { public int F1; public int CombineHashCodes(int h1, int h2) { return F1 + h1 + h2; } } } "; var source1 = @" class Program { static void Main() { System.ValueTuple tuple = default; tuple.F1 = 4; System.Console.WriteLine(tuple.CombineHashCodes(2, 3)); } } "; var source2 = @" class Program { public static void Main() { System.ValueTuple tuple = default; tuple.F1 = 4; System.Console.WriteLine(tuple.F1 + 2 + 3); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "9"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "9"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "9"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "9"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "9"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(43621, "https://github.com/dotnet/roslyn/issues/43621")] public void CustomFields_05() { var source0 = @" using System; namespace System { public class C { public unsafe static void Main() { var s = new ValueTuple(); int* p = s.MessageType; s.MessageType[0] = 12; p[1] = p[0]; Console.WriteLine(s.MessageType[1]); } } public unsafe struct ValueTuple { public fixed int MessageType[50]; } } "; var comp1 = CreateCompilation(source0, options: TestOptions.DebugExe.WithAllowUnsafe(true)); var verifier = CompileAndVerify(comp1, verify: Verification.Skipped); // unsafe code // There is a problem with caller, so execution currently yields the wrong result // Tracked by https://github.com/dotnet/roslyn/issues/43621 //var verifier = CompileAndVerify(comp1, expectedOutput: 12, verify: Verification.Skipped); // unsafe code if (ExecutionConditionUtil.IsCoreClr) { verifier.VerifyTypeIL("ValueTuple", @" .class public sequential ansi sealed beforefieldinit System.ValueTuple extends [netstandard]System.ValueType { // Nested Types .class nested public sequential ansi sealed beforefieldinit '<MessageType>e__FixedBuffer' extends [netstandard]System.ValueType { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [netstandard]System.Runtime.CompilerServices.UnsafeValueTypeAttribute::.ctor() = ( 01 00 00 00 ) .pack 0 .size 200 // Fields .field public int32 FixedElementField } // end of class <MessageType>e__FixedBuffer // Fields .field public valuetype System.ValueTuple/'<MessageType>e__FixedBuffer' MessageType .custom instance void [netstandard]System.Runtime.CompilerServices.FixedBufferAttribute::.ctor(class [netstandard]System.Type, int32) = ( 01 00 5c 53 79 73 74 65 6d 2e 49 6e 74 33 32 2c 20 6e 65 74 73 74 61 6e 64 61 72 64 2c 20 56 65 72 73 69 6f 6e 3d 32 2e 30 2e 30 2e 30 2c 20 43 75 6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50 75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 63 63 37 62 31 33 66 66 63 64 32 64 64 64 35 31 32 00 00 00 00 00 ) } // end of class System.ValueTuple "); } } [Fact] [WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")] public void TupleUnderlyingType_FromCSharp() { var source = @"#pragma warning disable 169 class Program { static System.ValueTuple F0; static (int, int) F1; static (int A, int B) F2; static (object, object, object, object, object, object, object, object) F3; static (object, object B, object, object D, object, object F, object, object H) F4; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single(); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F0").Single()).Type, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, "System.ValueTuple", "()"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F1").Single()).Type, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F2").Single()).Type, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F3").Single()).Type, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Null, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F4").Single()).Type, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Null, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)"); } [Fact] [WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")] public void TupleUnderlyingType_FromVisualBasic() { var source = @"Class Program Private F0 As System.ValueTuple Private F1 As (Integer, Integer) Private F2 As (A As Integer, B As Integer) Private F3 As (Object, Object, Object, Object, Object, Object, Object, Object) Private F4 As (Object, B As Object, Object, D As Object, Object, F As Object, Object, H As Object) End Class"; var comp = CreateVisualBasicCompilation(source, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); comp.VerifyDiagnostics(); var containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single(); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F0").Single()).Type, TupleUnderlyingTypeValue.Null, "System.ValueTuple", "System.ValueTuple"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F1").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F2").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F3").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F4").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)"); } private enum TupleUnderlyingTypeValue { Null, Distinct, Same } private static void VerifyTypeFromCSharp( NamedTypeSymbol type, TupleUnderlyingTypeValue expectedInternalValue, TupleUnderlyingTypeValue expectedPublicValue, TupleUnderlyingTypeValue definitionInternalValue, TupleUnderlyingTypeValue definitionPublicValue, string expectedCSharp, string expectedVisualBasic) { VerifyDisplay(type.GetPublicSymbol(), expectedCSharp, expectedVisualBasic); VerifyInternalType(type, expectedInternalValue); VerifyPublicType(type.GetPublicSymbol(), expectedPublicValue); type = type.OriginalDefinition; VerifyInternalType(type, definitionInternalValue); VerifyPublicType(type.GetPublicSymbol(), definitionPublicValue); } private static void VerifyTypeFromVisualBasic( INamedTypeSymbol type, TupleUnderlyingTypeValue expectedValue, string expectedCSharp, string expectedVisualBasic) { VerifyDisplay(type, expectedCSharp, expectedVisualBasic); VerifyPublicType(type, expectedValue); VerifyPublicType(type.OriginalDefinition, expectedValue); } private static void VerifyDisplay(INamedTypeSymbol type, string expectedCSharp, string expectedVisualBasic) { Assert.Equal(expectedCSharp, CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)); Assert.Equal(expectedVisualBasic, VisualBasic.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)); } private static void VerifyInternalType(NamedTypeSymbol type, TupleUnderlyingTypeValue expectedValue) { var underlyingType = type.TupleUnderlyingType; switch (expectedValue) { case TupleUnderlyingTypeValue.Null: Assert.Null(underlyingType); break; case TupleUnderlyingTypeValue.Distinct: Assert.NotEqual(type, underlyingType); Assert.True(type.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)); Assert.False(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)); VerifyInternalType(underlyingType, TupleUnderlyingTypeValue.Same); break; case TupleUnderlyingTypeValue.Same: Assert.Equal(type, underlyingType); Assert.True(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)); break; default: throw ExceptionUtilities.UnexpectedValue(expectedValue); } } private static void VerifyPublicType(INamedTypeSymbol type, TupleUnderlyingTypeValue expectedValue) { var underlyingType = type.TupleUnderlyingType; switch (expectedValue) { case TupleUnderlyingTypeValue.Null: Assert.Null(underlyingType); break; case TupleUnderlyingTypeValue.Distinct: Assert.NotEqual(type, underlyingType); Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.Default)); Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.ConsiderEverything)); VerifyPublicType(underlyingType, TupleUnderlyingTypeValue.Null); break; default: throw ExceptionUtilities.UnexpectedValue(expectedValue); } } [Fact] [WorkItem(40981, "https://github.com/dotnet/roslyn/issues/40981")] public void TupleFromMetadata_TypeInference() { var source0 = @" using System; public interface IInterface { (Type, Type)[] GetTypeTuples(); } "; var source1 = @" using System; using System.Linq; public class Class { private void Method(IInterface inter, Func<(Type, Type), string> keySelector) { var tuples = inter.GetTypeTuples(); IOrderedEnumerable<(Type, Type)> ordered = tuples.OrderBy(keySelector); } } "; var comp0 = CreateCompilation(new[] { source0, source1 }, options: TestOptions.DebugDll); CompileAndVerify(comp0); var comp1 = CreateCompilation(source0, options: TestOptions.DebugDll); CompileAndVerify(comp1); var comp2 = CreateCompilation(source1, references: new[] { comp1.EmitToImageReference() }, options: TestOptions.DebugDll); CompileAndVerify(comp2); } [Fact] [WorkItem(1090920, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/1090920")] public void GetSymbolInfoOnInitializerOfValueTupleField() { var source = @" namespace System { public struct ValueTuple<T1> { public T1 Item1 = default; public ValueTuple(T1 item1) { } } } "; var comp = CreateCompilation(new[] { source }, options: TestOptions.DebugDll); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var literal = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.True(model.GetSymbolInfo(literal).IsEmpty); } [Fact, WorkItem(1090920, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/1090920")] public void NameofFixedBuffer() { var source = @" namespace System { public class C { public static void Main() { ValueTuple<int> myStruct = default; Console.Write(myStruct.ToString()); char[] o; myStruct.DoSomething(out o); Console.Write(Other.GetFromExternal()); } } public unsafe struct ValueTuple<T1> { public fixed char MessageType[50]; public override string ToString() { return nameof(MessageType); } public void DoSomething(out char[] x) { x = new char[] { }; Action a = () => { System.Console.Write($"" {nameof(x)} ""); }; a(); } } class Other { public static string GetFromExternal() { ValueTuple<int> myStruct = default; return nameof(myStruct.MessageType); } } } "; var compilation = CreateCompilationWithMscorlib45(source, null, TestOptions.UnsafeDebugExe); CompileAndVerify(compilation, expectedOutput: "MessageType x MessageType").VerifyDiagnostics(); } [Fact] [WorkItem(27322, "https://github.com/dotnet/roslyn/issues/27322")] public void ExpressionTreeWithTuple() { var source = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { static void Main() { var tupleA = (1, 3); var tupleB = (1, ""123"".Length); Expression<Func<int>> ok1 = () => tupleA.Item1; Expression<Func<int>> ok2 = () => tupleA.GetHashCode(); Expression<Func<Tuple<int, int>>> ok3 = () => tupleA.ToTuple(); Expression<Func<bool>> ok4 = () => Equals(tupleA, tupleB); Expression<Func<int>> ok5 = () => Comparer<(int, int)>.Default.Compare(tupleA, tupleB); ok1.Compile()(); ok2.Compile()(); ok3.Compile()(); ok4.Compile()(); ok5.Compile()(); Expression<Func<bool>> issue1 = () => tupleA.Equals(tupleB); Expression<Func<int>> issue2 = () => tupleA.CompareTo(tupleB); Console.WriteLine(""Done.""); } }"; var comp = CreateCompilation( source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"Done."); verifier.VerifyIL("C.Main", @" { // Code size 799 (0x31f) .maxstack 7 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Linq.Expressions.Expression<System.Func<int>> V_1, //ok1 System.Linq.Expressions.Expression<System.Func<int>> V_2, //ok2 System.Linq.Expressions.Expression<System.Func<System.Tuple<int, int>>> V_3, //ok3 System.Linq.Expressions.Expression<System.Func<bool>> V_4) //ok4 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: ldc.i4.3 IL_0009: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000e: stfld ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_0013: ldloc.0 IL_0014: ldc.i4.1 IL_0015: ldstr ""123"" IL_001a: call ""int string.Length.get"" IL_001f: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0024: stfld ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_0029: ldloc.0 IL_002a: ldtoken ""C.<>c__DisplayClass0_0"" IL_002f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0034: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0039: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_003e: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0043: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0048: ldtoken ""int System.ValueTuple<int, int>.Item1"" IL_004d: ldtoken ""System.ValueTuple<int, int>"" IL_0052: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle, System.RuntimeTypeHandle)"" IL_0057: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_005c: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0061: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0066: stloc.1 IL_0067: ldloc.0 IL_0068: ldtoken ""C.<>c__DisplayClass0_0"" IL_006d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0072: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0077: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_007c: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0081: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0086: ldtoken ""int object.GetHashCode()"" IL_008b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0090: castclass ""System.Reflection.MethodInfo"" IL_0095: call ""System.Linq.Expressions.Expression[] System.Array.Empty<System.Linq.Expressions.Expression>()"" IL_009a: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_009f: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_00a4: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a9: stloc.2 IL_00aa: ldnull IL_00ab: ldtoken ""System.Tuple<int, int> System.TupleExtensions.ToTuple<int, int>(System.ValueTuple<int, int>)"" IL_00b0: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_00b5: castclass ""System.Reflection.MethodInfo"" IL_00ba: ldc.i4.1 IL_00bb: newarr ""System.Linq.Expressions.Expression"" IL_00c0: dup IL_00c1: ldc.i4.0 IL_00c2: ldloc.0 IL_00c3: ldtoken ""C.<>c__DisplayClass0_0"" IL_00c8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00cd: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_00d2: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_00d7: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_00dc: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_00e1: stelem.ref IL_00e2: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_00e7: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_00ec: call ""System.Linq.Expressions.Expression<System.Func<System.Tuple<int, int>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Tuple<int, int>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00f1: stloc.3 IL_00f2: ldnull IL_00f3: ldtoken ""bool object.Equals(object, object)"" IL_00f8: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_00fd: castclass ""System.Reflection.MethodInfo"" IL_0102: ldc.i4.2 IL_0103: newarr ""System.Linq.Expressions.Expression"" IL_0108: dup IL_0109: ldc.i4.0 IL_010a: ldloc.0 IL_010b: ldtoken ""C.<>c__DisplayClass0_0"" IL_0110: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0115: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_011a: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_011f: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0124: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0129: ldtoken ""object"" IL_012e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0133: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0138: stelem.ref IL_0139: dup IL_013a: ldc.i4.1 IL_013b: ldloc.0 IL_013c: ldtoken ""C.<>c__DisplayClass0_0"" IL_0141: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0146: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_014b: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_0150: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0155: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_015a: ldtoken ""object"" IL_015f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0164: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0169: stelem.ref IL_016a: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_016f: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0174: call ""System.Linq.Expressions.Expression<System.Func<bool>> System.Linq.Expressions.Expression.Lambda<System.Func<bool>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0179: stloc.s V_4 IL_017b: ldnull IL_017c: ldtoken ""System.Collections.Generic.Comparer<System.ValueTuple<int, int>> System.Collections.Generic.Comparer<System.ValueTuple<int, int>>.Default.get"" IL_0181: ldtoken ""System.Collections.Generic.Comparer<System.ValueTuple<int, int>>"" IL_0186: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_018b: castclass ""System.Reflection.MethodInfo"" IL_0190: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0195: ldtoken ""int System.Collections.Generic.Comparer<System.ValueTuple<int, int>>.Compare(System.ValueTuple<int, int>, System.ValueTuple<int, int>)"" IL_019a: ldtoken ""System.Collections.Generic.Comparer<System.ValueTuple<int, int>>"" IL_019f: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_01a4: castclass ""System.Reflection.MethodInfo"" IL_01a9: ldc.i4.2 IL_01aa: newarr ""System.Linq.Expressions.Expression"" IL_01af: dup IL_01b0: ldc.i4.0 IL_01b1: ldloc.0 IL_01b2: ldtoken ""C.<>c__DisplayClass0_0"" IL_01b7: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01bc: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_01c1: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_01c6: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_01cb: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_01d0: stelem.ref IL_01d1: dup IL_01d2: ldc.i4.1 IL_01d3: ldloc.0 IL_01d4: ldtoken ""C.<>c__DisplayClass0_0"" IL_01d9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01de: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_01e3: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_01e8: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_01ed: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_01f2: stelem.ref IL_01f3: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_01f8: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_01fd: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0202: ldloc.1 IL_0203: callvirt ""System.Func<int> System.Linq.Expressions.Expression<System.Func<int>>.Compile()"" IL_0208: callvirt ""int System.Func<int>.Invoke()"" IL_020d: pop IL_020e: ldloc.2 IL_020f: callvirt ""System.Func<int> System.Linq.Expressions.Expression<System.Func<int>>.Compile()"" IL_0214: callvirt ""int System.Func<int>.Invoke()"" IL_0219: pop IL_021a: ldloc.3 IL_021b: callvirt ""System.Func<System.Tuple<int, int>> System.Linq.Expressions.Expression<System.Func<System.Tuple<int, int>>>.Compile()"" IL_0220: callvirt ""System.Tuple<int, int> System.Func<System.Tuple<int, int>>.Invoke()"" IL_0225: pop IL_0226: ldloc.s V_4 IL_0228: callvirt ""System.Func<bool> System.Linq.Expressions.Expression<System.Func<bool>>.Compile()"" IL_022d: callvirt ""bool System.Func<bool>.Invoke()"" IL_0232: pop IL_0233: callvirt ""System.Func<int> System.Linq.Expressions.Expression<System.Func<int>>.Compile()"" IL_0238: callvirt ""int System.Func<int>.Invoke()"" IL_023d: pop IL_023e: ldloc.0 IL_023f: ldtoken ""C.<>c__DisplayClass0_0"" IL_0244: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0249: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_024e: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_0253: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0258: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_025d: ldtoken ""bool System.ValueTuple<int, int>.Equals(System.ValueTuple<int, int>)"" IL_0262: ldtoken ""System.ValueTuple<int, int>"" IL_0267: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_026c: castclass ""System.Reflection.MethodInfo"" IL_0271: ldc.i4.1 IL_0272: newarr ""System.Linq.Expressions.Expression"" IL_0277: dup IL_0278: ldc.i4.0 IL_0279: ldloc.0 IL_027a: ldtoken ""C.<>c__DisplayClass0_0"" IL_027f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0284: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0289: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_028e: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0293: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0298: stelem.ref IL_0299: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_029e: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_02a3: call ""System.Linq.Expressions.Expression<System.Func<bool>> System.Linq.Expressions.Expression.Lambda<System.Func<bool>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_02a8: pop IL_02a9: ldloc.0 IL_02aa: ldtoken ""C.<>c__DisplayClass0_0"" IL_02af: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02b4: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_02b9: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_02be: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_02c3: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_02c8: ldtoken ""int System.ValueTuple<int, int>.CompareTo(System.ValueTuple<int, int>)"" IL_02cd: ldtoken ""System.ValueTuple<int, int>"" IL_02d2: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_02d7: castclass ""System.Reflection.MethodInfo"" IL_02dc: ldc.i4.1 IL_02dd: newarr ""System.Linq.Expressions.Expression"" IL_02e2: dup IL_02e3: ldc.i4.0 IL_02e4: ldloc.0 IL_02e5: ldtoken ""C.<>c__DisplayClass0_0"" IL_02ea: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02ef: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_02f4: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_02f9: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_02fe: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0303: stelem.ref IL_0304: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0309: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_030e: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0313: pop IL_0314: ldstr ""Done."" IL_0319: call ""void System.Console.WriteLine(string)"" IL_031e: ret } "); } [Fact] [WorkItem(24517, "https://github.com/dotnet/roslyn/issues/24517")] public void Issue24517() { var source = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { static void Main() { Expression<Func<ValueTuple<int, int>>> e1 = () => new ValueTuple<int, int>(1, 2); Expression<Func<KeyValuePair<int, int>>> e2 = () => new KeyValuePair<int, int>(1, 2); e1.Compile()(); e2.Compile()(); Console.WriteLine(""Done.""); } }"; var comp = CreateCompilation( source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"Done."); } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); var type = (SourceNamedTypeSymbol)comp.GetMember("System.ValueTuple"); var field = (SourceMemberFieldSymbolFromDeclarator)type.GetMember("Item1"); var underlyingField = field.TupleUnderlyingField; Assert.True(field.RequiresCompletion); Assert.True(underlyingField.RequiresCompletion); Assert.False(field.HasComplete(CompletionPart.All)); Assert.False(underlyingField.HasComplete(CompletionPart.All)); field.ForceComplete(null, default); Assert.True(field.RequiresCompletion); Assert.True(underlyingField.RequiresCompletion); Assert.True(field.HasComplete(CompletionPart.All)); Assert.True(underlyingField.HasComplete(CompletionPart.All)); } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void EmptyValueTuple() { var source = @" namespace System { public struct ValueTuple<T1, T2> { } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "emptyValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); verifier.VerifyTypeIL("ValueTuple`2", @" .class public sequential ansi sealed beforefieldinit System.ValueTuple`2<T1, T2> extends [mscorlib]System.ValueType { .pack 0 .size 1 } // end of class System.ValueTuple`2 "); var client = @" class C { int M((int, int) t) { return t.Item1; } } "; var comp2 = CreateCompilation(client, references: new[] { comp.EmitToImageReference() }, targetFramework: TargetFramework.Mscorlib40); comp2.VerifyDiagnostics( // (6,18): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // return t.Item1; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 18) ); var comp3 = CreateCompilation("", references: new[] { comp.ToMetadataReference() }, targetFramework: TargetFramework.Mscorlib46); var retargetingValueTupleType = (NamedTypeSymbol)comp3.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.IsType<RetargetingNamedTypeSymbol>(retargetingValueTupleType); Assert.Empty(retargetingValueTupleType.GetFieldsToEmit()); verify(retargetingValueTupleType.GetMember<FieldSymbol>("Item1"), retargeting: true, index: 0); verify(retargetingValueTupleType.GetMember<FieldSymbol>("Item2"), retargeting: true, index: 1); AssertEx.SetEqual(new string[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "(T1, T2)..ctor()" }, retargetingValueTupleType.GetMembers().ToTestDisplayStrings()); AssertEx.SetEqual(new string[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "(T1, T2)..ctor()" }, retargetingValueTupleType.GetMembersUnordered().OrderBy(m => m.Name).ToTestDisplayStrings()); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.Empty(type.GetFieldsToEmit()); var item1 = type.GetMember<FieldSymbol>("Item1"); verify(item1, retargeting: false, index: 0); var item2 = type.GetMember<FieldSymbol>("Item2"); verify(item2, retargeting: false, index: 1); } static void verify(FieldSymbol field, bool retargeting, int index) { Assert.True(field.IsDefinition); Assert.True(field.HasUseSiteError); Assert.True(field.IsTupleElement()); Assert.True(field.IsDefaultTupleElement); Assert.Equal(index, field.TupleElementIndex); Assert.Null(field.TupleUnderlyingField); Assert.Same(field, field.CorrespondingTupleField); Assert.False(field.IsExplicitlyNamedTupleElement); } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void EmptyValueTuple_WithCtor() { var source = @" namespace System { public struct ValueTuple<T1, T2> { ValueTuple(T1 item1, T2 item2) => throw null; } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "emptyValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); verifier.VerifyTypeIL("ValueTuple`2", @" .class public sequential ansi sealed beforefieldinit System.ValueTuple`2<T1, T2> extends [mscorlib]System.ValueType { .pack 0 .size 1 // Methods .method private hidebysig specialname rtspecialname instance void .ctor ( !T1 item1, !T2 item2 ) cil managed { // Method begins at RVA 0x2050 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method ValueTuple`2::.ctor } // end of class System.ValueTuple`2 "); var client = @" class C { int M((int, int) t) { return t.Item1; } } "; var comp2 = CreateCompilation(client, references: new[] { comp.EmitToImageReference() }, targetFramework: TargetFramework.Mscorlib40); comp2.VerifyDiagnostics( // (6,18): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // return t.Item1; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 18) ); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.Equal("(T1, T2)", type.ToTestDisplayString()); var fields = type.GetMembers().OfType<FieldSymbol>(); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, fields.ToTestDisplayStrings()); Assert.All(fields, f => Assert.True(f.HasUseSiteError)); Assert.Equal(module is SourceModuleSymbol ? "SourceNamedTypeSymbol" : "PENamedTypeSymbolGeneric", type.GetType().Name); Assert.Empty(type.GetFieldsToEmit()); } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void EmptyValueTuple_WithTupleSyntaxInside() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public (T1, T2) M() => throw null; public (T1 Item1, T2 Item2) M2() => throw null; public (T1, T2 Item2) M3() => throw null; } }"; var comp = CreateCompilation(source + tupleattributes_cs, targetFramework: TargetFramework.Mscorlib40); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M").ReturnType; if (isSourceSymbol) Assert.Equal("SourceNamedTypeSymbol: (T1, T2)", print(tuple1)); else Assert.Equal("PENamedTypeSymbolGeneric: (T1, T2)", print(tuple1)); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1 Item1, T2 Item2)", print(tuple2)); var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1, T2 Item2)", print(tuple3)); } static string print(NamedTypeSymbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void ValueTuple_WithTupleSyntaxInside() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public (T1, T2) M() => throw null; public (T1 Item1, T2 Item2) M2() => throw null; public (T1, T2 Item2) M3() => throw null; } }"; var comp = CreateCompilation(source + tupleattributes_cs, targetFramework: TargetFramework.Mscorlib40); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M").ReturnType; if (isSourceSymbol) Assert.Equal("SourceNamedTypeSymbol: (T1, T2)", print(tuple1)); else Assert.Equal("PENamedTypeSymbolGeneric: (T1, T2)", print(tuple1)); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1 Item1, T2 Item2)", print(tuple2)); var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1, T2 Item2)", print(tuple3)); } static string print(NamedTypeSymbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Fact, WorkItem(43597, "https://github.com/dotnet/roslyn/issues/43597")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void TestValueTuplesDefinition() { var comp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples, targetFramework: TargetFramework.Mscorlib40); CompileAndVerify(comp, sourceSymbolValidator: verifyModule, symbolValidator: verifyModule); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var retargetingValueTupleTypes = comp2.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple"); verifyTupleTypes(retargetingValueTupleTypes, retargeting: true); static void verifyModule(ModuleSymbol module) { var valueTupleTypes = module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple"); verifyTupleTypes(valueTupleTypes, retargeting: false); } static void verifyTupleTypes(ImmutableArray<Symbol> valueTupleTypes, bool retargeting) { AssertEx.SetEqual(new[] { "(T1, T2)", "(T1, T2, T3)", "System.ValueTuple<T1>", "(T1, T2, T3, T4)", "(T1, T2, T3, T4, T5)", "(T1, T2, T3, T4, T5, T6)", "(T1, T2, T3, T4, T5, T6, T7)", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>" }, valueTupleTypes.ToTestDisplayStrings()); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, ((NamedTypeSymbol)valueTupleTypes[0]).GetFieldsToEmit().ToTestDisplayStrings()); verify(valueTupleTypes[0], name: "Item1", display: "T1 (T1, T2).Item1", index: 0); verify(valueTupleTypes[0], "Item2", "T2 (T1, T2).Item2", 1); verify(valueTupleTypes[1], "Item1", "T1 (T1, T2, T3).Item1", 0); verify(valueTupleTypes[1], "Item2", "T2 (T1, T2, T3).Item2", 1); verify(valueTupleTypes[1], "Item3", "T3 (T1, T2, T3).Item3", 2); verify(valueTupleTypes[2], "Item1", "T1 System.ValueTuple<T1>.Item1", 0); verify(valueTupleTypes[3], "Item1", "T1 (T1, T2, T3, T4).Item1", 0); verify(valueTupleTypes[3], "Item2", "T2 (T1, T2, T3, T4).Item2", 1); verify(valueTupleTypes[3], "Item3", "T3 (T1, T2, T3, T4).Item3", 2); verify(valueTupleTypes[3], "Item4", "T4 (T1, T2, T3, T4).Item4", 3); verify(valueTupleTypes[4], "Item1", "T1 (T1, T2, T3, T4, T5).Item1", 0); verify(valueTupleTypes[4], "Item2", "T2 (T1, T2, T3, T4, T5).Item2", 1); verify(valueTupleTypes[4], "Item3", "T3 (T1, T2, T3, T4, T5).Item3", 2); verify(valueTupleTypes[4], "Item4", "T4 (T1, T2, T3, T4, T5).Item4", 3); verify(valueTupleTypes[4], "Item5", "T5 (T1, T2, T3, T4, T5).Item5", 4); verify(valueTupleTypes[5], "Item1", "T1 (T1, T2, T3, T4, T5, T6).Item1", 0); verify(valueTupleTypes[5], "Item2", "T2 (T1, T2, T3, T4, T5, T6).Item2", 1); verify(valueTupleTypes[5], "Item3", "T3 (T1, T2, T3, T4, T5, T6).Item3", 2); verify(valueTupleTypes[5], "Item4", "T4 (T1, T2, T3, T4, T5, T6).Item4", 3); verify(valueTupleTypes[5], "Item5", "T5 (T1, T2, T3, T4, T5, T6).Item5", 4); verify(valueTupleTypes[5], "Item6", "T6 (T1, T2, T3, T4, T5, T6).Item6", 5); verify(valueTupleTypes[6], "Item1", "T1 (T1, T2, T3, T4, T5, T6, T7).Item1", 0); verify(valueTupleTypes[6], "Item2", "T2 (T1, T2, T3, T4, T5, T6, T7).Item2", 1); verify(valueTupleTypes[6], "Item3", "T3 (T1, T2, T3, T4, T5, T6, T7).Item3", 2); verify(valueTupleTypes[6], "Item4", "T4 (T1, T2, T3, T4, T5, T6, T7).Item4", 3); verify(valueTupleTypes[6], "Item5", "T5 (T1, T2, T3, T4, T5, T6, T7).Item5", 4); verify(valueTupleTypes[6], "Item6", "T6 (T1, T2, T3, T4, T5, T6, T7).Item6", 5); verify(valueTupleTypes[6], "Item7", "T7 (T1, T2, T3, T4, T5, T6, T7).Item7", 6); void verify(Symbol tuple, string name, string display, int index) { var isSourceSymbol = tuple.ContainingModule is SourceModuleSymbol; var namedType = (NamedTypeSymbol)tuple; Assert.True(namedType.IsTupleType); Assert.Equal(isSourceSymbol ? "SourceNamedTypeSymbol" : (retargeting ? "RetargetingNamedTypeSymbol" : "PENamedTypeSymbolGeneric"), namedType.GetType().Name); var item = namedType.GetMember<FieldSymbol>(name); if (retargeting) { Assert.IsType<RetargetingFieldSymbol>(item); } else if (isSourceSymbol) { Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(item); } else { Assert.IsType<PEFieldSymbol>(item); } Assert.True(item.IsDefaultTupleElement); Assert.True(item.IsDefinition); Assert.False(item.IsImplicitlyDeclared); Assert.False(item.IsVirtualTupleField); Assert.Equal(display, item.ToTestDisplayString()); Assert.Equal(index, item.TupleElementIndex); Assert.Equal(name, item.Name); Assert.Equal(1, item.Locations.Length); if (retargeting || isSourceSymbol) { Assert.Equal(name, item.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } else { Assert.Empty(item.DeclaringSyntaxReferences); } Assert.Same(item, item.TupleUnderlyingField); Assert.Same(item, item.CorrespondingTupleField); Assert.False(item.IsExplicitlyNamedTupleElement); Assert.Null(item.AssociatedSymbol); } } } [Fact, WorkItem(43597, "https://github.com/dotnet/roslyn/issues/43597")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void TestValueTuple8Definition() { var comp = CreateCompilation(trivialRemainingTuples, targetFramework: TargetFramework.Mscorlib40); CompileAndVerify(comp, sourceSymbolValidator: verifyModule, symbolValidator: verifyModule); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var retargetingValueTupleTypes = comp2.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple"); verifyTuple8Type(retargetingValueTupleTypes[5], retargeting: true); static void verifyModule(ModuleSymbol module) { var valueTupleTypes = module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").As<NamedTypeSymbol>(); AssertEx.SetEqual(new[] { "System.ValueTuple<T1>", "(T1, T2, T3, T4)", "(T1, T2, T3, T4, T5)", "(T1, T2, T3, T4, T5, T6)", "(T1, T2, T3, T4, T5, T6, T7)", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>" }, valueTupleTypes.ToTestDisplayStrings()); } static void verifyTuple8Type(Symbol tuple, bool retargeting) { verify("Item1", "T1 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item1"); verify("Item2", "T2 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item2"); verify("Item3", "T3 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item3"); verify("Item4", "T4 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item4"); verify("Item5", "T5 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item5"); verify("Item6", "T6 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item6"); verify("Item7", "T7 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item7"); verify("Rest", "TRest System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Rest"); void verify(string name, string display) { var isSourceSymbol = tuple.ContainingModule is SourceModuleSymbol; var namedType = (NamedTypeSymbol)tuple; Assert.False(namedType.IsTupleType); var item = namedType.GetMember<FieldSymbol>(name); Assert.Equal(-1, item.TupleElementIndex); if (retargeting) { Assert.IsType<RetargetingFieldSymbol>(item); } else if (isSourceSymbol) { Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(item); } else { Assert.IsType<PEFieldSymbol>(item); } Assert.False(item.IsDefaultTupleElement); Assert.True(item.IsDefinition); Assert.False(item.IsImplicitlyDeclared); Assert.False(item.IsVirtualTupleField); Assert.Equal(display, item.ToTestDisplayString()); Assert.Equal(-1, item.TupleElementIndex); Assert.Equal(name, item.Name); Assert.Equal(1, item.Locations.Length); if (retargeting || isSourceSymbol) { Assert.Equal(name, item.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } else { Assert.Empty(item.DeclaringSyntaxReferences); } Assert.Null(item.TupleUnderlyingField); Assert.Null(item.CorrespondingTupleField); Assert.False(item.IsExplicitlyNamedTupleElement); Assert.Null(item.AssociatedSymbol); } } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void TestValueTuple2Definition_WithExtraField() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public string field; } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "customValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); var comp3 = CreateCompilation("", references: new[] { comp.ToMetadataReference() }, targetFramework: TargetFramework.Mscorlib46); var retargetingValueTupleType = (NamedTypeSymbol)comp3.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.IsType<RetargetingNamedTypeSymbol>(retargetingValueTupleType); verifyTupleType(retargetingValueTupleType, retargeting: true); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); verifyTupleType(type, retargeting: false); } static void verifyTupleType(NamedTypeSymbol namedType, bool retargeting) { Assert.Equal("(T1, T2)", namedType.ToTestDisplayString()); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "System.String (T1, T2).field" }, namedType.GetFieldsToEmit().ToTestDisplayStrings()); var fields = namedType.GetMembers().OfType<FieldSymbol>(); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "System.String (T1, T2).field" }, fields.ToTestDisplayStrings()); Assert.All(fields, f => Assert.False(f.HasUseSiteError)); verify("Item1", "T1 (T1, T2).Item1", isTupleElement: true); verify("Item2", "T2 (T1, T2).Item2", true); verify("field", "System.String (T1, T2).field", false); void verify(string name, string display, bool isTupleElement) { var isSourceSymbol = namedType.ContainingModule is SourceModuleSymbol; Assert.True(namedType.IsTupleType); var item = namedType.GetMember<FieldSymbol>(name); if (retargeting) { Assert.IsType<RetargetingFieldSymbol>(item); } else if (isSourceSymbol) { Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(item); } else { Assert.IsType<PEFieldSymbol>(item); } Assert.Equal(isTupleElement, item.IsDefaultTupleElement); Assert.True(item.IsDefinition); Assert.False(item.IsImplicitlyDeclared); Assert.False(item.IsVirtualTupleField); Assert.Equal(display, item.ToTestDisplayString()); Assert.Equal(name, item.Name); Assert.Equal(1, item.Locations.Length); if (retargeting || isSourceSymbol) { Assert.Equal(name, item.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } else { Assert.Empty(item.DeclaringSyntaxReferences); } if (isTupleElement) { Assert.Same(item, item.CorrespondingTupleField); } else { Assert.Equal(-1, item.TupleElementIndex); Assert.Null(item.CorrespondingTupleField); } Assert.False(item.IsExplicitlyNamedTupleElement); Assert.Same(item, item.TupleUnderlyingField); Assert.Null(item.AssociatedSymbol); } } } [Fact] public void TestValueTuple2Definition_WithExtraAutoProperty() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public string Property { get; set; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "customValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var namedType = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); var isSourceSymbol = namedType.ContainingModule is SourceModuleSymbol; Assert.Equal("(T1, T2)", namedType.ToTestDisplayString()); var fields = namedType.GetMembers().OfType<FieldSymbol>(); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "System.String (T1, T2).<Property>k__BackingField" }, fields.ToTestDisplayStrings()); var backingField = namedType.GetField("<Property>k__BackingField"); if (isSourceSymbol) { Assert.IsType<SynthesizedBackingFieldSymbol>(backingField); Assert.Equal("System.String (T1, T2).Property { get; set; }", backingField.AssociatedSymbol.ToTestDisplayString()); } else { Assert.IsType<PEFieldSymbol>(backingField); Assert.Null(backingField.AssociatedSymbol); } } } [Fact] public void SwitchWithNamedTuple() { var source = @" class C { static int M() { var isColInit = true; var errorCode = (message: """", isColInit) switch { (message: null, isColInit: true) => 42, (message: null, isColInit: false) => 43, (message: { }, isColInit: true) => 44, (message: { }, isColInit: false) => 45, }; return errorCode; } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_Item2() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item2; public T1 Item13; public T1 Rest; } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); var item2 = type.GetMember<FieldSymbol>("Item2"); verify(item2); var item13 = type.GetMember<FieldSymbol>("Item13"); verify(item13); var rest = type.GetMember<FieldSymbol>("Rest"); verify(rest); } static void verify(FieldSymbol field) { Assert.False(field.IsTupleElement()); Assert.False(field.IsDefaultTupleElement); Assert.Equal(-1, field.TupleElementIndex); Assert.Same(field, field.TupleUnderlyingField); Assert.Null(field.CorrespondingTupleField); } } [Fact] public void TupleWithElementNamedWithDefaultName() { // Instrumenting test as part of investigating flakiness: https://github.com/dotnet/roslyn/issues/52658 for (int i = 0; i < 1000; i++) { string source = @" class C { (int Item1, int Item2) M() => throw null; } "; var comp = CreateCompilation(source); var m = (MethodSymbol)comp.GetMember("C.M"); var tuple = m.ReturnType; Assert.Equal("(System.Int32 Item1, System.Int32 Item2)", tuple.ToTestDisplayString()); Assert.IsType<ConstructedNamedTypeSymbol>(tuple); var item1 = tuple.GetMember<TupleElementFieldSymbol>("Item1"); // Instrumenting test as part of investigating flakiness: https://github.com/dotnet/roslyn/issues/52658 RoslynDebug.AssertOrFailFast(0 == item1.TupleElementIndex); var item1Underlying = item1.TupleUnderlyingField; Assert.IsType<SubstitutedFieldSymbol>(item1Underlying); Assert.Equal("System.Int32 (System.Int32 Item1, System.Int32 Item2).Item1", item1Underlying.ToTestDisplayString()); // Instrumenting test as part of investigating flakiness: https://github.com/dotnet/roslyn/issues/52658 RoslynDebug.AssertOrFailFast(0 == item1Underlying.TupleElementIndex); Assert.Same(item1Underlying, item1Underlying.TupleUnderlyingField); var item2 = tuple.GetMember<TupleElementFieldSymbol>("Item2"); Assert.Equal(1, item2.TupleElementIndex); var item2Underlying = item2.TupleUnderlyingField; Assert.IsType<SubstitutedFieldSymbol>(item2Underlying); Assert.Equal(1, item2Underlying.TupleElementIndex); Assert.Same(item2Underlying, item2Underlying.TupleUnderlyingField); } } [Fact] public void IndexOfUnderlyingFieldsInTuple9() { string source = @" class C { (int, int, int, int, int, int, int, int, int) M() => throw null; } "; var comp = CreateCompilation(source); var m = (MethodSymbol)comp.GetMember("C.M"); var tuple = m.ReturnType; Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", tuple.ToTestDisplayString()); Assert.IsType<ConstructedNamedTypeSymbol>(tuple); var item8 = tuple.GetMember<TupleElementFieldSymbol>("Item8"); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", item8.ToTestDisplayString()); Assert.Equal(7, item8.TupleElementIndex); var item8Underlying = item8.TupleUnderlyingField; Assert.Equal("Item1", item8Underlying.Name); Assert.IsType<SubstitutedFieldSymbol>(item8Underlying); Assert.Equal(0, item8Underlying.TupleElementIndex); Assert.Same(item8Underlying, item8Underlying.TupleUnderlyingField); var item9 = tuple.GetMember<TupleElementFieldSymbol>("Item9"); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", item9.ToTestDisplayString()); Assert.Equal(8, item9.TupleElementIndex); var item9Underlying = item9.TupleUnderlyingField; Assert.Equal("Item2", item9Underlying.Name); Assert.IsType<SubstitutedFieldSymbol>(item9Underlying); Assert.Equal(1, item9Underlying.TupleElementIndex); Assert.Same(item9Underlying, item9Underlying.TupleUnderlyingField); } [Fact] public void RealFieldsAreNotWrapped() { string source = @" public class C { public (int, int) M() => throw null; public (int Item1, int Item2) M2() => throw null; public (int a, int b) M3() => throw null; } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public int field; public ValueTuple(T1 item1, T2 item2) => throw null; } } "; var comp = CreateCompilation(source); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); assertValueTupleUnderlyingFields(type, isSourceSymbol); if (isSourceSymbol) { Assert.Equal("SourceNamedTypeSymbol: (T1, T2)", print(type)); AssertEx.SetEqual(new[] { "SourceMemberFieldSymbolFromDeclarator: field", "SourceMemberFieldSymbolFromDeclarator: Item1", "SourceMemberFieldSymbolFromDeclarator: Item2" }, printFields(type)); } else { Assert.Equal("PENamedTypeSymbolGeneric: (T1, T2)", print(type)); AssertEx.SetEqual(new[] { "PEFieldSymbol: field", "PEFieldSymbol: Item1", "PEFieldSymbol: Item2" }, printFields(type)); } var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32)", print(tuple1)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2" }, printFields(tuple1)); assertTupleUnderlyingFields(tuple1); var tuple1Item1 = tuple1.GetMember<FieldSymbol>("Item1"); Assert.False(tuple1Item1.IsDefinition); Assert.Equal("T1 (T1, T2).Item1", tuple1Item1.OriginalDefinition.ToTestDisplayString()); Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", tuple1Item1.OriginalDefinition.GetType().Name); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 Item1, System.Int32 Item2)", print(tuple2)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2" }, printFields(tuple2)); assertTupleUnderlyingFields(tuple2); var tuple2Item1 = tuple2.GetMember<FieldSymbol>("Item1"); Assert.False(tuple2Item1.IsDefinition); Assert.Equal("T1 (T1, T2).Item1", tuple2Item1.OriginalDefinition.ToTestDisplayString()); Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", tuple2Item1.OriginalDefinition.GetType().Name); var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 a, System.Int32 b)", print(tuple3)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleVirtualElementFieldSymbol: a", "TupleElementFieldSymbol: Item2", "TupleVirtualElementFieldSymbol: b", }, printFields(tuple3)); assertTupleUnderlyingFields(tuple3); var tuple3Item1 = tuple3.GetMember<FieldSymbol>("Item1"); Assert.False(tuple3Item1.IsDefinition); Assert.Equal("T1 (T1, T2).Item1", tuple3Item1.OriginalDefinition.ToTestDisplayString()); Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", tuple3Item1.OriginalDefinition.GetType().Name); Assert.True(tuple3.GetMember<FieldSymbol>("a").IsDefinition); Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32)", print(tuple3.TupleUnderlyingType)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2" }, printFields(tuple3.TupleUnderlyingType)); } static void assertValueTupleUnderlyingFields(NamedTypeSymbol type, bool isSourceSymbol) { var fields = type.GetMembers().OfType<FieldSymbol>(); foreach (var field in fields) { var underlying = field.TupleUnderlyingField; Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", underlying.GetType().Name); Assert.Equal(isSourceSymbol ? "SourceNamedTypeSymbol" : "PENamedTypeSymbolGeneric", underlying.ContainingType.GetType().Name); } } static void assertTupleUnderlyingFields(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); foreach (var field in fields) { var underlying = field.TupleUnderlyingField; Assert.Equal("SubstitutedFieldSymbol", underlying.GetType().Name); Assert.Equal("ConstructedNamedTypeSymbol", underlying.ContainingType.GetType().Name); } } static IEnumerable<string> printFields(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); return fields.Select(s => s.GetType().Name + ": " + s.Name); } static string print(Symbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Fact] public void RealFieldsAreNotWrapped_LongTuples() { string source = @" public class C { public (int, int, int, int, int, int, int, int) M() => throw null; public (int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M2() => throw null; public (int a, int b, int c, int d, int e, int f, int g, int h) M3() => throw null; public System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> M4() => throw null; } "; var comp = CreateCompilation(source + trivialRemainingTuples); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", print(tuple1)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple1)); assertUnderlying(tuple1); Assert.True(tuple1.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item8").IsDefinition); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)", print(tuple2)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple2)); assertUnderlying(tuple2); Assert.True(tuple2.TupleUnderlyingType.Equals(tuple1, TypeCompareKind.ConsiderEverything)); Assert.True(tuple2.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item8").IsDefinition); var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32 h)", print(tuple3)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8", "TupleVirtualElementFieldSymbol: a", "TupleVirtualElementFieldSymbol: b", "TupleVirtualElementFieldSymbol: c", "TupleVirtualElementFieldSymbol: d", "TupleVirtualElementFieldSymbol: e", "TupleVirtualElementFieldSymbol: f", "TupleVirtualElementFieldSymbol: g", "TupleVirtualElementFieldSymbol: h", }, printFields(tuple3)); assertUnderlying(tuple3); Assert.True(tuple3.TupleUnderlyingType.Equals(tuple1, TypeCompareKind.ConsiderEverything)); Assert.True(tuple3.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item8").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("a").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("b").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("c").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("d").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("e").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("f").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("g").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("h").IsDefinition); Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", print(tuple3.TupleUnderlyingType)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple3.TupleUnderlyingType)); var tuple4 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M4").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", print(tuple4)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple4)); assertUnderlying(tuple4); Assert.True(tuple4.TupleUnderlyingType.Equals(tuple1, TypeCompareKind.ConsiderEverything)); Assert.True(tuple4.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item8").IsDefinition); } static void assertUnderlying(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); foreach (var field in fields) { var underlying = field.TupleUnderlyingField; Assert.Equal("SubstitutedFieldSymbol", underlying.GetType().Name); Assert.Equal("ConstructedNamedTypeSymbol", underlying.ContainingType.GetType().Name); } } static IEnumerable<string> printFields(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); return fields.Select(s => s.GetType().Name + ": " + s.Name); } static string print(NamedTypeSymbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Theory, WorkItem(43857, "https://github.com/dotnet/roslyn/issues/43857")] [InlineData("(Z a, Z b)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")] [InlineData("(Z, Z b)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, ""b""})")] [InlineData("(Z a, Z)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", null})")] [InlineData("(Z, Z)*", null)] [InlineData("((Z a, Z b), Z c)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, ""c"", ""a"", ""b""})")] public void PointerTypeDecoding(string type, string expectedAttribute) { var comp = CompileAndVerify($@" unsafe struct Z {{ public {type} F; }} ", options: TestOptions.UnsafeReleaseDll, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("Z"); var field = c.GetField("F"); if (expectedAttribute == null) { Assert.Empty(field.GetAttributes()); } else { Assert.Equal(expectedAttribute, field.GetAttributes().Single().ToString()); } Assert.Equal(type, field.Type.ToTestDisplayString()); } } [Fact] public void TupleAsMemberTests() { // Use minimal framework to force the tuple symbols to be generated as ErrorFields, because they couldn't be matched with the // nonexistent System.ValueTuple's fields. var comp = CreateCompilation("", targetFramework: TargetFramework.Minimal); var @object = comp.GetSpecialType(SpecialType.System_Object); var obliviousObject = TypeWithAnnotations.Create(@object, NullableAnnotation.Oblivious); // (object~ a, object~ b, object~ c, object~ d, object~ e, object~ f, object~ g, object~ h, object~ i) // All positions are errored var obliviousOriginalTuple = NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: ImmutableArray.Create(obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject), elementLocations: ImmutableArray.Create<Location>(null, null, null, null, null, null, null, null, null), elementNames: ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "h", "i"), comp, shouldCheckConstraints: false, includeNullability: false, errorPositions: ImmutableArray.Create(true, true, true, true, true, true, true, true, true)); AssertEx.Equal("System.ValueTuple<System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, (System.Object, System.Object)>", obliviousOriginalTuple.ToTestDisplayString(includeNonNullable: true)); var nullableObject = TypeWithAnnotations.Create(@object, NullableAnnotation.Annotated); var nonNullableObject = TypeWithAnnotations.Create(@object, NullableAnnotation.NotAnnotated); // (object!, object?, object!, object?, object!, object?, object!, object?, object!) // All positions are errored var nullableEnabledTuple = NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: ImmutableArray.Create(nonNullableObject, nullableObject, nonNullableObject, nullableObject, nonNullableObject, nullableObject, nonNullableObject, nullableObject, nonNullableObject), elementLocations: ImmutableArray.Create<Location>(null, null, null, null, null, null, null, null, null), elementNames: default, comp, shouldCheckConstraints: false, includeNullability: false, errorPositions: ImmutableArray.Create(true, true, true, true, true, true, true, true, true)); AssertEx.Equal("System.ValueTuple<System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, (System.Object?, System.Object!)>", nullableEnabledTuple.ToTestDisplayString(includeNonNullable: true)); // Original tuple fields as a member of the nullable-enabled tuple, should carry the names over for (int i = 0; i < obliviousOriginalTuple.TupleElements.Length; i++) { var originalField = (TupleErrorFieldSymbol)obliviousOriginalTuple.TupleElements[i]; verifyIndexAndDefaultElement(originalField, i, isDefaultElement: false); var nullabilityString = (i % 2 == 1) ? "?" : "!"; var name = ((char)('a' + i)).ToString(); var newField = (TupleErrorFieldSymbol)originalField.AsMember(nullableEnabledTuple); AssertEx.Equal($"System.Object{nullabilityString} System.ValueTuple<System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, (System.Object?, System.Object!)>.{name}", newField.ToTestDisplayString(includeNonNullable: true)); verifyIndexAndDefaultElement(newField, i, isDefaultElement: false); verifyDefaultFieldType(newField, i, nullabilityString); var newDefaultField = (TupleErrorFieldSymbol)newField.CorrespondingTupleField; verifyIndexAndDefaultElement(newDefaultField, i, isDefaultElement: true); verifyDefaultFieldType(newDefaultField, i, nullabilityString); var originalDefaultField = (TupleErrorFieldSymbol)originalField.CorrespondingTupleField; verifyIndexAndDefaultElement(originalDefaultField, i, isDefaultElement: true); newDefaultField = (TupleErrorFieldSymbol)originalDefaultField.AsMember(nullableEnabledTuple); verifyIndexAndDefaultElement(newDefaultField, i, isDefaultElement: true); verifyDefaultFieldType(newDefaultField, i, nullabilityString); } static void verifyIndexAndDefaultElement(TupleErrorFieldSymbol tupleField, int i, bool isDefaultElement) { Assert.Equal(i, tupleField.TupleElementIndex); Assert.Equal(isDefaultElement, tupleField.IsDefaultTupleElement); } static void verifyDefaultFieldType(FieldSymbol tupleField, int i, string nullabilityString) { AssertEx.Equal($"System.Object{nullabilityString} System.ValueTuple<System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, (System.Object?, System.Object!)>.Item{i + 1}", tupleField.CorrespondingTupleField.ToTestDisplayString(includeNonNullable: 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Reflection.Metadata; using System.Text; 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.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static TestResources.NetFX.ValueTuple; using static Roslyn.Test.Utilities.TestMetadata; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.Tuples)] public class CodeGenTupleTests : CSharpTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; private static readonly string trivial2uple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } "; private static readonly string trivial3uple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 item1, T2 item2, T3 item3) { this.Item1 = item1; this.Item2 = item2; this.Item3 = item3; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + "", "" + Item3?.ToString() + '}'; } } } "; private static readonly string trivialRemainingTuples = @" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { this.Item1 = item1; } public override string ToString() { return '{' + Item1?.ToString() + '}'; } } public struct ValueTuple<T1, T2, T3, T4> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; } } public struct ValueTuple<T1, T2, T3, T4, T5> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override string ToString() { return base.ToString(); } } } "; [Fact] public void BadValueTupleByItself() { var source = @" namespace System { struct ValueTuple<T1, T2> { public T1 Item1; private T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics( // (7,20): warning CS0169: The field '(T1, T2).Item2' is never used // private T2 Item2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(7, 20), // (8,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(8, 16), // (8,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(8, 16), // (11,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = item2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(11, 18) ); } [Fact] public void ValueTupleWithDifferentNamesInOperator() { var source = @" namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static bool operator +((T1 a, T2 b) t) => throw null; public static bool operator true((T1 a, T2 b) t) => throw null; public static bool operator false((T1 a, T2 b) t) => throw null; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); } [Fact] public void MergeNamesFromTypelessTuple() { var src = @" class C { T M<T>(T x, T y) => throw null; void M2() { var t = M((a: 1, b: ""hello""), (a: default, b: null)); t.a.ToString(); t.b.ToString(); var t2 = M((a: 1, b: ""hello""), (a: default, z: null)); // 1 t2.a.ToString(); t2.b.ToString(); var t3 = M((1, ""hello""), (a: default, b: null)); // 2, 3 t3.a.ToString(); // 4 t3.b.ToString(); // 5 } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,53): warning CS8123: The tuple element name 'z' is ignored because a different name or no name is specified by the target type '(int a, string b)'. // var t2 = M((a: 1, b: "hello"), (a: default, z: null)); // 1 Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "z: null").WithArguments("z", "(int a, string b)").WithLocation(11, 53), // (15,35): warning CS8123: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(int, string)'. // var t3 = M((1, "hello"), (a: default, b: null)); // 2, 3 Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: default").WithArguments("a", "(int, string)").WithLocation(15, 35), // (15,47): warning CS8123: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(int, string)'. // var t3 = M((1, "hello"), (a: default, b: null)); // 2, 3 Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: null").WithArguments("b", "(int, string)").WithLocation(15, 47), // (16,12): error CS1061: '(int, string)' does not contain a definition for 'a' and no accessible extension method 'a' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // t3.a.ToString(); // 4 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, string)", "a").WithLocation(16, 12), // (17,12): error CS1061: '(int, string)' does not contain a definition for 'b' and no accessible extension method 'b' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // t3.b.ToString(); // 5 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b").WithArguments("(int, string)", "b").WithLocation(17, 12) ); } [Fact] public void InferenceWithTupleNamesInNullableContext() { var src = @" #nullable enable public class C<T> { void M(C<(int a, string b)> list) { _ = list.Select(i => i.a); } } public static class Extensions { public static T2 Select<T1, T2>(this C<T1> list, System.Func<T1, T2> f) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void InterfaceImplAttributesAreNotSharedAcrossTypeRefs() { var src1 = @" public interface I1<T> {} public interface I2 : I1<(int a, int b)> {} public interface I3 : I1<(int c, int d)> {}"; var src2 = @" class C1 : I2, I1<(int a, int b)> {} class C2 : I3, I1<(int c, int d)> {}"; var comp1 = CreateCompilation(src1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(src2, references: new[] { comp1.ToMetadataReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(src2, references: new[] { comp1.EmitToImageReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")] public void ConstraintAttributesAreNotSharedAcrossTypeRefs() { var src1 = @" using System.Collections.Generic; public abstract class C1 { public abstract void M<T>(T t) where T : IEnumerable<(int a, int b)>; } public abstract class C2 { public abstract void M<T>(T t) where T : IEnumerable<(int c, int d)>; }"; var src2 = @" class C3 : C1 { public override void M<U>(U u) { int x; foreach (var kvp in u) { x = kvp.a + kvp.b; } } } class C4 : C2 { public override void M<U>(U u) { int x; foreach (var kvp in u) { x = kvp.c + kvp.d; } } }"; var comp1 = CreateCompilationWithMscorlib40(src1, references: s_valueTupleRefs); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40(src2, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef, comp1.ToMetadataReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilationWithMscorlib40(src2, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef, comp1.EmitToImageReference() }); comp3.VerifyDiagnostics(); } [Fact] public void InterfaceAttributes() { var comp = CreateCompilation(@" using System; using System.Collections; using System.Collections.Generic; interface ITest<T> { T Get(); } public class C : ITest<(int key, int val)> { public (int key, int val) Get() => (0, 0); } public class Base<T> : ITest<T> { public T Get() => default(T); } public class C2 : Base<(int x, int y)> { } public class C3 : IEnumerable<(int key, int val)> { private readonly (int, int)[] _backing; public C3((int, int)[] backing) { _backing = backing; } private class Inner : IEnumerator<(int key, int val)>, IEnumerator { private int index = -1; private readonly (int, int)[] _backing; public Inner((int, int)[] backing) { _backing = backing; } public (int key, int val) Current => _backing[index]; object IEnumerator.Current => Current; public void Dispose() { } public bool MoveNext() => ++index < _backing.Length; public void Reset() { throw new NotSupportedException(); } } IEnumerator<(int key, int val)> IEnumerable<(int key, int val)>.GetEnumerator() => new Inner(_backing); IEnumerator IEnumerable.GetEnumerator() => new Inner(_backing); } public class C4 : C3 { public C4((int, int)[] backing) : base(backing) { } } "); CompileAndVerify(comp, symbolValidator: m => { var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.Interfaces().Length); NamedTypeSymbol iface = c.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); TypeSymbol typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.False(((NamedTypeSymbol)typeArg).IsSerializable); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); var c2 = m.GlobalNamespace.GetTypeMember("C2"); var @base = c2.BaseType(); Assert.Equal("Base", @base.Name); Assert.Equal(1, @base.Interfaces().Length); iface = @base.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "x", "y" }, typeArg.TupleElementNames); var c3 = m.GlobalNamespace.GetTypeMember("C3"); Assert.Equal(2, c3.Interfaces().Length); iface = c3.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); var d = m.GlobalNamespace.GetTypeMember("C3"); Assert.Equal(2, d.Interfaces().Length); iface = d.Interfaces()[0]; Assert.True(iface.IsGenericType); Assert.Equal(1, iface.TypeArguments().Length); typeArg = iface.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); }); CompileAndVerify(@" using System; class D { public static void Main(string[] args) { var c = new C(); var temp = c.Get(); Console.WriteLine(temp); Console.WriteLine(""key: "" + temp.key); Console.WriteLine(""val: "" + temp.val); var c2 = new C2(); var temp2 = c2.Get(); Console.WriteLine(temp); Console.WriteLine(""x: "" + temp2.x); Console.WriteLine(""y: "" + temp2.y); var backing = new[] { (1, 1), (2, 2), (3, 3) }; var c3 = new C3(backing); foreach (var kvp in c3) { Console.WriteLine($""(key: {kvp.key}, val: {kvp.val})""); } var c4 = new C4(backing); foreach (var kvp in c4) { Console.WriteLine($""(key: {kvp.key}, val: {kvp.val})""); } } }", references: new[] { comp.EmitToImageReference() }, expectedOutput: @"(0, 0) key: 0 val: 0 (0, 0) x: 0 y: 0 (key: 1, val: 1) (key: 2, val: 2) (key: 3, val: 3) (key: 1, val: 1) (key: 2, val: 2) (key: 3, val: 3)"); } [Fact] public void GenericConstraintAttributes() { var comp = CreateCompilation(@" using System; using System.Collections; using System.Collections.Generic; public interface ITest<T> { T Get { get; } } public class Test : ITest<(int key, int val)> { public (int key, int val) Get => (0, 0); } public class Base<T> : ITest<T> { public T Get { get; } protected Base(T t) { Get = t; } } public class C<T> where T : ITest<(int key, int val)> { public T Get { get; } public C(T t) { Get = t; } } public class C2<T> where T : Base<(int key, int val)> { public T Get { get; } public C2(T t) { Get = t; } } public sealed class Test2 : Base<(int key, int val)> { public Test2() : base((-1, -2)) {} } public class C3<T> where T : IEnumerable<(int key, int val)> { public T Get { get; } public C3(T t) { Get = t; } } public struct TestEnumerable : IEnumerable<(int key, int val)> { private readonly (int, int)[] _backing; public TestEnumerable((int, int)[] backing) { _backing = backing; } private class Inner : IEnumerator<(int key, int val)>, IEnumerator { private int index = -1; private readonly (int, int)[] _backing; public Inner((int, int)[] backing) { _backing = backing; } public (int key, int val) Current => _backing[index]; object IEnumerator.Current => Current; public void Dispose() { } public bool MoveNext() => ++index < _backing.Length; public void Reset() { throw new NotSupportedException(); } } IEnumerator<(int key, int val)> IEnumerable<(int key, int val)>.GetEnumerator() => new Inner(_backing); IEnumerator IEnumerable.GetEnumerator() => new Inner(_backing); } "); CompileAndVerify(comp, symbolValidator: m => { var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.TypeParameters.Length); var param = c.TypeParameters[0]; Assert.Equal(1, param.ConstraintTypes().Length); var constraint = Assert.IsAssignableFrom<NamedTypeSymbol>(param.ConstraintTypes()[0]); Assert.True(constraint.IsGenericType); Assert.Equal(1, constraint.TypeArguments().Length); TypeSymbol typeArg = constraint.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.False(typeArg.TupleElementNames.IsDefault); Assert.Equal(2, typeArg.TupleElementNames.Length); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); var c2 = m.GlobalNamespace.GetTypeMember("C2"); Assert.Equal(1, c2.TypeParameters.Length); param = c2.TypeParameters[0]; Assert.Equal(1, param.ConstraintTypes().Length); constraint = Assert.IsAssignableFrom<NamedTypeSymbol>(param.ConstraintTypes()[0]); Assert.True(constraint.IsGenericType); Assert.Equal(1, constraint.TypeArguments().Length); typeArg = constraint.TypeArguments()[0]; Assert.True(typeArg.IsTupleType); Assert.Equal(2, typeArg.TupleElementTypesWithAnnotations.Length); Assert.All(typeArg.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); Assert.False(typeArg.TupleElementNames.IsDefault); Assert.Equal(2, typeArg.TupleElementNames.Length); Assert.Equal(new[] { "key", "val" }, typeArg.TupleElementNames); }); CompileAndVerify(@" using System; class D { public static void Main(string[] args) { var c = new C<Test>(new Test()); var temp = c.Get.Get; Console.WriteLine(temp); Console.WriteLine(""key: "" + temp.key); Console.WriteLine(""val: "" + temp.val); var c2 = new C2<Test2>(new Test2()); var temp2 = c2.Get.Get; Console.WriteLine(temp2); Console.WriteLine(""key: "" + temp2.key); Console.WriteLine(""val: "" + temp2.val); var backing = new[] { (1, 2), (3, 4), (5, 6) }; var c3 = new C3<TestEnumerable>(new TestEnumerable(backing)); foreach (var kvp in c3.Get) { Console.WriteLine($""key: {kvp.key}, val: {kvp.val}""); } var c4 = new C<Test2>(new Test2()); var temp4 = c4.Get.Get; Console.WriteLine(temp4); Console.WriteLine(""key: "" + temp4.key); Console.WriteLine(""val: "" + temp4.val); } }", references: new[] { comp.EmitToImageReference() }, expectedOutput: @"(0, 0) key: 0 val: 0 (-1, -2) key: -1 val: -2 key: 1, val: 2 key: 3, val: 4 key: 5, val: 6 (-1, -2) key: -1 val: -2 "); } [Fact] public void BadTupleNameMetadata() { var comp = CreateCompilationWithILAndMscorlib40("", @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooFewNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooManyNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooFewNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooFewNamesMethod .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooManyNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooManyNamesMethod } // end of class C ", references: s_valueTupleRefs); var c = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var validField = c.GetMember<FieldSymbol>("ValidField"); Assert.False(validField.Type.IsErrorType()); Assert.True(validField.Type.IsTupleType); Assert.True(validField.Type.TupleElementNames.IsDefault); var validFieldWithAttribute = c.GetMember<FieldSymbol>("ValidFieldWithAttribute"); Assert.True(validFieldWithAttribute.Type.IsErrorType()); Assert.False(validFieldWithAttribute.Type.IsTupleType); Assert.IsType<UnsupportedMetadataTypeSymbol>(validFieldWithAttribute.Type); var tooFewNames = c.GetMember<FieldSymbol>("TooFewNames"); Assert.True(tooFewNames.Type.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooFewNames.Type); Assert.False(((NamedTypeSymbol)tooFewNames.Type).IsSerializable); var tooManyNames = c.GetMember<FieldSymbol>("TooManyNames"); Assert.True(tooManyNames.Type.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooManyNames.Type); var tooFewNamesMethod = c.GetMember<MethodSymbol>("TooFewNamesMethod"); Assert.True(tooFewNamesMethod.ReturnType.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooFewNamesMethod.ReturnType); var tooManyNamesMethod = c.GetMember<MethodSymbol>("TooManyNamesMethod"); Assert.True(tooManyNamesMethod.ReturnType.IsErrorType()); Assert.IsType<UnsupportedMetadataTypeSymbol>(tooManyNamesMethod.ReturnType); } [Fact] public void MetadataForPartiallyNamedTuples() { var comp = CreateCompilationWithILAndMscorlib40("", @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // In source, all or no names must be specified for a tuple .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> PartialNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](""e1"", null)} = ( 01 00 02 00 00 00 02 65 31 FF ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> AllNullNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](null, null)} = ( 01 00 02 00 00 00 ff ff 00 00 ) .method public hidebysig instance void PartialNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, ""e1"", null)} = ( 01 00 03 00 00 00 FF 02 65 31 FF ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::PartialNamesMethod .method public hidebysig instance void AllNullNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, null, null)} = ( 01 00 03 00 00 00 ff ff ff 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::AllNullNamesMethod } // end of class C ", targetFramework: TargetFramework.Mscorlib40, references: s_valueTupleRefs); var c = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var validField = c.GetMember<FieldSymbol>("ValidField"); Assert.False(validField.Type.IsErrorType()); Assert.True(validField.Type.IsTupleType); Assert.True(validField.Type.TupleElementNames.IsDefault); var validFieldWithAttribute = c.GetMember<FieldSymbol>("ValidFieldWithAttribute"); Assert.True(validFieldWithAttribute.Type.IsErrorType()); Assert.False(validFieldWithAttribute.Type.IsTupleType); Assert.IsType<UnsupportedMetadataTypeSymbol>(validFieldWithAttribute.Type); var partialNames = c.GetMember<FieldSymbol>("PartialNames"); Assert.False(partialNames.Type.IsErrorType()); Assert.True(partialNames.Type.IsTupleType); Assert.Equal("(System.Int32 e1, System.Int32)", partialNames.TypeWithAnnotations.ToTestDisplayString()); var allNullNames = c.GetMember<FieldSymbol>("AllNullNames"); Assert.False(allNullNames.Type.IsErrorType()); Assert.True(allNullNames.Type.IsTupleType); Assert.Equal("(System.Int32, System.Int32)", allNullNames.TypeWithAnnotations.ToTestDisplayString()); var partialNamesMethod = c.GetMember<MethodSymbol>("PartialNamesMethod"); var partialParamType = partialNamesMethod.Parameters.Single().TypeWithAnnotations; Assert.False(partialParamType.Type.IsErrorType()); Assert.True(partialParamType.Type.IsTupleType); Assert.Equal("System.ValueTuple<(System.Int32 e1, System.Int32)>", partialParamType.ToTestDisplayString()); var allNullNamesMethod = c.GetMember<MethodSymbol>("AllNullNamesMethod"); var allNullParamType = allNullNamesMethod.Parameters.Single().TypeWithAnnotations; Assert.False(allNullParamType.Type.IsErrorType()); Assert.True(allNullParamType.Type.IsTupleType); Assert.Equal("System.ValueTuple<(System.Int32, System.Int32)>", allNullParamType.ToTestDisplayString()); } [Fact] public void NestedTuplesNoAttribute() { var comp = CreateCompilationWithILAndMscorlib40("", @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base`1<T> extends [mscorlib]System.Object { } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> Field1 .field public class Base`1<class [System.ValueTuple]System.ValueTuple`1< class [System.ValueTuple]System.ValueTuple`2<int32, int32>>> Field2; } // end of class C ", references: s_valueTupleRefs); var c = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var base1 = comp.GlobalNamespace.GetTypeMember("Base"); Assert.NotNull(base1); var field1 = c.GetMember<FieldSymbol>("Field1"); Assert.False(field1.Type.IsErrorType()); Assert.True(field1.Type.IsTupleType); Assert.True(field1.Type.TupleElementNames.IsDefault); NamedTypeSymbol field2Type = (NamedTypeSymbol)c.GetMember<FieldSymbol>("Field2").Type; Assert.Equal(base1, field2Type.OriginalDefinition); Assert.True(field2Type.IsGenericType); var first = field2Type.TypeArguments()[0]; Assert.True(first.IsTupleType); Assert.Equal(1, first.TupleElementTypesWithAnnotations.Length); Assert.True(first.TupleElementNames.IsDefault); var second = first.TupleElementTypesWithAnnotations[0].Type; Assert.True(second.IsTupleType); Assert.True(second.TupleElementNames.IsDefault); Assert.Equal(2, second.TupleElementTypesWithAnnotations.Length); Assert.All(second.TupleElementTypesWithAnnotations, t => Assert.Equal(SpecialType.System_Int32, t.SpecialType)); } [Fact] public void SimpleTuple() { var source = @" class C { static void Main() { var x = (1, 2); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "{1, 2}"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: constrained. ""System.ValueTuple<int, int>"" IL_0011: callvirt ""string object.ToString()"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: ret }"); } [Fact] public void SimpleTupleNew() { var source = @" class C { static void Main() { var x = new (int, int)(1, 2); System.Console.WriteLine(x.ToString()); x = new (int, int)(); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int, int)(1, 2); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(6, 21), // (9,17): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // x = new (int, int)(); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(9, 17) ); } [Fact] public void SimpleTupleNew1() { var source = @" class C { static void Main() { dynamic arg = 2; var x = new (int, int)(1, arg); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int, int)(1, arg); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(7, 21) ); } [Fact] public void SimpleTupleNew2() { var source = @" class C { static void Main() { var x = new (int a, int b)(1, 2); System.Console.WriteLine(x.a.ToString()); var x1 = new (int a, int b)(1, 2) { a = 3, Item2 = 4}; System.Console.WriteLine(x1.a.ToString()); var x2 = new (int a, (int b, int c) d)(1, new (int, int)(2, 3)) { a = 5, d = {b = 6, c = 7}}; System.Console.WriteLine(x2.a.ToString()); System.Console.WriteLine(x2.d.b.ToString()); System.Console.WriteLine(x2.d.c.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int a, int b)(1, 2); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, int b)").WithLocation(6, 21), // (9,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x1 = new (int a, int b)(1, 2) { a = 3, Item2 = 4}; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, int b)").WithLocation(9, 22), // (12,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x2 = new (int a, (int b, int c) d)(1, new (int, int)(2, 3)) { a = 5, d = {b = 6, c = 7}}; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, (int b, int c) d)").WithLocation(12, 22), // (12,55): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x2 = new (int a, (int b, int c) d)(1, new (int, int)(2, 3)) { a = 5, d = {b = 6, c = 7}}; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(12, 55) ); } [WorkItem(10874, "https://github.com/dotnet/roslyn/issues/10874")] [Fact] public void SimpleTupleNew3() { var source = @" class C { static void Main() { var x0 = new (int a, int b)(1, 2, 3); System.Console.WriteLine(x0.ToString()); var x1 = new (int, int)(1, 2, 3); System.Console.WriteLine(x1.ToString()); var x2 = new (int, int)(1, ""2""); System.Console.WriteLine(x2.ToString()); var x3 = new (int, int)(1); System.Console.WriteLine(x3.ToString()); var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; System.Console.WriteLine(x3.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x0 = new (int a, int b)(1, 2, 3); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int a, int b)").WithLocation(6, 22), // (9,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x1 = new (int, int)(1, 2, 3); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(9, 22), // (12,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x2 = new (int, int)(1, "2"); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(12, 22), // (15,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x3 = new (int, int)(1); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(15, 22), // (18,22): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int)").WithLocation(18, 22), // (18,40): error CS0117: '(int, int)' does not contain a definition for 'a' // var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; Diagnostic(ErrorCode.ERR_NoSuchMember, "a").WithArguments("(int, int)", "a").WithLocation(18, 40), // (18,47): error CS0117: '(int, int)' does not contain a definition for 'Item3' // var x4 = new (int, int)(1, 1) {a = 1, Item3 = 2} ; Diagnostic(ErrorCode.ERR_NoSuchMember, "Item3").WithArguments("(int, int)", "Item3").WithLocation(18, 47) ); } [Fact] public void SimpleTuple2() { var source = @" class C { static void Main() { var s = Single((a:1, b:2)); System.Console.WriteLine(s[0].b.ToString()); } static T[] Single<T>(T x) { return new T[]{x}; } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "2"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: call ""System.ValueTuple<int, int>[] C.Single<System.ValueTuple<int, int>>(System.ValueTuple<int, int>)"" IL_000c: ldc.i4.0 IL_000d: ldelema ""System.ValueTuple<int, int>"" IL_0012: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0017: call ""string int.ToString()"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret }"); } [Fact] public void SimpleTupleTargetTyped() { var source = @" class C { static void Main() { (object, object) x = (null, null); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "{, }"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple<object, object> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldnull IL_0004: call ""System.ValueTuple<object, object>..ctor(object, object)"" IL_0009: ldloca.s V_0 IL_000b: constrained. ""System.ValueTuple<object, object>"" IL_0011: callvirt ""string object.ToString()"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: ret }"); } [Fact] public void SimpleTupleNested() { var source = @" class C { static void Main() { var x = (1, (2, (3, 4)).ToString()); System.Console.WriteLine(x.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: "{1, {2, {3, 4}}}"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 5 .locals init (System.ValueTuple<int, string> V_0, //x System.ValueTuple<int, System.ValueTuple<int, int>> V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: ldc.i4.4 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: newobj ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: constrained. ""System.ValueTuple<int, System.ValueTuple<int, int>>"" IL_0019: callvirt ""string object.ToString()"" IL_001e: call ""System.ValueTuple<int, string>..ctor(int, string)"" IL_0023: ldloca.s V_0 IL_0025: constrained. ""System.ValueTuple<int, string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: ret }"); } [Fact] public void TupleUnderlyingItemAccess() { var source = @" class C { static void Main() { var x = (1, 2); System.Console.WriteLine(x.Item2.ToString()); x.Item1 = 40; System.Console.WriteLine(x.Item1 + x.Item2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0010: call ""string int.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0023: ldloc.0 IL_0024: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0029: ldloc.0 IL_002a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002f: add IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret } "); } [Fact] public void TupleUnderlyingItemAccess01() { var source = @" class C { static void Main() { var x = (a: 1, b: 2); System.Console.WriteLine(x.Item2.ToString()); x.Item1 = 40; System.Console.WriteLine(x.Item1 + x.Item2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0010: call ""string int.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0023: ldloc.0 IL_0024: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0029: ldloc.0 IL_002a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002f: add IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret } "); } [Fact] public void TupleItemAccess() { var source = @" class C { static void Main() { var x = (a: 1, b: 2); System.Console.WriteLine(x.b.ToString()); x.a = 40; System.Console.WriteLine(x.a + x.b); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldflda ""int System.ValueTuple<int, int>.Item2"" IL_0010: call ""string int.ToString()"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0023: ldloc.0 IL_0024: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0029: ldloc.0 IL_002a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002f: add IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret } "); } [Fact] public void TupleItemAccess01() { var source = @" class C { static void Main() { var x = (a: 1, b: (c: 2, d: 3)); System.Console.WriteLine(x.b.c.ToString()); x.b.d = 39; System.Console.WriteLine(x.a + x.b.c + x.b.d); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"2 42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 87 (0x57) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_000f: ldloca.s V_0 IL_0011: ldflda ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0016: ldflda ""int System.ValueTuple<int, int>.Item1"" IL_001b: call ""string int.ToString()"" IL_0020: call ""void System.Console.WriteLine(string)"" IL_0025: ldloca.s V_0 IL_0027: ldflda ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_002c: ldc.i4.s 39 IL_002e: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0033: ldloc.0 IL_0034: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0039: ldloc.0 IL_003a: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_003f: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0044: add IL_0045: ldloc.0 IL_0046: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_004b: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0050: add IL_0051: call ""void System.Console.WriteLine(int)"" IL_0056: ret } "); } [Fact] public void TupleTypeDeclaration() { var source = @" class C { static void Main() { (int, string, int) x = (1, ""hello"", 2); System.Console.WriteLine(x.ToString()); } } " + trivial3uple; var comp = CompileAndVerify(source, expectedOutput: @"{1, hello, 2}"); } [Fact] [WorkItem(11281, "https://github.com/dotnet/roslyn/issues/11281")] public void TupleTypeMismatch_01() { var source = @" class C { static void Main() { (int, string) x = (1, ""hello"", 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (6,27): error CS0029: Cannot implicitly convert type '(int, string, int)' to '(int, string)' // (int, string) x = (1, "hello", 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(1, ""hello"", 2)").WithArguments("(int, string, int)", "(int, string)").WithLocation(6, 27)); } [Fact] [WorkItem(11282, "https://github.com/dotnet/roslyn/issues/11282")] public void TupleTypeMismatch_02() { var source = @" class C { static void Main() { (int, string) x = (1, null, 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (6,27): error CS8135: Tuple with 3 elements cannot be converted to type '(int, string)'. // (int, string) x = (1, null, 2); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(1, null, 2)").WithArguments("3", "(int, string)").WithLocation(6, 27) ); } [Fact] [WorkItem(11283, "https://github.com/dotnet/roslyn/issues/11283")] public void LongTupleTypeMismatch() { var source = @" class C { static void Main() { (int, int, int, int, int, int, int, int) x = (""Alice"", 2, 3, 4, 5, 6, 7, 8); (int, int, int, int, int, int, int, int) y = (1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }).VerifyDiagnostics( // (6,55): error CS0029: Cannot implicitly convert type 'string' to 'int' // (int, int, int, int, int, int, int, int) x = ("Alice", 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Alice""").WithArguments("string", "int").WithLocation(6, 55), // (7,54): error CS0029: Cannot implicitly convert type '(int, int, int, int, int, int, int, int, int)' to '(int, int, int, int, int, int, int, int)' // (int, int, int, int, int, int, int, int) y = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("(int, int, int, int, int, int, int, int, int)", "(int, int, int, int, int, int, int, int)").WithLocation(7, 54) ); } [Fact] public void TupleTypeWithLateDiscoveredName() { var source = @" class C { static void Main() { (int, string a) x = (1, ""hello"", c: 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type '(int, string, int c)' to '(int, string a)' // (int, string a) x = (1, "hello", c: 2); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(1, ""hello"", c: 2)").WithArguments("(int, string, int c)", "(int, string a)").WithLocation(6, 29) ); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""hello"", c: 2)", node.ToString()); Assert.Equal("(System.Int32, System.String, System.Int32 c)", model.GetTypeInfo(node).Type.ToTestDisplayString()); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = model.GetDeclaredSymbol(x).GetSymbol<SourceLocalSymbol>().Type; Assert.Equal("(System.Int32, System.String a)", xSymbol.ToTestDisplayString()); Assert.True(xSymbol.IsTupleType); Assert.Equal(new[] { "System.Int32", "System.String" }, xSymbol.TupleElementTypesWithAnnotations.SelectAsArray(t => t.ToTestDisplayString())); Assert.Equal(new[] { null, "a" }, xSymbol.TupleElementNames); } [Fact] public void TupleTypeDeclarationWithNames() { var source = @" class C { static void Main() { (int a, string b) x = (1, ""hello""); System.Console.WriteLine(x.a.ToString()); System.Console.WriteLine(x.b.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 hello"); } [Fact] public void TupleTypeWithOnlySomeNames() { var source = @" class C { static void Main() { (int, string a, int Item3) x = (1, ""hello"", 3); System.Console.WriteLine(x.Item1 + "" "" + x.Item2 + "" "" + x.a + "" "" + x.Item3); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 hello hello 3"); } [Fact] public void TupleTypeWithOnlySomeNamesInMetadata() { var source1 = @" public class C { public static (int, string b, int Item3) M() { return (1, ""hello"", 3); } } "; var source2 = @" class D { public static void Main() { var t = C.M(); System.Console.WriteLine(t.Item1 + "" "" + t.Item2 + "" "" + t.b + "" "" + t.Item3); } } "; var comp1 = CreateCompilationWithMscorlib40(source2 + source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, expectedOutput: "1 hello hello 3"); var compLib = CreateCompilationWithMscorlib40(source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseDll); compLib.VerifyDiagnostics(); var compLibCompilationRef = compLib.ToMetadataReference(); var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, compLibCompilationRef }, options: TestOptions.ReleaseExe); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, expectedOutput: "1 hello hello 3"); var comp3 = CreateCompilationWithMscorlib40(source2, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, compLib.EmitToImageReference() }, options: TestOptions.ReleaseExe); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, expectedOutput: "1 hello hello 3"); } [Fact] public void TupleLiteralWithOnlySomeNames() { var source = @" class C { static void Main() { (int, string, int) x = (1, b: ""hello"", Item3: 3); System.Console.WriteLine(x.Item1 + "" "" + x.Item2 + "" "" + x.Item3); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 hello 3"); } [Fact] public void TupleDictionary01() { var source = @" using System.Collections.Generic; class C { static void Main() { var k = (1, 2); var v = (a: 1, b: (c: 2, d: (e: 3, f: 4))); var d = Test(k, v); System.Console.WriteLine(d[(1, 2)].b.d.Item2); } static Dictionary<K, V> Test<K, V>(K key, V value) { var d = new Dictionary<K, V>(); d[key] = value; return d; } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"4"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @" { // Code size 67 (0x43) .maxstack 6 .locals init (System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>> V_0) //v IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.1 IL_000a: ldc.i4.2 IL_000b: ldc.i4.3 IL_000c: ldc.i4.4 IL_000d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0012: newobj ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0017: call ""System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>..ctor(int, System.ValueTuple<int, System.ValueTuple<int, int>>)"" IL_001c: ldloc.0 IL_001d: call ""System.Collections.Generic.Dictionary<System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>> C.Test<System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>>(System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>)"" IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0029: callvirt ""System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>> System.Collections.Generic.Dictionary<System.ValueTuple<int, int>, System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>>.this[System.ValueTuple<int, int>].get"" IL_002e: ldfld ""System.ValueTuple<int, System.ValueTuple<int, int>> System.ValueTuple<int, System.ValueTuple<int, System.ValueTuple<int, int>>>.Item2"" IL_0033: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0038: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: ret } "); } [Fact] public void TupleLambdaCapture01() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: a, f2: a); Func<T> f = () => x.f2; return f(); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<T, T> C.<>c__DisplayClass1_0<T>.x"" IL_0006: ldfld ""T System.ValueTuple<T, T>.Item2"" IL_000b: ret } "); } [Fact] public void TupleLambdaCapture02() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static string Test<T>(T a) { var x = (f1: a, f2: a); Func<string> f = () => x.ToString(); return f(); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"{42, 42}"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<T, T> C.<>c__DisplayClass1_0<T>.x"" IL_0006: constrained. ""System.ValueTuple<T, T>"" IL_000c: callvirt ""string object.ToString()"" IL_0011: ret } "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33615")] public void TupleLambdaCapture03() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: a, f2: a); Func<T> f = () => x.Test(a); return f(); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var comp = CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib46Extended, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""(T f1, T f2) C.<>c__DisplayClass1_0<T>.x"" IL_0006: ldarg.0 IL_0007: ldfld ""T C.<>c__DisplayClass1_0<T>.a"" IL_000c: call ""T System.ValueTuple<T, T>.Test<T>(T)"" IL_0011: ret } "); } [Fact] public void TupleLambdaCapture04() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: 1, f2: 2); Func<T> f = () => x.Test(a); return f(); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var comp = CompileAndVerify(source, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<int, int> C.<>c__DisplayClass1_0<T>.x"" IL_0006: ldarg.0 IL_0007: ldfld ""T C.<>c__DisplayClass1_0<T>.a"" IL_000c: call ""T System.ValueTuple<int, int>.Test<T>(T)"" IL_0011: ret } "); } [Fact] public void TupleLambdaCapture05() { var source = @" using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static T Test<T>(T a) { var x = (f1: a, f2: a); Func<T> f = () => x.P1; return f(); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public T1 P1 { get { return Item1; } } } } "; var comp = CompileAndVerify(source, expectedOutput: @"42"); comp.VerifyDiagnostics(); comp.VerifyIL("C.<>c__DisplayClass1_0<T>.<Test>b__0()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""System.ValueTuple<T, T> C.<>c__DisplayClass1_0<T>.x"" IL_0006: call ""T System.ValueTuple<T, T>.P1.get"" IL_000b: ret } "); } [Fact] public void TupleLambdaCapture06() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Action<int> d1 = (int i1) => System.Console.WriteLine(i1); v1.Test(v1, d1); Test(v1); } static void Test<T1, T2>((T1, T2) v1) { System.Action f = () => { System.Action<T1> d1 = (T1 i1) => System.Console.WriteLine(i1); System.Action<T2> d2 = (T2 i2) => System.Console.WriteLine(i2); v1.E1 += d1; v1.RaiseE1(); v1.E1 -= d1; v1.RaiseE1(); v1.E2 += d2; v1.RaiseE2(); v1.E2 -= d2; v1.RaiseE2(); }; f(); } static (int, long) M1() { return (1, 11); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this._e2 = null; } public event System.Action<T1> E1; private System.Action<T2> _e2; public event System.Action<T2> E2 { add { _e2 += value; } remove { _e2 -= value; } } public void RaiseE1() { System.Console.WriteLine(""-""); if (E1 == null) { System.Console.WriteLine(""null""); } else { E1(Item1); } System.Console.WriteLine(""-""); } public void RaiseE2() { System.Console.WriteLine(""--""); if (_e2 == null) { System.Console.WriteLine(""null""); } else { _e2(Item2); } System.Console.WriteLine(""--""); } public void Test<S1, S2>((S1, S2) val, System.Action<S1> d) { System.Action f= () => { val.E1 += d; System.Console.WriteLine(val.E1); val.E1(val.Item1); val.E1 -= d; System.Console.WriteLine(val.E1 == null); }; f(); } } } " + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"System.Action`1[System.Int32] 1 True - 1 - - null - -- 11 -- -- null --"); } [Fact] public void TupleAsyncCapture01() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.f1; } } " + trivial2uple + tupleattributes_cs; var verifier = CompileAndVerify(source, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 207 (0xcf) .maxstack 3 .locals init (int V_0, T V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""T C.<Test>d__1<T>.a"" IL_0011: ldarg.0 IL_0012: ldfld ""T C.<Test>d__1<T>.a"" IL_0017: newobj ""System.ValueTuple<T, T>..ctor(T, T)"" IL_001c: stfld ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_0056: leave.s IL_00ce IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005e: stloc.2 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0074: ldloca.s V_2 IL_0076: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_007b: ldarg.0 IL_007c: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0081: ldfld ""T System.ValueTuple<T, T>.Item1"" IL_0086: stloc.1 IL_0087: leave.s IL_00ae } catch System.Exception { IL_0089: stloc.s V_4 IL_008b: ldarg.0 IL_008c: ldc.i4.s -2 IL_008e: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0093: ldarg.0 IL_0094: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0099: initobj ""System.ValueTuple<T, T>"" IL_009f: ldarg.0 IL_00a0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00a5: ldloc.s V_4 IL_00a7: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetException(System.Exception)"" IL_00ac: leave.s IL_00ce } IL_00ae: ldarg.0 IL_00af: ldc.i4.s -2 IL_00b1: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00b6: ldarg.0 IL_00b7: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_00bc: initobj ""System.ValueTuple<T, T>"" IL_00c2: ldarg.0 IL_00c3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00c8: ldloc.1 IL_00c9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetResult(T)"" IL_00ce: ret } "); } [Fact] public void TupleAsyncCapture02() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<string> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.ToString(); } } " + trivial2uple + tupleattributes_cs; var verifier = CompileAndVerify(source, expectedOutput: @"{42, 42}", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 213 (0xd5) .maxstack 3 .locals init (int V_0, string V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""T C.<Test>d__1<T>.a"" IL_0011: ldarg.0 IL_0012: ldfld ""T C.<Test>d__1<T>.a"" IL_0017: newobj ""System.ValueTuple<T, T>..ctor(T, T)"" IL_001c: stfld ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string> C.<Test>d__1<T>.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_0056: leave.s IL_00d4 IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005e: stloc.2 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0074: ldloca.s V_2 IL_0076: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_007b: ldarg.0 IL_007c: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_0081: constrained. ""System.ValueTuple<T, T>"" IL_0087: callvirt ""string object.ToString()"" IL_008c: stloc.1 IL_008d: leave.s IL_00b4 } catch System.Exception { IL_008f: stloc.s V_4 IL_0091: ldarg.0 IL_0092: ldc.i4.s -2 IL_0094: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0099: ldarg.0 IL_009a: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_009f: initobj ""System.ValueTuple<T, T>"" IL_00a5: ldarg.0 IL_00a6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string> C.<Test>d__1<T>.<>t__builder"" IL_00ab: ldloc.s V_4 IL_00ad: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string>.SetException(System.Exception)"" IL_00b2: leave.s IL_00d4 } IL_00b4: ldarg.0 IL_00b5: ldc.i4.s -2 IL_00b7: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00bc: ldarg.0 IL_00bd: ldflda ""System.ValueTuple<T, T> C.<Test>d__1<T>.<x>5__2"" IL_00c2: initobj ""System.ValueTuple<T, T>"" IL_00c8: ldarg.0 IL_00c9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string> C.<Test>d__1<T>.<>t__builder"" IL_00ce: ldloc.1 IL_00cf: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<string>.SetResult(string)"" IL_00d4: ret } "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33615")] public void TupleAsyncCapture03() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.Test(a); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var verifier = CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib46Extended, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 189 (0xbd) .maxstack 3 .locals init (int V_0, T V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld ""T C.<Test>d__1<T>.a"" IL_0011: ldarg.0 IL_0012: ldfld ""T C.<Test>d__1<T>.a"" IL_0017: newobj ""System.ValueTuple<T, T>..ctor(T, T)"" IL_001c: stfld ""(T f1, T f2) C.<Test>d__1<T>.<x>5__2"" IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_0056: leave.s IL_00bc IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005e: stloc.2 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0074: ldloca.s V_2 IL_0076: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_007b: ldarg.0 IL_007c: ldflda ""(T f1, T f2) C.<Test>d__1<T>.<x>5__2"" IL_0081: ldarg.0 IL_0082: ldfld ""T C.<Test>d__1<T>.a"" IL_0087: call ""T System.ValueTuple<T, T>.Test<T>(T)"" IL_008c: stloc.1 IL_008d: leave.s IL_00a8 } catch System.Exception { IL_008f: stloc.s V_4 IL_0091: ldarg.0 IL_0092: ldc.i4.s -2 IL_0094: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0099: ldarg.0 IL_009a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_009f: ldloc.s V_4 IL_00a1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetException(System.Exception)"" IL_00a6: leave.s IL_00bc } IL_00a8: ldarg.0 IL_00a9: ldc.i4.s -2 IL_00ab: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00b0: ldarg.0 IL_00b1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00b6: ldloc.1 IL_00b7: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetResult(T)"" IL_00bc: ret } "); } [Fact] public void TupleAsyncCapture04() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: 1, f2: 2); await Task.Yield(); return x.Test(a); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier.VerifyIL("C.<Test>d__1<T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 179 (0xb3) .maxstack 3 .locals init (int V_0, T V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1<T>.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_004e IL_000a: ldarg.0 IL_000b: ldc.i4.1 IL_000c: ldc.i4.2 IL_000d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0012: stfld ""System.ValueTuple<int, int> C.<Test>d__1<T>.<x>5__2"" IL_0017: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_001c: stloc.3 IL_001d: ldloca.s V_3 IL_001f: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0024: stloc.2 IL_0025: ldloca.s V_2 IL_0027: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_002c: brtrue.s IL_006a IL_002e: ldarg.0 IL_002f: ldc.i4.0 IL_0030: dup IL_0031: stloc.0 IL_0032: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_0037: ldarg.0 IL_0038: ldloc.2 IL_0039: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_003e: ldarg.0 IL_003f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_0044: ldloca.s V_2 IL_0046: ldarg.0 IL_0047: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1<T>>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1<T>)"" IL_004c: leave.s IL_00b2 IL_004e: ldarg.0 IL_004f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_0054: stloc.2 IL_0055: ldarg.0 IL_0056: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1<T>.<>u__1"" IL_005b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0061: ldarg.0 IL_0062: ldc.i4.m1 IL_0063: dup IL_0064: stloc.0 IL_0065: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_006a: ldloca.s V_2 IL_006c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0071: ldarg.0 IL_0072: ldflda ""System.ValueTuple<int, int> C.<Test>d__1<T>.<x>5__2"" IL_0077: ldarg.0 IL_0078: ldfld ""T C.<Test>d__1<T>.a"" IL_007d: call ""T System.ValueTuple<int, int>.Test<T>(T)"" IL_0082: stloc.1 IL_0083: leave.s IL_009e } catch System.Exception { IL_0085: stloc.s V_4 IL_0087: ldarg.0 IL_0088: ldc.i4.s -2 IL_008a: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_008f: ldarg.0 IL_0090: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_0095: ldloc.s V_4 IL_0097: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetException(System.Exception)"" IL_009c: leave.s IL_00b2 } IL_009e: ldarg.0 IL_009f: ldc.i4.s -2 IL_00a1: stfld ""int C.<Test>d__1<T>.<>1__state"" IL_00a6: ldarg.0 IL_00a7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T> C.<Test>d__1<T>.<>t__builder"" IL_00ac: ldloc.1 IL_00ad: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<T>.SetResult(T)"" IL_00b2: ret } "); } [Fact] public void TupleAsyncCapture05() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: a, f2: a); await Task.Yield(); return x.P1; } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public T1 P1 { get { return Item1; } } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"42", options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); } [Fact] public void TupleAsyncCapture06() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { var v1 = M1(); System.Action<int> d1 = (int i1) => System.Console.WriteLine(i1); v1.Test(v1, d1).Wait(); Test(v1).Wait(); } static async Task Test<T1, T2>((T1, T2) v1) { System.Action<T1> d1 = (T1 i1) => System.Console.WriteLine(i1); System.Action<T2> d2 = (T2 i2) => System.Console.WriteLine(i2); await Task.Yield(); v1.E1 += d1; v1.RaiseE1(); v1.E1 -= d1; v1.RaiseE1(); v1.E2 += d2; v1.RaiseE2(); v1.E2 -= d2; v1.RaiseE2(); } static (int, long) M1() { return (1, 11); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this._e2 = null; } public event System.Action<T1> E1; private System.Action<T2> _e2; public event System.Action<T2> E2 { add { _e2 += value; } remove { _e2 -= value; } } public void RaiseE1() { System.Console.WriteLine(""-""); if (E1 == null) { System.Console.WriteLine(""null""); } else { E1(Item1); } System.Console.WriteLine(""-""); } public void RaiseE2() { System.Console.WriteLine(""--""); if (_e2 == null) { System.Console.WriteLine(""null""); } else { _e2(Item2); } System.Console.WriteLine(""--""); } public async Task Test<S1, S2>((S1, S2) val, System.Action<S1> d) { d = d; await Task.Yield(); val.E1 += d; System.Console.WriteLine(val.E1); val.E1(val.Item1); val.E1 -= d; System.Console.WriteLine(val.E1 == null); } } } " + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"System.Action`1[System.Int32] 1 True - 1 - - null - -- 11 -- -- null --"); } [Fact] public void LongTupleWithSubstitution() { var source = @" using System; using System.Threading.Tasks; class C { static void Main() { Console.WriteLine(Test(42).Result); } public static async Task<T> Test<T>(T a) { var x = (f1: 1, f2: 2, f3: 3, f4: 4, f5: 5, f6: 6, f7: 7, f8: a); await Task.Yield(); return x.f8; } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; CompileAndVerify(source, expectedOutput: @"42", targetFramework: TargetFramework.Mscorlib46, options: TestOptions.ReleaseExe); } [Fact] public void TupleUsageWithoutTupleLibrary() { var source = @" class C { static void Main() { (int, string) x = (1, ""hello""); } } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, string) x = (1, "hello"); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, string)").WithArguments("System.ValueTuple`2").WithLocation(6, 9), // (6,27): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, string) x = (1, "hello"); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, @"(1, ""hello"")").WithArguments("System.ValueTuple`2").WithLocation(6, 27) ); } [Fact] public void TupleUsageWithMissingTupleMembers() { var source = @" namespace System { public struct ValueTuple<T1, T2> { } } class C { static void Main() { (int, int) x = (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (11,20): warning CS0219: The variable 'x' is assigned but its value is never used // (int, int) x = (1, 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 20), // (11,24): error CS8128: Member '.ctor' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int, int) x = (1, 2); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "(1, 2)").WithArguments(".ctor", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 24) ); } [Fact] public void TupleWithDuplicateNames() { var source = @" class C { static void Main() { (int a, string a) x = (b: 1, b: ""hello"", b: 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, b: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "a").WithLocation(6, 24), // (6,38): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, b: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "b").WithLocation(6, 38), // (6,50): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, b: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "b").WithLocation(6, 50) ); } [Fact] public void TupleWithDuplicateReservedNames() { var source = @" class C { static void Main() { (int Item1, string Item1) x = (Item1: 1, Item1: ""hello""); (int Item2, string Item2) y = (Item2: 1, Item2: ""hello""); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,28): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // (int Item1, string Item1) x = (Item1: 1, Item1: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(6, 28), // (6,50): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // (int Item1, string Item1) x = (Item1: 1, Item1: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(6, 50), // (7,14): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item2, string Item2) y = (Item2: 1, Item2: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(7, 14), // (7,40): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item2, string Item2) y = (Item2: 1, Item2: "hello"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(7, 40) ); } [Fact] public void TupleWithNonReservedNames() { var source = @" class C { static void Main() { (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,37): error CS8125: Tuple member name 'Item10' is only allowed at position 10. // (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item10").WithArguments("Item10", "10").WithLocation(6, 37), // (6,61): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(6, 61), // (6,71): error CS8125: Tuple member name 'Item10' is only allowed at position 10. // (int Item1, int Item01, int Item10) x = (Item01: 1, Item1: 2, Item10: 3); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item10").WithArguments("Item10", "10").WithLocation(6, 71) ); } [Fact] public void DefaultValueForTuple() { var source = @" class C { static void Main() { (int a, string b) x = (1, ""hello""); x = default((int, string)); System.Console.WriteLine(x.a); System.Console.WriteLine(x.b ?? ""null""); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"0 null"); } [Fact] public void TupleWithDuplicateMemberNames() { var source = @" class C { static void Main() { (int a, string a) x = (b: 1, c: ""hello"", b: 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, c: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "a").WithLocation(6, 24), // (6,50): error CS8127: Tuple member names must be unique. // (int a, string a) x = (b: 1, c: "hello", b: 2); Diagnostic(ErrorCode.ERR_TupleDuplicateElementName, "b").WithLocation(6, 50) ); } [Fact] public void TupleWithReservedMemberNames() { var source = @" class C { static void Main() { (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: ""bad"", Item4: ""bad"", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: ""bad""); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,28): error CS8125: Tuple member name 'Item3' is only allowed at position 3. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item3").WithArguments("Item3", "3").WithLocation(6, 28), // (6,42): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(6, 42), // (6,100): error CS8126: Tuple member name 'Rest' is disallowed at any position. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Rest").WithArguments("Rest").WithLocation(6, 100), // (6,111): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(6, 111), // (6,125): error CS8125: Tuple member name 'Item4' is only allowed at position 4. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item4").WithArguments("Item4", "4").WithLocation(6, 125), // (6,189): error CS8126: Tuple member name 'Rest' is disallowed at any position. // (int Item1, string Item3, string Item2, int Item4, int Item5, int Item6, int Item7, string Rest) x = (Item2: "bad", Item4: "bad", Item3: 3, Item4: 4, Item5: 5, Item6: 6, Item7: 7, Rest: "bad"); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Rest").WithArguments("Rest").WithLocation(6, 189) ); } [Fact] public void TupleWithExistingUnderlyingMemberNames() { var source = @" class C { static void Main() { var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8126: Tuple member name 'CompareTo' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "CompareTo").WithArguments("CompareTo").WithLocation(6, 18), // (6,43): error CS8126: Tuple member name 'Deconstruct' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Deconstruct").WithArguments("Deconstruct").WithLocation(6, 43), // (6,59): error CS8126: Tuple member name 'Equals' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Equals").WithArguments("Equals").WithLocation(6, 59), // (6,70): error CS8126: Tuple member name 'GetHashCode' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "GetHashCode").WithArguments("GetHashCode").WithLocation(6, 70), // (6,86): error CS8126: Tuple member name 'Rest' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "Rest").WithArguments("Rest").WithLocation(6, 86), // (6,95): error CS8126: Tuple member name 'ToString' is disallowed at any position. // var x = (CompareTo: 2, Create: 3, Deconstruct: 4, Equals: 5, GetHashCode: 6, Rest: 8, ToString: 10); Diagnostic(ErrorCode.ERR_TupleReservedElementNameAnyPosition, "ToString").WithArguments("ToString").WithLocation(6, 95) ); } [Fact] public void TupleWithExistingInaccessibleUnderlyingMemberNames() { var source = @" class C { static void Main() { var x = (CombineHashCodes: 1, Create: 2, GetHashCodeCore: 3, Size: 4, ToStringEnd: 5); System.Console.WriteLine(x.CombineHashCodes + "" "" + x.Create + "" "" + x.GetHashCodeCore + "" "" + x.Size + "" "" + x.ToStringEnd); } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(DesktopOnly))] public void LongTupleDeclaration() { var source = @" class C { static void Main() { (int, int, int, int, int, int, int, string, int, int, int, int) x = (1, 2, 3, 4, 5, 6, 7, ""Alice"", 2, 3, 4, 5); System.Console.WriteLine($""{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} {x.Item9} {x.Item10} {x.Item11} {x.Item12}""); } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " + "System.String, System.Int32, System.Int32, System.Int32, System.Int32) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void LongTupleDeclarationWithNames() { var source = @" class C { static void Main() { (int a, int b, int c, int d, int e, int f, int g, string h, int i, int j, int k, int l) x = (1, 2, 3, 4, 5, 6, 7, ""Alice"", 2, 3, 4, 5); System.Console.WriteLine($""{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, " + "System.String h, System.Int32 i, System.Int32 j, System.Int32 k, System.Int32 l) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); }; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] // The used assemblies test hook is blocked by https://github.com/dotnet/roslyn/issues/39976 [WorkItem(39976, "https://github.com/dotnet/roslyn/issues/39976")] public void HugeTupleCreationParses() { StringBuilder b = new StringBuilder(); b.Append("("); for (int i = 0; i < 3000; i++) { b.Append("1, "); } b.Append("1)"); var source = @" class C { static void Main() { var x = " + b.ToString() + @"; } } "; CreateCompilation(source); } [ConditionalFact(typeof(NoIOperationValidation))] public void HugeTupleDeclarationParses() { StringBuilder b = new StringBuilder(); b.Append("("); for (int i = 0; i < 3000; i++) { b.Append("int, "); } b.Append("int)"); var source = @" class C { static void Main() { " + b.ToString() + @" x; } } "; CreateCompilation(source); } [Fact] public void GenericTupleWithoutTupleLibrary_01() { var source = @" class C { static void Main() { var x = M<int, bool>(); System.Console.WriteLine($""{x.first} {x.second}""); } static (T1 first, T2 second) M<T1, T2>() { return (default(T1), default(T2)); } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (10,12): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // static (T1 first, T2 second) M<T1, T2>() Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(T1 first, T2 second)").WithArguments("System.ValueTuple`2").WithLocation(10, 12), // (12,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (default(T1), default(T2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(default(T1), default(T2))").WithArguments("System.ValueTuple`2").WithLocation(12, 16) ); var c = comp.GetTypeByMetadataName("C"); var mTuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M").ReturnType; Assert.True(mTuple.IsTupleType); Assert.Equal(TypeKind.Error, mTuple.TupleUnderlyingType.TypeKind); Assert.Equal(SymbolKind.ErrorType, mTuple.TupleUnderlyingType.Kind); Assert.IsAssignableFrom<ErrorTypeSymbol>(mTuple.TupleUnderlyingType); Assert.Equal(TypeKind.Error, mTuple.TypeKind); AssertTupleTypeEquality(mTuple); Assert.False(mTuple.IsImplicitlyDeclared); Assert.Equal("Predefined type 'System.ValueTuple`2' is not defined or imported", mTuple.GetUseSiteDiagnostic().GetMessage(CultureInfo.InvariantCulture)); Assert.Null(mTuple.BaseType()); Assert.False(mTuple.TupleData.UnderlyingDefinitionToMemberMap.Any()); var mFirst = (FieldSymbol)mTuple.GetMembers("first").Single(); Assert.IsType<TupleErrorFieldSymbol>(mFirst); Assert.Equal("first", mFirst.Name); Assert.Same(mFirst, mFirst.OriginalDefinition); Assert.True(mFirst.Equals(mFirst)); Assert.Null(mFirst.TupleUnderlyingField); Assert.Null(mFirst.AssociatedSymbol); Assert.Same(mTuple, mFirst.ContainingSymbol); Assert.True(mFirst.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(mFirst.GetAttributes().IsEmpty); Assert.Null(mFirst.GetUseSiteDiagnostic()); Assert.False(mFirst.Locations.IsEmpty); Assert.Equal("T1 first", mFirst.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.False(mFirst.IsImplicitlyDeclared); Assert.Null(mFirst.TypeLayoutOffset); var mItem1 = (FieldSymbol)mTuple.GetMembers("Item1").Single(); Assert.IsType<TupleErrorFieldSymbol>(mItem1); Assert.Equal("Item1", mItem1.Name); Assert.Same(mItem1, mItem1.OriginalDefinition); Assert.True(mItem1.Equals(mItem1)); Assert.Null(mItem1.TupleUnderlyingField); Assert.Null(mItem1.AssociatedSymbol); Assert.Same(mTuple, mItem1.ContainingSymbol); Assert.True(mItem1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(mItem1.GetAttributes().IsEmpty); Assert.Null(mItem1.GetUseSiteDiagnostic()); Assert.True(mItem1.Locations.IsEmpty); Assert.True(mItem1.IsImplicitlyDeclared); Assert.Null(mItem1.TypeLayoutOffset); } [Fact] [WorkItem(11287, "https://github.com/dotnet/roslyn/issues/11287")] public void GenericTupleWithoutTupleLibrary_02() { var source = @" class C { static void Main() { } static (T1, T2, T3, T4, T5, T6, T7, T8, T9) M<T1, T2, T3, T4, T5, T6, T7, T8, T9>() { throw new System.NotSupportedException(); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (8,12): error CS8179: Predefined type 'System.ValueTuple`8' is not defined or imported // static (T1, T2, T3, T4, T5, T6, T7, T8, T9) M<T1, T2, T3, T4, T5, T6, T7, T8, T9>() Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(T1, T2, T3, T4, T5, T6, T7, T8, T9)").WithArguments("System.ValueTuple`8").WithLocation(8, 12) ); } [Fact] public void GenericTuple() { var source = @" class C { static void Main() { var x = M<int, bool>(); System.Console.WriteLine($""{x.first} {x.second}""); } static (T1 first, T2 second) M<T1, T2>() { return (default(T1), default(T2)); } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 False"); } [Fact] public void LongTupleCreation() { var source = @" class C { static void Main() { var x = (1, 2, 3, 4, 5, 6, 7, ""Alice"", 2, 3, 4, 5, 6, 7, ""Bob"", 2, 3); System.Console.WriteLine($""{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} {x.Item9} {x.Item10} {x.Item11} {x.Item12} {x.Item13} {x.Item14} {x.Item15} {x.Item16} {x.Item17}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " + "System.String, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " + "System.String, System.Int32, System.Int32)", model.GetTypeInfo(node).Type.ToTestDisplayString()); }; var verifier = CompileAndVerifyWithMscorlib40(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3", references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void TupleInLambda() { var source = @" class C { static void Main() { System.Action<(int, string)> f = ((int, string) x) => System.Console.WriteLine($""{x.Item1} {x.Item2}""); f((42, ""Alice"")); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void TupleWithNamesInLambda() { var source = @" class C { static void Main() { int a, b = 0; System.Action<(int, string)> f = ((int a, string b) x) => System.Console.WriteLine($""{x.a} {x.b}""); f((c: 42, d: ""Alice"")); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void TupleInProperty() { var source = @" class C { static (int a, string b) P { get; set; } static void Main() { P = (42, ""Alice""); System.Console.WriteLine($""{P.a} {P.b}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void ExtensionMethodOnTuple() { var source = @" static class C { static void Extension(this (int a, string b) x) { System.Console.WriteLine($""{x.a} {x.b}""); } static void Main() { (42, ""Alice"").Extension(); } } "; CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib45, references: new[] { Net451.System, Net451.SystemCore, Net451.SystemRuntime, ValueTupleRef }, expectedOutput: @"42 Alice"); } [Fact] public void TupleInOptionalParam() { var source = @" class C { void M(int x, (int a, string b) y = (42, ""Alice"")) { } } "; CreateCompilation(source).VerifyDiagnostics( // (4,41): error CS1736: Default parameter value for 'y' must be a compile-time constant // void M(int x, (int a, string b) y = (42, "Alice")) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"(42, ""Alice"")").WithArguments("y").WithLocation(4, 41)); } [Fact] public void TupleDefaultInOptionalParam() { var source = @" class C { public static void Main() { M(); } static void M((int a, string b) x = default((int, string))) { System.Console.WriteLine($""{x.a} {x.b}""); } } "; CompileAndVerify(source, expectedOutput: @"0 "); } [Fact] public void TupleAsNamedParam() { var source = @" class C { static void Main() { M(y : (42, ""Alice""), x : 1); } static void M(int x, (int a, string b) y) { System.Console.WriteLine($""{y.a} {y.Item2}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"42 Alice"); } [Fact] public void LongTupleCreationWithNames() { var source = @" class C { static void Main() { var x = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: ""Alice"", i: 2, j: 3, k: 4, l: 5, m: 6, n: 7, o: ""Bob"", p: 2, q: 3); System.Console.WriteLine($""{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l} {x.m} {x.n} {x.o} {x.p} {x.q}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); var type = (INamedTypeSymbol)model.GetTypeInfo(node).Type; Assert.Equal("(System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, " + "System.String h, System.Int32 i, System.Int32 j, System.Int32 k, System.Int32 l, System.Int32 m, System.Int32 n, " + "System.String o, System.Int32 p, System.Int32 q)", type.ToTestDisplayString()); foreach (var item in type.TupleElements) { Assert.True(item.IsExplicitlyNamedTupleElement); Assert.False(item.CorrespondingTupleField.IsExplicitlyNamedTupleElement); } }; var verifier = CompileAndVerify(source, expectedOutput: @"1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void TupleCreationWithInferredNamesWithCSharp7() { var source = @" class C { int e = 5; int f = 6; C instance = null; void M() { int a = 1; int b = 3; int Item4 = 4; int g = 7; int Rest = 9; (int x, int, int b, int, int, int, int f, int, int, int) y = (a, (a), b: 2, b, Item4, instance.e, this.f, g, g, Rest); var z = (x: b, b); System.Console.Write(y); System.Console.Write(z); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var yTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); var yType = (INamedTypeSymbol)model.GetTypeInfo(yTuple).Type; Assert.Equal("(System.Int32 a, System.Int32, System.Int32 b, System.Int32, System.Int32, System.Int32 e, System.Int32 f, System.Int32, System.Int32, System.Int32)", yType.ToTestDisplayString()); Assert.Equal("a", yType.TupleElements[0].Name); Assert.True(yType.TupleElements[0].IsExplicitlyNamedTupleElement); Assert.False(yType.TupleElements[0].CorrespondingTupleField.IsExplicitlyNamedTupleElement); Assert.Equal("Item2", yType.TupleElements[1].Name); Assert.False(yType.TupleElements[1].IsExplicitlyNamedTupleElement); Assert.Same(yType.TupleElements[1], yType.TupleElements[1].CorrespondingTupleField); Assert.Equal("b", yType.TupleElements[2].Name); Assert.True(yType.TupleElements[2].IsExplicitlyNamedTupleElement); Assert.False(yType.TupleElements[2].CorrespondingTupleField.IsExplicitlyNamedTupleElement); var zTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(System.Int32 x, System.Int32 b)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void MissingMemberAccessWithCSharp7() { var source = @" class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); System.Console.Write(GetTuple().a); } (int, int) GetTuple() { return (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (8,32): error CS8305: Tuple element name 'a' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "a").WithArguments("a", "7.1").WithLocation(8, 32), // (9,41): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(GetTuple().a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(9, 41) ); } [Fact] public void UseSiteDiagnosticOnTupleField() { var missing_cs = @"public class Missing { }"; var lib_cs = @" public class C { public static (Missing, int) GetTuple() { throw null; } } "; var source_cs = @" class D { void M() { System.Console.Write(C.GetTuple().Item1); } }"; var missingComp = CreateCompilation(missing_cs, assemblyName: "UseSiteDiagnosticOnTupleField_missingComp"); missingComp.VerifyDiagnostics(); var libComp = CreateCompilationWithMscorlib40(lib_cs, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, missingComp.ToMetadataReference() }); libComp.VerifyDiagnostics(); var comp7 = CreateCompilationWithMscorlib40(source_cs, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular); comp7.VerifyDiagnostics( // (6,30): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C.GetTuple").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,43): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Item1").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); var comp7_1 = CreateCompilationWithMscorlib40(source_cs, assemblyName: "UseSiteDiagnosticOnTupleField_comp7_1", references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference() }, parseOptions: TestOptions.Regular7_1); comp7_1.VerifyDiagnostics( // (6,30): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C.GetTuple").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,43): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(C.GetTuple().Item1); Diagnostic(ErrorCode.ERR_NoTypeDef, "Item1").WithArguments("Missing", "UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); } [Fact] public void UseSiteDiagnosticOnTupleField2() { var source_cs = @" public class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); } } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } "; var comp7 = CreateCompilation(source_cs, parseOptions: TestOptions.Regular, assemblyName: "UseSiteDiagnosticOnTupleField2_comp7"); comp7.VerifyDiagnostics( // (8,32): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'UseSiteDiagnosticOnTupleField2_comp7, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "UseSiteDiagnosticOnTupleField2_comp7, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 32) ); var comp7_1 = CreateCompilation(source_cs, parseOptions: TestOptions.Regular7_1, assemblyName: "UseSiteDiagnosticOnTupleField2_comp7_1"); comp7_1.VerifyDiagnostics( // (8,32): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'UseSiteDiagnosticOnTupleField2_comp7_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "UseSiteDiagnosticOnTupleField2_comp7_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 32) ); } [Fact] public void MissingMemberAccessWithExtensionWithCSharp7() { var source = @" class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); System.Console.Write(t.a()); System.Console.Write(GetTuple().a); } (int, int) GetTuple() { return (1, 2); } } public static class Extensions { public static string a(this (int, int) self) { return ""hello""; } } "; var comp = CreateCompilationWithMscorlib45(source, references: new[] { Net451.System, Net451.SystemCore, Net451.SystemRuntime, ValueTupleRef }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (8,32): error CS8305: Tuple element name 'a' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // System.Console.Write(t.a); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "a").WithArguments("a", "7.1").WithLocation(8, 32), // (10,30): error CS1503: Argument 1: cannot convert from 'method group' to 'string' // System.Console.Write(GetTuple().a); Diagnostic(ErrorCode.ERR_BadArgType, "GetTuple().a").WithArguments("1", "method group", "string") ); } [Fact] public void MissingMemberAccessWithCSharp7_1() { var source = @" class C { void M() { int a = 1; var t = (a, 2); System.Console.Write(t.a); System.Console.Write(t.b); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_1); comp.VerifyDiagnostics( // (9,32): error CS1061: '(int a, int)' does not contain a definition for 'b' and no extension method 'b' accepting a first argument of type '(int a, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(t.b); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b").WithArguments("(int a, int)", "b").WithLocation(9, 32) ); } [Fact] public void TupleCreationWithInferredNames() { var source = @" class C { int e = 5; int f = 6; C instance = null; string M() { int a = 1; int b = 3; int Item4 = 4; int g = 7; int Rest = 9; (int x, int, int b, int, int, int, int f, int, int, int) y = (a, (a), b: 2, b, Item4, instance.e, this.f, g, g, Rest); var z = (x: b, b); System.Console.Write(y); System.Console.Write(z); return null; } int P { set { var t = (M(), value); System.Console.Write(t.value); } } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var yTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(System.Int32 a, System.Int32, System.Int32 b, System.Int32, System.Int32, System.Int32 e, System.Int32 f, System.Int32, System.Int32, System.Int32)", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()); var zTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(System.Int32 x, System.Int32 b)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()); var tTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("(System.String, System.Int32 value)", model.GetTypeInfo(tTuple).Type.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void TupleCreationWithInferredNames2() { var source = @" class C { private int e = 5; } class C2 { C instance = null; C2 instance2 = null; int M() { var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); System.Console.Write(y); return 42; } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1)); compilation.VerifyDiagnostics( // (12,27): error CS0122: 'C.e' is inaccessible due to its protection level // var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); Diagnostic(ErrorCode.ERR_BadAccess, ".e").WithArguments("C.e").WithLocation(12, 27), // (12,41): error CS0122: 'C.e' is inaccessible due to its protection level // var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); Diagnostic(ErrorCode.ERR_BadAccess, "e").WithArguments("C.e").WithLocation(12, 41), // (12,76): error CS0122: 'C.e' is inaccessible due to its protection level // var y = (instance?.e, (instance.e, instance2.M(), checked(instance.e), default(int))); Diagnostic(ErrorCode.ERR_BadAccess, "e").WithArguments("C.e").WithLocation(12, 76), // (4,17): warning CS0414: The field 'C.e' is assigned but its value is never used // private int e = 5; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("C.e") ); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); // The type for int? was not picked up // Follow-up issue: https://github.com/dotnet/roslyn/issues/19144 var yTuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(? e, (System.Int32 e, System.Int32, System.Int32, System.Int32))", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()); } [Fact] public void InferredNamesInLinq() { var source = @" using System.Collections.Generic; using System.Linq; class C { int f1 = 0; int f2 = 1; static void M(IEnumerable<C> list) { var result = list.Select(c => (c.f1, c.f2)).Where(t => t.f2 == 1); // t and result have names f1 and f2 System.Console.Write(result.Count()); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var result = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "result").Single(); var resultSymbol = model.GetDeclaredSymbol(result); Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 f1, System.Int32 f2)> result", resultSymbol.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void InferredNamesInTernary() { var source = @" class C { static void Main() { var i = 1; var flag = false; var t = flag ? (i, 2) : (i, 3); System.Console.Write(t.i); } } "; var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), targetFramework: TargetFramework.Mscorlib46Extended, expectedOutput: "1"); verifier.VerifyDiagnostics(); } [Fact] public void InferredNames_ExtensionNowFailsInCSharp7ButNotCSharp7_1() { var source = @" using System; class C { static void Main() { Action M = () => Console.Write(""lambda""); (1, M).M(); } } static class Extension { public static void M(this (int, Action) t) => Console.Write(""extension""); } "; // When C# 7.0 shipped, no tuple element would be found/inferred, so the extension method was called. // The C# 7.1 compiler disallows that, even when LanguageVersion is 7.0 var comp7 = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); comp7.VerifyDiagnostics( // (8,16): error CS8305: Tuple element name 'M' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. // (1, M).M(); Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "M").WithArguments("M", "7.1") ); var verifier7_1 = CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), expectedOutput: "lambda"); verifier7_1.VerifyDiagnostics(); } [WorkItem(21518, "https://github.com/dotnet/roslyn/issues/21518")] [Fact] public void InferredName_Conversion() { var source = @"class C { static void F((object, object) t) { } static void G(object o) { var t = (1, o); F(t); } }"; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef }); comp.VerifyEmitDiagnostics(); } [Fact] public void LongTupleWithArgumentEvaluation() { var source = @" class C { static void Main() { var x = (a: PrintAndReturn(1), b: 2, c: 3, d: PrintAndReturn(4), e: 5, f: 6, g: PrintAndReturn(7), h: PrintAndReturn(""Alice""), i: 2, j: 3, k: 4, l: 5, m: 6, n: PrintAndReturn(7), o: PrintAndReturn(""Bob""), p: 2, q: PrintAndReturn(3)); x.ToString(); } static T PrintAndReturn<T>(T i) { System.Console.Write(i + "" ""); return i; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 4 7 Alice 7 Bob 3"); verifier.VerifyDiagnostics(); } [Fact] public void LongTupleGettingRest() { var source = @" class C { static void Main() { var x = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: ""Alice"", i: 1); System.Console.WriteLine($""{x.Rest.Item1} {x.Rest.Item2}""); } } "; Action<ModuleSymbol> validator = module => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<MemberAccessExpressionSyntax>().Where(n => n.ToString() == "x.Rest").First(); Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(node).Type.ToTestDisplayString()); }; var verifier = CompileAndVerify(source, expectedOutput: @"Alice 1", sourceSymbolValidator: validator); verifier.VerifyDiagnostics(); } [Fact] public void MethodReturnsValueTuple() { var source = @" class C { static void Main() { System.Console.WriteLine(M().ToString()); } static (int, string) M() { return (1, ""hello""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"(1, hello)"); } [Fact] public void DistinctTupleTypesInCompilation() { var source1 = @" public class C1 { public static (int a, int b) M() { return (1, 2); } } "; var source2 = @" public class C2 { public static (int c, int d) M() { return (3, 4); } } "; var source = @" class C3 { public static void Main() { System.Console.Write(C1.M().Item1 + "" ""); System.Console.Write(C1.M().a + "" ""); System.Console.Write(C1.M().Item2 + "" ""); System.Console.Write(C1.M().b + "" ""); System.Console.Write(C2.M().Item1 + "" ""); System.Console.Write(C2.M().c + "" ""); System.Console.Write(C2.M().Item2 + "" ""); System.Console.Write(C2.M().d); } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); var comp = CompileAndVerify(source, expectedOutput: @"1 1 2 2 3 3 4 4", references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2), }); } [Fact] public void DistinctTupleTypesInCompilationCanAssign() { var source1 = @" public class C1 { public static (int a, int b) M() { System.Console.WriteLine(""C1.M""); return (1, 2); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public static (int c, int d) M() { System.Console.WriteLine(""C2.M""); return (3, 4); } } " + trivial2uple + tupleattributes_cs; var source = @" class C3 { public static void Main() { var x = C1.M(); x = C2.M(); } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); var comp = CreateCompilation(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, expectedOutput: @" C1.M C2.M "); v.VerifyIL("C3.Main()", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: call ""System.ValueTuple<int, int> C1.M()"" IL_0005: pop IL_0006: call ""System.ValueTuple<int, int> C2.M()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0012: ldloc.0 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_001d: pop IL_001e: ret } "); } [Fact] public void AmbiguousTupleTypesForCreationWithVar() { var source = @" class C3 { public static void Main() { var x = (1, 1); } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); } [Fact] public void AmbiguousTupleTypesForCreation() { var source = @" class C3 { public static void Main() { (int, int) x = (1, 1); } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); comp.VerifyDiagnostics( // (6,9): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9), // (6,24): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 24) ); } [Fact] public void AmbiguousTupleTypesForDeclaration() { var source = @" class C3 { public void M((int, int) x) { } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); comp.VerifyDiagnostics( // (4,19): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // public void M((int, int) x) { } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(int, int)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(4, 19) ); } [Fact] public void LocalTupleTypeWinsWhenTupleTypesInCompilation() { var source1 = @" public class C1 { public static (int a, int b) M() { return (1, 2); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public static (int c, int d) M() { return (3, 4); } } " + trivial2uple + tupleattributes_cs; var source = @" class C3 { public static void Main() { System.Console.Write(C1.M().Item1 + "" ""); System.Console.Write(C1.M().a + "" ""); System.Console.Write(C1.M().Item2 + "" ""); System.Console.Write(C1.M().b + "" ""); System.Console.Write(C2.M().Item1 + "" ""); System.Console.Write(C2.M().c + "" ""); System.Console.Write(C2.M().Item2 + "" ""); System.Console.Write(C2.M().d + "" ""); var x = (e: 5, f: 6); System.Console.Write(x.Item1 + "" ""); System.Console.Write(x.e + "" ""); System.Console.Write(x.Item2 + "" ""); System.Console.Write(x.f + "" ""); System.Console.Write(x.GetType().Assembly == typeof(C3).Assembly); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40(source1); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40(source2); comp2.VerifyDiagnostics(); var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: @"1 1 2 2 3 3 4 4 5 5 6 6 True", references: new[] { new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }); } [Fact] public void UnderlyingTypeMemberWithWrongSignature_1() { string source = @" class C { static void M() { var x = (""Alice"", ""Bob""); System.Console.WriteLine($""{x.Item1}""); } } namespace System { public struct ValueTuple<T1, T2> { public string Item1; // Not T1 public int Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = ""1""; this.Item2 = 2; } (T1, T2) M1() => throw null; (T1 a, T2 b) M2() => throw null; } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (20,18): error CS0229: Ambiguity between '(T1, T2).Item1' and '(T1, T2).Item1' // this.Item1 = "1"; Diagnostic(ErrorCode.ERR_AmbigMember, "Item1").WithArguments("(T1, T2).Item1", "(T1, T2).Item1").WithLocation(20, 18), // (21,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = 2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(21, 18), // (18,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(18, 16), // (18,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(18, 16), // (18,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(18, 16), // (18,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(18, 16), // (7,39): error CS0229: Ambiguity between '(string, string).Item1' and '(string, string).Item1' // System.Console.WriteLine($"{x.Item1}"); Diagnostic(ErrorCode.ERR_AmbigMember, "Item1").WithArguments("(string, string).Item1", "(string, string).Item1").WithLocation(7, 39), // (6,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = ("Alice", "Bob"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13) ); var vt2 = comp.GetTypeByMetadataName("System.ValueTuple`2"); Assert.True(vt2.IsTupleType); Assert.True(vt2.IsDefinition); AssertEx.Equal(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, vt2.TupleElements.ToTestDisplayStrings()); vt2.TupleElements.All(e => verifyTupleErrorField(e)); AssertEx.Equal(new[] { "System.String (T1, T2).Item1", "System.Int32 (T1, T2).Item2", "(T1, T2)..ctor(T1 item1, T2 item2)", "(T1, T2) (T1, T2).M1()", "(T1 a, T2 b) (T1, T2).M2()", "(T1, T2)..ctor()", "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, vt2.GetMembers().ToTestDisplayStrings()); var stringItem1 = vt2.GetMembers("Item1")[0]; Assert.Equal("System.String (T1, T2).Item1", stringItem1.ToTestDisplayString()); Assert.Equal(-1, ((FieldSymbol)stringItem1).TupleElementIndex); var intItem2 = vt2.GetMembers("Item2")[0]; Assert.Equal("System.Int32 (T1, T2).Item2", intItem2.ToTestDisplayString()); Assert.Equal(-1, ((FieldSymbol)intItem2).TupleElementIndex); var unnamedTuple = (NamedTypeSymbol)((MethodSymbol)vt2.GetMember("M1")).ReturnType; Assert.Equal("(T1, T2)", unnamedTuple.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, unnamedTuple.Kind); Assert.True(unnamedTuple.IsDefinition); Assert.True(unnamedTuple.IsTupleType); Assert.Same(vt2, unnamedTuple); Assert.IsType<SourceNamedTypeSymbol>(unnamedTuple); Assert.Same(vt2, unnamedTuple.ConstructedFrom); Assert.Same(unnamedTuple, unnamedTuple.OriginalDefinition); Assert.Same(unnamedTuple, unnamedTuple.TupleUnderlyingType); var namedTuple = (NamedTypeSymbol)((MethodSymbol)vt2.GetMember("M2")).ReturnType; Assert.Equal("(T1 a, T2 b)", namedTuple.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, namedTuple.Kind); Assert.False(namedTuple.IsDefinition); Assert.True(namedTuple.IsTupleType); Assert.IsType<ConstructedNamedTypeSymbol>(namedTuple); Assert.NotSame(vt2, namedTuple); Assert.Same(vt2, namedTuple.ConstructedFrom); Assert.Same(vt2, namedTuple.OriginalDefinition); Assert.False(namedTuple.Equals(namedTuple.TupleUnderlyingType, TypeCompareKind.ConsiderEverything)); Assert.True(namedTuple.Equals(namedTuple.TupleUnderlyingType, TypeCompareKind.IgnoreTupleNames)); bool verifyTupleErrorField(FieldSymbol field) { var errorField = field as TupleErrorFieldSymbol; Assert.NotNull(errorField); Assert.True(errorField.IsDefinition); Assert.True(errorField.TupleElementIndex != -1); return true; } } [Fact] public void UnderlyingTypeMemberWithWrongSignature_2() { string source = @" class C { (string, string) M() { var x = (""Alice"", ""Bob""); System.Console.WriteLine($""{x.Item1}""); return x; } void M2((int a, int b) y) { System.Console.WriteLine($""{y.Item1}""); System.Console.WriteLine($""{y.a}""); System.Console.WriteLine($""{y.Item2}""); System.Console.WriteLine($""{y.b}""); } } namespace System { public struct ValueTuple<T1, T2> { public int Item2; public ValueTuple(T1 item1, T2 item2) { this.Item2 = 2; } } } "; var comp = CreateCompilationWithMscorlib40(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (11,13): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? // void M2((int a, int b) y) Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(int a, int b)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(11, 13), // (28,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = 2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(28, 18), // (26,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(26, 16), // (26,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(26, 16), // (26,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(26, 16), // (7,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.Item1}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 39), // (13,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{y.Item1}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(13, 39), // (14,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{y.a}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(14, 39), // (15,39): error CS0229: Ambiguity between '(int a, int b).Item2' and '(int a, int b).Item2' // System.Console.WriteLine($"{y.Item2}"); Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(int a, int b).Item2", "(int a, int b).Item2").WithLocation(15, 39), // (16,39): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{y.b}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "b").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(16, 39) ); var mTuple = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M").ReturnType; AssertTupleTypeEquality(mTuple); var mItem1 = (FieldSymbol)mTuple.GetMembers("Item1").Single(); Assert.IsType<TupleErrorFieldSymbol>(mItem1); Assert.Same(mItem1, mItem1.OriginalDefinition); Assert.True(mItem1.Equals(mItem1)); Assert.Equal("Item1", mItem1.Name); Assert.Null(mItem1.TupleUnderlyingField); Assert.Null(mItem1.AssociatedSymbol); Assert.Same(mTuple, mItem1.ContainingSymbol); Assert.True(mItem1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(mItem1.GetAttributes().IsEmpty); Assert.Equal("error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.", mItem1.GetUseSiteDiagnostic().ToString(EnsureEnglishUICulture.PreferredOrNull)); Assert.True(mItem1.Locations.IsEmpty); Assert.True(mItem1.DeclaringSyntaxReferences.IsEmpty); Assert.True(mItem1.IsImplicitlyDeclared); Assert.Null(mItem1.TypeLayoutOffset); // Note: fields come first AssertTestDisplayString(mTuple.GetMembers(), "System.String (System.String, System.String).Item1", "System.String (System.String, System.String).Item2", "System.Int32 (System.String, System.String).Item2", "(System.String, System.String)..ctor(System.String item1, System.String item2)", "(System.String, System.String)..ctor()"); var m2Tuple = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M2").Parameters[0].Type; AssertTupleTypeEquality(m2Tuple); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a, System.Int32 b).Item1", "System.Int32 (System.Int32 a, System.Int32 b).a", "System.Int32 (System.Int32 a, System.Int32 b).Item2", "System.Int32 (System.Int32 a, System.Int32 b).b", "System.Int32 (System.Int32 a, System.Int32 b).Item2", "(System.Int32 a, System.Int32 b)..ctor(System.Int32 item1, System.Int32 item2)", "(System.Int32 a, System.Int32 b)..ctor()" ); } [Fact] public void UnderlyingTypeMemberWithWrongSignature_3() { string source = @" class C { static void M() { var x = (a: ""Alice"", b: ""Bob""); System.Console.WriteLine($""{x.a}""); } } namespace System { public struct ValueTuple<T1, T2> { public int Item2; public ValueTuple(T1 item1, T2 item2) { this.Item2 = 2; } } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (7,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.a}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 39), // (17,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(17, 16), // (17,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(17, 16), // (17,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(17, 16), // (19,18): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2' // this.Item2 = 2; Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(19, 18) ); } [Fact] public void UnderlyingTypeMemberWithWrongSignature_4() { string source = @" class C { static void M() { var x = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9); System.Console.WriteLine($""{x.a}""); System.Console.WriteLine($""{x.g}""); System.Console.WriteLine($""{x.h}""); System.Console.WriteLine($""{x.i}""); } } namespace System { public struct ValueTuple<T1, T2> { } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public TRest Rest; } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyDiagnostics( // (7,39): error CS8128: Member 'Item1' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.a}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "a").WithArguments("Item1", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 39), // (8,39): error CS8128: Member 'Item7' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.g}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "g").WithArguments("Item7", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 39), // (9,39): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.h}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "h").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 39), // (10,39): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine($"{x.i}"); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "i").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(10, 39) ); } [Fact] public void ImplementTupleInterface() { string source = @" public interface I { (int, int) M((string, string) a); } class C : I { static void Main() { I i = new C(); var r = i.M((""Alice"", ""Bob"")); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } public (int, int) M((string, string) a) { return (a.Item1.Length, a.Item2.Length); } } "; var comp = CompileAndVerify(source, expectedOutput: @"5 3"); comp.VerifyDiagnostics(); } [Fact] public void ImplementLongTupleInterface() { string source = @" public interface I { (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) a); } class C : I { static void Main() { I i = new C(); var r = i.M((1, 2, 3, 4, 5, 6, 7, 8)); System.Console.WriteLine($""{r.Item1} {r.Item7} {r.Item8}""); } public (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) a) { return a; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 7 8"); comp.VerifyDiagnostics(); } [Fact] public void ImplementTupleInterfaceWithValueTuple() { string source = @" public interface I { (int, int) M((string, string) a); } class C : I { static void Main() { I i = new C(); var r = i.M((""Alice"", ""Bob"")); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) { return (a.Item1.Length, a.Item2.Length); } } "; var comp = CompileAndVerify(source, expectedOutput: @"5 3"); comp.VerifyDiagnostics(); } [Fact] public void ImplementTupleInterfaceWithValueTuple2() { string source = @" public interface I { (int i1, int i2) M((string, string) a); } class C : I { public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) { return (1, 2); } void M(I i, C c) { var result1 = i.M((null, null)); System.Console.Write(result1.i1); var result2 = c.M((null, null)); System.Console.Write(result2.i1); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,38): error CS1061: '(int, int)' does not contain a definition for 'i1' and no extension method 'i1' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result2.i1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "i1").WithArguments("(int, int)", "i1").WithLocation(19, 38) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation1 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("i.M((null, null))", invocation1.ToString()); Assert.Equal("(System.Int32 i1, System.Int32 i2) I.M((System.String, System.String) a)", model.GetSymbolInfo(invocation1.Expression).Symbol.ToTestDisplayString()); var invocation2 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(2); Assert.Equal("c.M((null, null))", invocation2.ToString()); Assert.Equal("(System.Int32, System.Int32) C.M((System.String, System.String) a)", model.GetSymbolInfo(invocation2.Expression).Symbol.ToTestDisplayString()); } [Fact] public void ImplementValueTupleInterfaceWithTuple() { string source = @" public interface I { System.ValueTuple<int, int> M(System.ValueTuple<string, string> a); } class C : I { static void Main() { I i = new C(); var r = i.M((""Alice"", ""Bob"")); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } public (int, int) M((string, string) a) { return new System.ValueTuple<int, int>(a.Item1.Length, a.Item2.Length); } } "; var comp = CompileAndVerify(source, expectedOutput: @"5 3"); comp.VerifyDiagnostics(); } [Fact] public void ImplementInterfaceWithGeneric() { string source = @" public interface I<TB, TA> where TB : TA { (TB, TA, TC) M<TC>((TB, (TA, TC)) arg) where TC : TB; } public class CA { public override string ToString() { return ""CA""; } } public class CB : CA { public override string ToString() { return ""CB""; } } public class CC : CB { public override string ToString() { return ""CC""; } } class C : I<CB, CA> { static void Main() { I<CB, CA> i = new C(); var r = i.M((new CB(), (new CA(), new CC()))); System.Console.WriteLine($""{r.Item1} {r.Item2} {r.Item3}""); } public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) where TC : CB { return (arg.Item1, arg.Item2.Item1, arg.Item2.Item2); } } "; var comp = CompileAndVerify(source, expectedOutput: @"CB CA CC"); comp.VerifyDiagnostics(); } [Fact] public void ImplementInterfaceWithGenericError() { string source = @" public interface I<TB, TA> where TB : TA { (TB, TA, TC) M<TC>((TB, (TA, TC)) arg) where TC : TB; } public class CA { } public class CB : CA { } public class CC : CB { } class C1 : I<CB, CA> { public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) { return (arg.Item1, arg.Item2.Item1, arg.Item2.Item2); } } class C2 : I<CB, CA> { public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) where TC : CB { return (arg.Item2.Item1, arg.Item1, arg.Item2.Item2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,25): error CS0425: The constraints for type parameter 'TC' of method 'C1.M<TC>((CB, (CA, TC)))' must match the constraints for type parameter 'TC' of interface method 'I<CB, CA>.M<TC>((CB, (CA, TC)))'. Consider using an explicit interface implementation instead. // public (CB, CA, TC) M<TC>((CB, (CA, TC)) arg) Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("TC", "C1.M<TC>((CB, (CA, TC)))", "TC", "I<CB, CA>.M<TC>((CB, (CA, TC)))").WithLocation(15, 25), // (25,17): error CS0029: Cannot implicitly convert type 'CA' to 'CB' // return (arg.Item2.Item1, arg.Item1, arg.Item2.Item2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "arg.Item2.Item1").WithArguments("CA", "CB").WithLocation(25, 17) ); } [Fact] public void OverrideTupleMethodWithDifferentNames() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int e, int f) M((int g, int h) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,36): error CS8139: 'D.M((int g, int h))': cannot change tuple element names when overriding inherited member 'C.M((int c, int d))' // public override (int e, int f) M((int g, int h) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M((int g, int h))", "C.M((int c, int d))").WithLocation(11, 36) ); } [Fact] public void OverrideTupleMethodWithDifferentNamesInParameterType() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int, int) M((int g, int h) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,32): error CS8139: 'D.M((int g, int h))': cannot change tuple element names when overriding inherited member 'C.M((int c, int d))' // public override (int, int) M((int g, int h) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M((int g, int h))", "C.M((int c, int d))").WithLocation(11, 32) ); } [Fact] public void OverrideTupleMethodWithDifferentNamesInReturnType() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int e, int f) M((int, int) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,36): error CS8139: 'D.M((int, int))': cannot change tuple element names when overriding inherited member 'C.M((int c, int d))' // public override (int e, int f) M((int, int) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M((int, int))", "C.M((int c, int d))").WithLocation(11, 36) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTupleMethodWithNoNames() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { throw new System.Exception(); } } class D : C { public override (int, int) M((int, int) y) { return y; } } class E { void M(D d) { var result = d.M((1, 2)); System.Console.Write(result.a); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (21,37): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(21, 37) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("d.M((1, 2))", invocation.ToString()); Assert.Equal("(System.Int32, System.Int32) D.M((System.Int32, System.Int32) y)", model.GetSymbolInfo(invocation.Expression).Symbol.ToTestDisplayString()); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTupleMethodWithNoNamesWithValueTuple() { string source = @" using System; class C { public virtual (int a, int b) M((int c, int d) x) { throw null; } } class D : C { public override ValueTuple<int, int> M(ValueTuple<int, int> y) { return y; } } class E { void M(D d) { var result = d.M((1, 2)); System.Console.Write(result.a); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,37): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(22, 37) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("d.M((1, 2))", invocation.ToString()); Assert.Equal("(System.Int32, System.Int32) D.M((System.Int32, System.Int32) y)", model.GetSymbolInfo(invocation.Expression).Symbol.ToTestDisplayString()); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTuplePropertyWithNoNames() { string source = @" class C { public virtual (int a, int b) P { get; set; } } class D : C { public override (int, int) P { get; set; } void M(D d) { var result = d.P; var result2 = this.P; var result3 = base.P; System.Console.Write(result.a); System.Console.Write(result2.a); System.Console.Write(result3.a); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,37): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(14, 37), // (15,38): error CS1061: '(int, int)' does not contain a definition for 'a' and no extension method 'a' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result2.a); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a").WithArguments("(int, int)", "a").WithLocation(15, 38) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var memberAccess = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ElementAt(0); Assert.Equal("d.P", memberAccess.ToString()); Assert.Equal("(System.Int32, System.Int32) D.P { get; set; }", model.GetSymbolInfo(memberAccess).Symbol.ToTestDisplayString()); var memberAccess2 = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ElementAt(1); Assert.Equal("this.P", memberAccess2.ToString()); Assert.Equal("(System.Int32, System.Int32) D.P { get; set; }", model.GetSymbolInfo(memberAccess2).Symbol.ToTestDisplayString()); var memberAccess3 = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ElementAt(2); Assert.Equal("base.P", memberAccess3.ToString()); Assert.Equal("(System.Int32 a, System.Int32 b) C.P { get; set; }", model.GetSymbolInfo(memberAccess3).Symbol.ToTestDisplayString()); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void OverrideTupleEventWithNoNames() { string source = @" class C { public virtual event System.Func<((int a, int b) c, int d)> E; } class D : C { public override event System.Func<((int, int), int)> E; void M(D d) { var result = d.E(); System.Console.Write(result.c); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,37): error CS1061: '((int, int), int)' does not contain a definition for 'c' and no extension method 'c' accepting a first argument of type '((int, int), int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(result.c); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c").WithArguments("((int, int), int)", "c").WithLocation(12, 37), // (4,65): warning CS0067: The event 'C.E' is never used // public virtual event System.Func<((int a, int b) c, int d)> E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(4, 65) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ElementAt(0); Assert.Equal("d.E()", invocation.ToString()); Assert.Equal("event System.Func<((System.Int32, System.Int32), System.Int32)> D.E", model.GetSymbolInfo(invocation.Expression).Symbol.ToTestDisplayString()); } [Fact] public void NewTupleMethodWithDifferentNames() { string source = @" class C { public virtual (int a, int b) M((int c, int d) x) { System.Console.WriteLine(""base""); return x; } } class D : C { static void Main() { D d = new D(); d.M((1, 2)); C c = d; c.M((1, 2)); } public new (int e, int f) M((int g, int h) y) { System.Console.Write(""new ""); return y; } } "; var comp = CompileAndVerify(source, expectedOutput: @"new base"); comp.VerifyDiagnostics(); } [Fact] public void DuplicateTupleMethodsNotAllowed() { string source = @" class C { public (int, int) M((string, string) a) { return new System.ValueTuple<int, int>(a.Item1.Length, a.Item2.Length); } public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) { return (a.Item1.Length, a.Item2.Length); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,40): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types // public System.ValueTuple<int, int> M(System.ValueTuple<string, string> a) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(9, 40) ); } [Fact] public void TupleArrays() { string source = @" public interface I { System.ValueTuple<int, int>[] M((int, int)[] a); } class C : I { static void Main() { I i = new C(); var r = i.M(new [] { new System.ValueTuple<int, int>(1, 2) }); System.Console.WriteLine($""{r[0].Item1} {r[0].Item2}""); } public (int, int)[] M(System.ValueTuple<int, int>[] a) { return new [] { (a[0].Item1, a[0].Item2) }; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 2"); comp.VerifyDiagnostics(); } [Fact] public void TupleRef() { string source = @" class C { static void Main() { var r = (1, 2); M(ref r); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } static void M(ref (int, int) a) { System.Console.WriteLine($""{a.Item1} {a.Item2}""); a = (3, 4); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"1 2 3 4"); comp.VerifyDiagnostics(); } [Fact] public void TupleOut() { string source = @" class C { static void Main() { (int, int) r; M(out r); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } static void M(out (int, int) a) { a = (1, 2); } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 2"); comp.VerifyDiagnostics(); } [Fact] public void TupleTypeArgs() { string source = @" class C { static void Main() { var a = (1, ""Alice""); var r = M<int, string>(a); System.Console.WriteLine($""{r.Item1} {r.Item2}""); } static (T1, T2) M<T1, T2>((T1, T2) a) { return a; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 Alice"); comp.VerifyDiagnostics(); } [Fact] public void NullableTuple() { string source = @" class C { static void Main() { M((1, ""Alice"")); } static void M((int, string)? a) { System.Console.WriteLine($""{a.HasValue} {a.Value.Item1} {a.Value.Item2}""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"True 1 Alice"); comp.VerifyDiagnostics(); } [Fact] public void TupleUnsupportedInUsingStatement() { var source = @" using VT2 = (int, int); "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,13): error CS1001: Identifier expected // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 13), // (2,13): error CS1002: ; expected // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_SemicolonExpected, "(").WithLocation(2, 13), // (2,14): error CS1525: Invalid expression term 'int' // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(2, 14), // (2,19): error CS1525: Invalid expression term 'int' // using VT2 = (int, int); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(2, 19), // (2,1): hidden CS8019: Unnecessary using directive. // using VT2 = (int, int); Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using VT2 = ").WithLocation(2, 1) ); } [Fact] public void TupleWithVar() { var source = @" class C { static void Main() { (int, var) x = (1, 2); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,15): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // (int, var) x = (1, 2); Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 15) ); } [Fact] [WorkItem(12032, "https://github.com/dotnet/roslyn/issues/12032")] public void MissingTypeInAlias() { var source = @" using System; using VT2 = System.ValueTuple<int, int>; // ValueTuple is referenced but does not exist namespace System { public class Bogus { } } namespace TuplesCrash2 { class Program { static void Main(string[] args) { } } } "; var tree = Parse(source); var comp = CreateCompilation(new[] { tree }); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); model.LookupStaticMembers(201); // This position is inside Main method for (int pos = 0; pos < source.Length; pos++) { model.LookupStaticMembers(pos); } // didn't crash } [Fact] [WorkItem(11302, "https://github.com/dotnet/roslyn/issues/11302")] public void MultipleDefinitionsOfValueTuple() { var source1 = @" public static class C1 { public static void M1(this int x, (int, int) y) { System.Console.WriteLine(""C1.M1""); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public static class C2 { public static void M1(this int x, (int, int) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source = @" class C3 { public static void Main() { int x = 0; x.M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }); comp.VerifyDiagnostics( // (7,14): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // x.M1((1, 1)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) ); comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference() }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1.M1"); } [Fact] [WorkItem(12082, "https://github.com/dotnet/roslyn/issues/12082")] public void TupleWithDynamic() { var source = @" class C { static void Main() { (dynamic, dynamic) d1 = (1, 1); // implicit to dynamic System.Console.WriteLine(d1); (dynamic, dynamic) d2 = M(); System.Console.WriteLine(d2); (int, int) t3 = (3, 3); (dynamic, dynamic) d3 = t3; System.Console.WriteLine(d3); (int, int) t4 = (4, 4); (dynamic, dynamic) d4 = ((dynamic, dynamic))t4; // explicit to dynamic System.Console.WriteLine(d4); dynamic d5 = 5; (int, int) t5 = (d5, d5); // implicit from dynamic System.Console.WriteLine(t5); (dynamic, dynamic) d6 = (6, 6); (int, int) t6 = ((int, int))d6; // explicit from dynamic System.Console.WriteLine(t6); (dynamic, dynamic) d7; (int, int) t7 = (7, 7); d7 = t7; System.Console.WriteLine(d7); } static (dynamic, dynamic) M() { return (2, 2); } } "; string expectedOutput = @"(1, 1) (2, 2) (3, 3) (4, 4) (5, 5) (6, 6) (7, 7) "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); comp.VerifyDiagnostics(); } [Fact] [WorkItem(12082, "https://github.com/dotnet/roslyn/issues/12082")] public void TupleWithDynamic2() { var source = @" class C { static void Main() { (dynamic, dynamic) d = (1, 1); (int, int) t = d; } } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (7,24): error CS0266: Cannot implicitly convert type '(dynamic, dynamic)' to '(int, int)'. An explicit conversion exists (are you missing a cast?) // (int, int) t = d; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "d").WithArguments("(dynamic, dynamic)", "(int, int)").WithLocation(7, 24) ); } [Fact] public void TupleWithDynamic3() { var source = @" class C { public static void Main() { dynamic longTuple = (a: 2, b: 2, c: 2, d: 2, e: 2, f: 2, g: 2, h: 2, i: 2); System.Console.Write($""Item1: {longTuple.Item1} Rest: {longTuple.Rest}""); try { System.Console.Write(longTuple.a); System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} try { System.Console.Write(longTuple.i); System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} try { System.Console.Write(longTuple.Item9); System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} } } "; var comp = CompileAndVerify(source, expectedOutput: "Item1: 2 Rest: (2, 2)", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleWithDynamic4() { var source = @" class C { public static void Main() { dynamic x = (1, 2, 3, 4, 5, 6, 7, 8, 9); M(x); } public static void M((int a, int, int, int, int, int, int, int h, int i) t) { System.Console.Write($""a:{t.a}, h:{t.h}, i:{t.i}, Item9:{t.Item9}, Rest:{t.Rest}""); } } "; var comp = CompileAndVerify(source, expectedOutput: "a:1, h:8, i:9, Item9:9, Rest:(8, 9)", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleWithDynamic5() { var source = @" class C { public static void Main() { dynamic d = (1, 2); try { (string, string) t = d; System.Console.Write(""unreachable""); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) {} System.Console.Write(""done""); } } "; var comp = CompileAndVerify(source, expectedOutput: "done", references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void TupleWithDynamic6() { var source = @" class C { public static void Main() { (int, int) t1 = (1, 1); M(t1, ""int""); (byte, byte) t2 = (2, 2); M(t2, ""byte""); (dynamic, dynamic) t3 = (3, 3); M(t3, ""dynamic""); (string, string) t4 = (""4"", ""4""); M(t4, ""string""); } public static void M((int, int) t, string type) { System.Console.WriteLine($""int overload with value {t} and type {type}""); } public static void M((dynamic, dynamic) t, string type) { System.Console.WriteLine($""dynamic overload with value {t} and type {type}""); } } "; string expectedOutput = @"int overload with value (1, 1) and type int int overload with value (2, 2) and type byte dynamic overload with value (3, 3) and type dynamic dynamic overload with value (4, 4) and type string"; var comp = CompileAndVerify(source, expectedOutput: expectedOutput, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); } [Fact] public void Tuple2To8Members() { var source = @" class C { static void Main() { System.Console.Write((1, 2).Item1); System.Console.Write((1, 2).Item2); System.Console.Write((3, 4, 5).Item1); System.Console.Write((3, 4, 5).Item2); System.Console.Write((3, 4, 5).Item3); System.Console.Write((6, 7, 8, 9).Item1); System.Console.Write((6, 7, 8, 9).Item2); System.Console.Write((6, 7, 8, 9).Item3); System.Console.Write((6, 7, 8, 9).Item4); System.Console.Write((0, 1, 2, 3, 4).Item1); System.Console.Write((0, 1, 2, 3, 4).Item2); System.Console.Write((0, 1, 2, 3, 4).Item3); System.Console.Write((0, 1, 2, 3, 4).Item4); System.Console.Write((0, 1, 2, 3, 4).Item5); System.Console.Write((5, 6, 7, 8, 9, 0).Item1); System.Console.Write((5, 6, 7, 8, 9, 0).Item2); System.Console.Write((5, 6, 7, 8, 9, 0).Item3); System.Console.Write((5, 6, 7, 8, 9, 0).Item4); System.Console.Write((5, 6, 7, 8, 9, 0).Item5); System.Console.Write((5, 6, 7, 8, 9, 0).Item6); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item1); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item2); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item3); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item4); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item5); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item6); System.Console.Write((1, 2, 3, 4, 5, 6, 7).Item7); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item1); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item2); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item3); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item4); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item5); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item6); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item7); System.Console.Write((8, 9, 0, 1, 2, 3, 4, 5).Item8); } } "; var comp = CompileAndVerify(source, expectedOutput: "12345678901234567890123456789012345"); } [Fact] public void CreateTupleTypeSymbol_BadArguments() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); Assert.Throws<ArgumentNullException>(() => comp.CreateTupleTypeSymbol(null, default(ImmutableArray<string>))); // if names are provided, you need one for each element var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt2, new[] { "Item1" }.AsImmutable())); Assert.Contains(CodeAnalysisResources.TupleElementNameCountMismatch, e.Message); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt2, elementLocations: new[] { loc1 }.AsImmutable())); Assert.Contains(CodeAnalysisResources.TupleElementLocationCountMismatch, e.Message); } [Fact, WorkItem(36676, "https://github.com/dotnet/roslyn/issues/36676")] public void CreateTupleTypeSymbol_WithValueTuple_TupleZero() { var tupleComp = CreateCompilationWithMscorlib40(@" namespace System { public struct ValueTuple { } }"); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); var vt0 = comp.GetWellKnownType(WellKnownType.System_ValueTuple); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt0, ImmutableArray<string>.Empty); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.Null(tupleWithoutNames.TupleUnderlyingType); Assert.Equal("System.ValueTuple", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Empty(ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, vt0); Assert.False(vt8.IsTupleType); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt8, default)); } [Fact, WorkItem(36676, "https://github.com/dotnet/roslyn/issues/36676")] public void CreateTupleTypeSymbol_WithValueTuple_TupleOne() { var tupleComp = CreateCompilationWithMscorlib40(@" namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(intType); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt1, ImmutableArray.Create(new[] { (string)null })); Assert.Same(vt1, ((Symbols.PublicModel.NonErrorNamedTypeSymbol)tupleWithoutNames).UnderlyingNamedTypeSymbol); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32>", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32" }, ElementTypeNames(tupleWithoutNames)); } [Fact] public void CreateTupleTypeSymbol_WithValueTuple() { var tupleComp = CreateCompilationWithMscorlib40(trivial2uple); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create<string>(null, null)); Assert.Same(vt2, ((Symbols.PublicModel.NamedTypeSymbol)tupleWithoutNames).UnderlyingNamedTypeSymbol); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.Null(tupleWithoutNames.TupleUnderlyingType); Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.All(tupleWithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } private static ImmutableArray<string> GetTupleElementNames(INamedTypeSymbol tuple) { var elements = tuple.TupleElements; if (elements.All(e => e.IsImplicitlyDeclared)) { return default(ImmutableArray<string>); } return elements.SelectAsArray(e => e.ProvidedTupleElementNameOrNull()); } [Fact] public void CreateTupleTypeSymbol_Locations() { var tupleComp = CreateCompilation(trivial2uple); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); var intType = comp.GetSpecialType(SpecialType.System_Int32); var stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); var loc2 = Location.Create(tree, new TextSpan(1, 1)); var tuple = comp.CreateTupleTypeSymbol( vt2, ImmutableArray.Create<string>("i1", "i2"), ImmutableArray.Create(loc1, loc2)); Assert.True(tuple.IsTupleType); Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind); Assert.Equal("(System.Int32 i1, System.String i2)", tuple.ToTestDisplayString()); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tuple)); Assert.Equal(SymbolKind.NamedType, tuple.Kind); Assert.Equal(loc1, tuple.GetMembers("i1").Single().Locations.Single()); Assert.Equal(loc2, tuple.GetMembers("i2").Single().Locations.Single()); } [Fact] public void MemberNamesOnValueTupleFromPEWithoutFields() { string trivial2uple_withoutFields = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; public override string ToString() => throw null; } }"; var tupleComp = CreateCompilation(trivial2uple_withoutFields); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.EmitToImageReference() }); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); AssertEx.SetEqual(vt2.MemberNames.ToArray(), new[] { ".ctor", "ToString" }); } [Fact] public void CreateTupleTypeSymbol_NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, default(ImmutableArray<string>)); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.Kind); Assert.Null(tupleWithoutNames.TupleUnderlyingType); Assert.Equal("(System.Int32, System.String)[missing]", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.Kind); Assert.All(tupleWithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var tupleWithNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Alice", "Bob")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Alice, System.String Bob)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice", "Bob" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); Assert.All(tupleWithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_WithSomeNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, stringType, intType); var tupleWithSomeNames = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create(null, "Item2", "Charlie")); Assert.True(tupleWithSomeNames.IsTupleType); Assert.Equal("(System.Int32, System.String Item2, System.Int32 Charlie)[missing]", tupleWithSomeNames.ToTestDisplayString()); Assert.Equal(new[] { null, "Item2", "Charlie" }, GetTupleElementNames(tupleWithSomeNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tupleWithSomeNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithSomeNames.Kind); Assert.All(tupleWithSomeNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_WithBadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); var tupleWithNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item2", "Item1")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Item2, System.Int32 Item1)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Item2", "Item1" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.Int32" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); Assert.All(tupleWithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple8NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)); var tuple8WithoutNames = comp.CreateTupleTypeSymbol(vt8, default(ImmutableArray<string>)); Assert.True(tuple8WithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithoutNames.ToTestDisplayString()); Assert.False(vt8.OriginalDefinition.IsTupleType); Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithoutNames)); Assert.All(tuple8WithoutNames.TupleElements.Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple8NoNames_WithValueTupleTypes() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)); var tuple8WithoutNames = comp.CreateTupleTypeSymbol(vt8, elementNames: default); Assert.Same(vt8, ((Symbols.PublicModel.NamedTypeSymbol)tuple8WithoutNames).UnderlyingNamespaceOrTypeSymbol); Assert.True(tuple8WithoutNames.IsTupleType); Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)", tuple8WithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithoutNames)); Assert.All(tuple8WithoutNames.GetMembers().OfType<IFieldSymbol>().Where(f => f.Name != "Rest").Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple8WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)); var tuple8WithNames = comp.CreateTupleTypeSymbol(vt8, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")); Assert.True(tuple8WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8" }, GetTupleElementNames(tuple8WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithNames)); Assert.All(tuple8WithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple9NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)); var tuple9WithoutNames = comp.CreateTupleTypeSymbol(vt9, default(ImmutableArray<string>)); Assert.True(tuple9WithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithoutNames)); Assert.All(tuple9WithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple9WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)); var tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")); Assert.True(tuple9WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9" }, GetTupleElementNames(tuple9WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithNames)); Assert.All(tuple9WithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_Tuple9WithDefaultNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var originalVT2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.True(originalVT2.IsDefinition); var vt2 = originalVT2.Construct(intType, intType); Assert.False(vt2.IsDefinition); comp.CreateTupleTypeSymbol(vt2, new[] { "Item1", "Item2" }.AsImmutable()); var vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest) .Construct(intType, stringType, intType, stringType, intType, stringType, intType, vt2); var tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); Assert.True(tuple9WithNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.Int32, System.Int32)[missing]>[missing]", tuple9WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9" }, GetTupleElementNames(tuple9WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.Int32", "System.Int32" }, ElementTypeNames(tuple9WithNames)); Assert.All(tuple9WithNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact] public void CreateTupleTypeSymbol_ElementTypeIsError() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); var vt2WithErrorType = vt2.Construct(intType, ErrorTypeSymbol.UnknownResultType); var tupleWithoutNames = ((Symbols.PublicModel.NamedTypeSymbol)comp.CreateTupleTypeSymbol(vt2WithErrorType, elementNames: default)).UnderlyingNamedTypeSymbol; Assert.Same(vt2WithErrorType, tupleWithoutNames); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); var types = tupleWithoutNames.TupleElements.SelectAsArray(e => e.Type); Assert.Equal(2, types.Length); Assert.Equal(SymbolKind.NamedType, types[0].Kind); Assert.Equal(SymbolKind.ErrorType, types[1].Kind); Assert.All(tupleWithoutNames.GetMembers().OfType<IFieldSymbol>().Select(f => f.Locations.FirstOrDefault()), loc => Assert.Null(loc)); } [Fact, WorkItem(13277, "https://github.com/dotnet/roslyn/issues/13277")] [WorkItem(14365, "https://github.com/dotnet/roslyn/issues/14365")] public void CreateTupleTypeSymbol_UnderlyingTypeIsError() { var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, TestReferences.SymbolsTests.netModule.netModule1 }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.CreateErrorTypeSymbol(null, "ValueTuple", 2).Construct(intType, intType); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(underlyingType: vt2)); var vbComp = CreateVisualBasicCompilation(""); Assert.Throws<ArgumentNullException>(() => comp.CreateErrorTypeSymbol(null, null, 2)); Assert.Throws<ArgumentException>(() => comp.CreateErrorTypeSymbol(null, "a", -1)); Assert.Throws<ArgumentException>(() => comp.CreateErrorTypeSymbol(vbComp.GlobalNamespace, "a", 1)); Assert.Throws<ArgumentNullException>(() => comp.CreateErrorNamespaceSymbol(null, "a")); Assert.Throws<ArgumentNullException>(() => comp.CreateErrorNamespaceSymbol(vbComp.GlobalNamespace, null)); Assert.Throws<ArgumentException>(() => comp.CreateErrorNamespaceSymbol(vbComp.GlobalNamespace, "a")); var ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a"); Assert.Equal("a", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind); Assert.Same(comp.GlobalNamespace, ns.ContainingSymbol); Assert.Same(comp.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly); Assert.Same(comp.GlobalNamespace.ContainingModule, ns.ContainingModule); ns = comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "a"); Assert.Equal("a", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); Assert.Equal(NamespaceKind.Assembly, ns.NamespaceKind); Assert.Same(comp.Assembly.GlobalNamespace, ns.ContainingSymbol); Assert.Same(comp.Assembly.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly); Assert.Same(comp.Assembly.GlobalNamespace.ContainingModule, ns.ContainingModule); ns = comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "a"); Assert.Equal("a", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); Assert.Equal(NamespaceKind.Module, ns.NamespaceKind); Assert.Same(comp.SourceModule.GlobalNamespace, ns.ContainingSymbol); Assert.Same(comp.SourceModule.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly); Assert.Same(comp.SourceModule.GlobalNamespace.ContainingModule, ns.ContainingModule); ns = comp.CreateErrorNamespaceSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a"), "b"); Assert.Equal("a.b", ns.ToTestDisplayString()); ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, ""); Assert.Equal("", ns.ToTestDisplayString()); Assert.False(ns.IsGlobalNamespace); vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType); Assert.Equal("(System.Int32, System.Int32)[missing]", comp.CreateTupleTypeSymbol(underlyingType: vt2).ToTestDisplayString()); vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType); Assert.Equal("(System.Int32, System.Int32)[missing]", comp.CreateTupleTypeSymbol(underlyingType: vt2).ToTestDisplayString()); vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType); Assert.Equal("(System.Int32, System.Int32)[missing]", comp.CreateTupleTypeSymbol(underlyingType: vt2).ToTestDisplayString()); } [Fact] public void CreateTupleTypeSymbol_BadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); NamedTypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); var vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, intType, intType); // illegal C# identifiers, space and null var tuple2 = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create("123", " ", null)); Assert.Equal(new[] { "123", " ", null }, GetTupleElementNames(tuple2)); // reserved identifiers var tuple3 = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("return", "class")); Assert.Equal(new[] { "return", "class" }, GetTupleElementNames(tuple3)); // not tuple-compatible underlying type var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(intType)); Assert.Contains(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, e.Message); } [Fact] public void CreateTupleTypeSymbol_EmptyNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); NamedTypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); // illegal C# identifiers and blank var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("123", ""))); Assert.Contains(CodeAnalysisResources.TupleElementNameEmpty, e.Message); Assert.Contains("elementNames[1]", e.Message); } [Fact] public void CreateTupleTypeSymbol_VisualBasicElements() { var vbSource = @"Public Class C End Class"; var vbComp = CreateVisualBasicCompilation("VB", vbSource, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbComp.VerifyDiagnostics(); INamedTypeSymbol vbType = (INamedTypeSymbol)vbComp.GlobalNamespace.GetMembers("C").Single(); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(vbType, default(ImmutableArray<string>))); Assert.Contains(CSharpResources.NotACSharpSymbol, e.Message); } [Fact] public void CreateAnonymousTypeSymbol_VisualBasicElements() { var vbSource = @"Public Class C End Class"; var vbComp = CreateVisualBasicCompilation("VB", vbSource, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbComp.VerifyDiagnostics(); var vbType = (ITypeSymbol)vbComp.GlobalNamespace.GetMembers("C").Single(); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); var e = Assert.Throws<ArgumentException>(() => comp.CreateAnonymousTypeSymbol(ImmutableArray.Create(vbType), ImmutableArray.Create("m1"))); Assert.Contains(CSharpResources.NotACSharpSymbol, e.Message); } [Fact] public void CreateTupleTypeSymbol2_BadArguments() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); Assert.Throws<ArgumentNullException>(() => comp.CreateTupleTypeSymbol(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<string>))); // 0-tuple and 1-tuple are not supported at this point Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(ImmutableArray<ITypeSymbol>.Empty, default(ImmutableArray<string>))); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(new[] { intType }.AsImmutable(), default(ImmutableArray<string>))); // if names are provided, you need one for each element Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(new[] { intType, intType }.AsImmutable(), new[] { "Item1" }.AsImmutable())); var syntaxTree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(syntaxTree, new TextSpan(0, 1)); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(new[] { intType, intType }.AsImmutable(), elementLocations: ImmutableArray.Create(loc1))); // null types aren't allowed Assert.Throws<ArgumentNullException>(() => comp.CreateTupleTypeSymbol(new[] { intType, null }.AsImmutable(), default(ImmutableArray<string>))); } [Fact] public void CreateTupleTypeSymbol2_WithValueTuple() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create<string>(null, null)); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); Assert.True(tupleWithoutNames.GetMembers("Item1").Single().Locations.IsEmpty); } [Fact] public void CreateTupleTypeSymbol_WithLocations() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); var intType = comp.GetSpecialType(SpecialType.System_Int32); var stringType = comp.GetSpecialType(SpecialType.System_String); var syntaxTree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(syntaxTree, new TextSpan(0, 1)); var loc2 = Location.Create(syntaxTree, new TextSpan(1, 1)); var tuple = comp.CreateTupleTypeSymbol( ImmutableArray.Create<TypeSymbol>(intType, stringType), ImmutableArray.Create<string>(null, null), ImmutableArray.Create(loc1, loc2)); Assert.True(tuple.IsTupleType); Assert.Equal("(System.Int32, System.String)", tuple.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tuple)); Assert.Equal(SymbolKind.NamedType, tuple.Kind); Assert.Equal(loc1, tuple.GetMembers("Item1").Single().Locations.Single()); Assert.Equal(loc2, tuple.GetMembers("Item2").Single().Locations.Single()); } private static IEnumerable<string> ElementTypeNames(INamedTypeSymbol tuple) { return tuple.TupleElements.Select(t => t.Type.ToTestDisplayString()); } [Fact] public void CreateTupleTypeSymbol2_NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), default(ImmutableArray<string>)); Assert.True(tupleWithoutNames.IsTupleType); Assert.Equal("(System.Int32, System.String)[missing]", tupleWithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithoutNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.Kind); } [Fact] public void CreateTupleTypeSymbol2_WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tupleWithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("Alice", "Bob")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Alice, System.String Bob)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice", "Bob" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.String" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); } [Fact] public void CreateTupleTypeSymbol2_WithBadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var tupleWithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("Item2", "Item1")); Assert.True(tupleWithNames.IsTupleType); Assert.Equal("(System.Int32 Item2, System.Int32 Item1)[missing]", tupleWithNames.ToTestDisplayString()); Assert.Equal(new[] { "Item2", "Item1" }, GetTupleElementNames(tupleWithNames)); Assert.Equal(new[] { "System.Int32", "System.Int32" }, ElementTypeNames(tupleWithNames)); Assert.Equal(SymbolKind.ErrorType, tupleWithNames.Kind); } [Fact] public void CreateTupleTypeSymbol2_Tuple8NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple8WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), default(ImmutableArray<string>)); Assert.True(tuple8WithoutNames.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithoutNames.ToTestDisplayString()); Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithoutNames)); } [Fact] public void CreateTupleTypeSymbol2_Tuple8WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple8WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")); Assert.True(tuple8WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.ValueTuple<System.String>[missing]>[missing]", tuple8WithNames.ToTestDisplayString()); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8" }, GetTupleElementNames(tuple8WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String" }, ElementTypeNames(tuple8WithNames)); } [Fact] public void CreateTupleTypeSymbol2_Tuple9NoNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple9WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), default(ImmutableArray<string>)); Assert.True(tuple9WithoutNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithoutNames.ToTestDisplayString()); Assert.False(tuple9WithoutNames.IsDefinition); Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithoutNames)); } [Fact] public void CreateTupleTypeSymbol2_Tuple9WithNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); // no ValueTuple TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var tuple9WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")); Assert.True(tuple9WithNames.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, (System.String, System.Int32)[missing]>[missing]", tuple9WithNames.ToTestDisplayString()); Assert.False(tuple9WithNames.IsDefinition); Assert.Equal(new[] { "Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9" }, GetTupleElementNames(tuple9WithNames)); Assert.Equal(new[] { "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32" }, ElementTypeNames(tuple9WithNames)); } [Fact] public void CreateTupleTypeSymbol2_ElementTypeIsError() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); var tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, ErrorTypeSymbol.UnknownResultType), default(ImmutableArray<string>)); Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind); var types = tupleWithoutNames.TupleElements.SelectAsArray(e => e.Type); Assert.Equal(2, types.Length); Assert.Equal(SymbolKind.NamedType, types[0].Kind); Assert.Equal(SymbolKind.ErrorType, types[1].Kind); } [Fact] public void CreateTupleTypeSymbol2_BadNames() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); // illegal C# identifiers and blank var tuple2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("123", " ")); Assert.Equal(new[] { "123", " " }, GetTupleElementNames(tuple2)); // reserved identifiers var tuple3 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("return", "class")); Assert.Equal(new[] { "return", "class" }, GetTupleElementNames(tuple3)); } [Fact] public void CreateTupleTypeSymbol2_VisualBasicElements() { var vbSource = @"Public Class C End Class"; var vbComp = CreateVisualBasicCompilation("VB", vbSource, compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vbComp.VerifyDiagnostics(); ITypeSymbol vbType = (ITypeSymbol)vbComp.GlobalNamespace.GetMembers("C").Single(); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); INamedTypeSymbol intType = comp.GetSpecialType(SpecialType.System_String).GetPublicSymbol(); Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, vbType), default(ImmutableArray<string>))); } [Fact] public void CreateTupleTypeSymbol_ComparingSymbols() { var source = @" class C { System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)> F; } "; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IFieldSymbol>("F").Type; var intType = comp.GetSpecialType(SpecialType.System_Int32); var stringType = comp.GetSpecialType(SpecialType.System_String); var twoStrings = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, stringType); var twoStringsWithNames = comp.CreateTupleTypeSymbol(twoStrings, ImmutableArray.Create("a", "b")); var tuple2Underlying = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).Construct(intType, intType, intType, intType, intType, intType, intType, twoStringsWithNames); var tuple2 = comp.CreateTupleTypeSymbol(tuple2Underlying); var tuple3 = comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(intType, intType, intType, intType, intType, intType, intType, stringType, stringType), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")); var tuple4 = comp.CreateTupleTypeSymbol(tuple1, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")); Assert.True(tuple1.Equals(tuple2)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(tuple1.Equals(tuple3)); Assert.True(tuple1.Equals(tuple3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(tuple1.Equals(tuple4)); Assert.True(tuple1.Equals(tuple4, TypeCompareKind.IgnoreDynamicAndTupleNames)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_UnderlyingType_DefaultArgs_01() { var source = @"class Program { (int, string) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; Assert.Null(tuple1.TupleUnderlyingType); var underlyingType = tuple1; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] [WorkItem(40105, "https://github.com/dotnet/roslyn/issues/40105")] public void CreateTupleTypeSymbol_UnderlyingType_DefaultArgs_02() { var source = @"class Program { (string, #nullable enable string, string?) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; Assert.Null(tuple1.TupleUnderlyingType); var underlyingType = tuple1; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_ElementTypes_DefaultArgs_01() { var source = @"class Program { (int, string) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] [WorkItem(40105, "https://github.com/dotnet/roslyn/issues/40105")] public void CreateTupleTypeSymbol_ElementTypes_DefaultArgs_02() { var source = @"class Program { (string, #nullable enable string, string?) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default, default, default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, default(ImmutableArray<string>), default(ImmutableArray<Location>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNames: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementLocations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_01() { var source = @"class Program { (int, string) F; }"; var comp = CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((FieldSymbol)comp.GetMember("Program.F")).GetPublicSymbol().Type; Assert.Null(tuple1.TupleUnderlyingType); var underlyingType = tuple1; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2, TypeCompareKind.ConsiderEverything)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.True(tuple1.Equals(tuple2)); Assert.False(tuple1.Equals(tuple2, SymbolEqualityComparer.IncludeNullability)); Assert.Equal("(System.Int32, System.String?)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_02() { var source = @"class Program { (object _1, object _2, object _3, object _4, object _5, object _6, object _7, object _8, object _9) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var underlyingType = tuple1.TupleUnderlyingType; var tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: default); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)); Assert.False(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Assert.Equal("(System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?)", tuple2.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_01() { var source = @"class Program { (int, string) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(tuple1.Equals(tuple2)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.True(tuple1.Equals(tuple2)); Assert.False(tuple1.Equals(tuple2, SymbolEqualityComparer.IncludeNullability)); Assert.Equal("(System.Int32, System.String?)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)); Assert.True(tuple1.Equals(tuple2)); Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_02() { var source = @"class Program { (object _1, object _2, object _3, object _4, object _5, object _6, object _7, object _8, object _9) F; }"; var comp = (Compilation)CreateCompilation(source); var tuple1 = (INamedTypeSymbol)((IFieldSymbol)comp.GetMember("Program.F")).Type; var elementTypes = tuple1.TupleElements.SelectAsArray(e => e.Type); var tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: default); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); var e = Assert.Throws<ArgumentException>(() => comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))); Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, e.Message); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString(includeNonNullable: true)); tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations: CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)); Assert.False(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)); Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Assert.Equal("(System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?, System.Object?)", tuple2.ToTestDisplayString(includeNonNullable: true)); } private static ImmutableArray<CodeAnalysis.NullableAnnotation> CreateAnnotations(CodeAnalysis.NullableAnnotation annotation, int n) => ImmutableArray.CreateRange(Enumerable.Range(0, n).Select(_ => annotation)); private static bool TypeEquals(ITypeSymbol a, ITypeSymbol b, TypeCompareKind compareKind) => a.Equals(b, compareKind); [Fact] public void TupleMethodsOnNonTupleType() { var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef }); NamedTypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); Assert.False(stringType.IsTupleType); Assert.True(stringType.TupleElements.IsDefault); Assert.Null(stringType.TupleUnderlyingType); } [Fact] public void TupleTargetTypeAndConvert01() { var source = @" class C { static void Main() { // this works (short, string) x1 = (1, ""hello""); // this does not (short, string) x2 = ((long, string))(1, ""hello""); // this does not (short a, string b) x3 = ((long c, string d))(1, ""hello""); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,30): error CS0266: Cannot implicitly convert type '(long, string)' to '(short, string)'. An explicit conversion exists (are you missing a cast?) // (short, string) x2 = ((long, string))(1, "hello"); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, @"((long, string))(1, ""hello"")").WithArguments("(long, string)", "(short, string)").WithLocation(10, 30), // (13,34): error CS0266: Cannot implicitly convert type '(long c, string d)' to '(short a, string b)'. An explicit conversion exists (are you missing a cast?) // (short a, string b) x3 = ((long c, string d))(1, "hello"); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, @"((long c, string d))(1, ""hello"")").WithArguments("(long c, string d)", "(short a, string b)").WithLocation(13, 34), // (7,25): warning CS0219: The variable 'x1' is assigned but its value is never used // (short, string) x1 = (1, "hello"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(7, 25), // (10,25): warning CS0219: The variable 'x2' is assigned but its value is never used // (short, string) x2 = ((long, string))(1, "hello"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(10, 25), // (13,29): warning CS0219: The variable 'x3' is assigned but its value is never used // (short a, string b) x3 = ((long c, string d))(1, "hello"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(13, 29) ); } [Fact] public void TupleTargetTypeAndConvert02() { var source = @" class C { static void Main() { (short, string) x2 = ((byte, string))(1, ""hello""); System.Console.WriteLine(x2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {1, hello}"); comp.VerifyIL("C.Main()", @" { // Code size 41 (0x29) .maxstack 3 .locals init (System.ValueTuple<byte, string> V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldstr ""hello"" IL_0008: call ""System.ValueTuple<byte, string>..ctor(byte, string)"" IL_000d: ldloc.0 IL_000e: ldfld ""byte System.ValueTuple<byte, string>.Item1"" IL_0013: ldloc.0 IL_0014: ldfld ""string System.ValueTuple<byte, string>.Item2"" IL_0019: newobj ""System.ValueTuple<short, string>..ctor(short, string)"" IL_001e: box ""System.ValueTuple<short, string>"" IL_0023: call ""void System.Console.WriteLine(object)"" IL_0028: ret } "); ; } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail01() { var source = @" class C { static void Main() { (int, int) x; x = (null, null, null); x = (1, 1, 1); x = (1, ""string""); x = (1, 1, garbage); x = (1, 1, ); x = (null, null); x = (1, null); x = (1, (t)=>t); x = null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (12,20): error CS1525: Invalid expression term ')' // x = (1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 20), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = (null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 13), // (9,13): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(int, int)' // x = (1, 1, 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 13), // (10,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // x = (1, "string"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 17), // (11,20): error CS0103: The name 'garbage' does not exist in the current context // x = (1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 20), // (13,14): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 14), // (13,20): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 20), // (14,17): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (1, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 17), // (15,17): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 17), // (16,13): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(int, int)").WithLocation(16, 13) ); } [Fact] public void TupleExplicitConversionFail01() { var source = @" class C { static void Main() { (int, int) x; x = ((int, int))(null, null, null); x = ((int, int))(1, 1, 1); x = ((int, int))(1, ""string""); x = ((int, int))(1, 1, garbage); x = ((int, int))(1, 1, ); x = ((int, int))(null, null); x = ((int, int))(1, null); x = ((int, int))(1, (t)=>t); x = ((int, int))null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (12,32): error CS1525: Invalid expression term ')' // x = ((int, int))(1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 32), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = ((int, int))(null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "((int, int))(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 13), // (9,13): error CS0030: Cannot convert type '(int, int, int)' to '(int, int)' // x = ((int, int))(1, 1, 1); Diagnostic(ErrorCode.ERR_NoExplicitConv, "((int, int))(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 13), // (10,29): error CS0030: Cannot convert type 'string' to 'int' // x = ((int, int))(1, "string"); Diagnostic(ErrorCode.ERR_NoExplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 29), // (11,32): error CS0103: The name 'garbage' does not exist in the current context // x = ((int, int))(1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 32), // (13,26): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((int, int))(null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 26), // (13,32): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((int, int))(null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 32), // (14,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((int, int))(1, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 29), // (15,29): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = ((int, int))(1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 29), // (16,13): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = ((int, int))null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "((int, int))null").WithArguments("(int, int)").WithLocation(16, 13) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail02() { var source = @" class C { static void Main() { System.ValueTuple<int, int> x; x = (null, null, null); x = (1, 1, 1); x = (1, ""string""); x = (1, 1, garbage); x = (1, 1, ); x = (null, null); x = (1, null); x = (1, (t)=>t); x = null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (12,20): error CS1525: Invalid expression term ')' // x = (1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 20), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = (null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 13), // (9,13): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(int, int)' // x = (1, 1, 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 13), // (10,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // x = (1, "string"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 17), // (11,20): error CS0103: The name 'garbage' does not exist in the current context // x = (1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 20), // (13,14): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 14), // (13,20): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (null, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 20), // (14,17): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = (1, null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 17), // (15,17): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 17), // (16,13): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(int, int)").WithLocation(16, 13) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail03() { var source = @" class C { static void Main() { (string, string) x; x = (null, null, null); x = (1, 1, 1); x = (1, ""string""); x = (1, 1, garbage); x = (1, 1, ); x = (null, null); x = (1, null); x = (1, (t)=>t); x = null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (12,20): error CS1525: Invalid expression term ')' // x = (1, 1, ); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 20), // (8,13): error CS8129: Tuple with 3 elements cannot be converted to type '(string, string)'. // x = (null, null, null); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(string, string)").WithLocation(8, 13), // (9,13): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(string, string)' // x = (1, 1, 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(string, string)").WithLocation(9, 13), // (10,14): error CS0029: Cannot implicitly convert type 'int' to 'string' // x = (1, "string"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(10, 14), // (11,20): error CS0103: The name 'garbage' does not exist in the current context // x = (1, 1, garbage); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 20), // (14,14): error CS0029: Cannot implicitly convert type 'int' to 'string' // x = (1, null); Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(14, 14), // (15,14): error CS0029: Cannot implicitly convert type 'int' to 'string' // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(15, 14), // (15,17): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type // x = (1, (t)=>t); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "string").WithLocation(15, 17), // (16,13): error CS0037: Cannot convert null to '(string, string)' because it is a non-nullable value type // x = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(string, string)").WithLocation(16, 13) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail04() { var source = @" class C { static void Main() { ((int, int), int) x; x = ((null, null, null), 1); x = ((1, 1, 1), 1); x = ((1, ""string""), 1); x = ((1, 1, garbage), 1); x = ((1, 1, ), 1); x = ((null, null), 1); x = ((1, null), 1); x = ((1, (t)=>t), 1); x = (null, 1); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (12,21): error CS1525: Invalid expression term ')' // x = ((1, 1, ), 1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 21), // (8,14): error CS8129: Tuple with 3 elements cannot be converted to type '(int, int)'. // x = ((null, null, null), 1); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(null, null, null)").WithArguments("3", "(int, int)").WithLocation(8, 14), // (9,14): error CS0029: Cannot implicitly convert type '(int, int, int)' to '(int, int)' // x = ((1, 1, 1), 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 1, 1)").WithArguments("(int, int, int)", "(int, int)").WithLocation(9, 14), // (10,18): error CS0029: Cannot implicitly convert type 'string' to 'int' // x = ((1, "string"), 1); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""string""").WithArguments("string", "int").WithLocation(10, 18), // (11,21): error CS0103: The name 'garbage' does not exist in the current context // x = ((1, 1, garbage), 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "garbage").WithArguments("garbage").WithLocation(11, 21), // (13,15): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((null, null), 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 15), // (13,21): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((null, null), 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(13, 21), // (14,18): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // x = ((1, null), 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(14, 18), // (15,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // x = ((1, (t)=>t), 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(t)=>t").WithArguments("lambda expression", "int").WithLocation(15, 18), // (16,14): error CS0037: Cannot convert null to '(int, int)' because it is a non-nullable value type // x = (null, 1); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("(int, int)").WithLocation(16, 14) ); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail05() { var source = @" class C { static void Main() { (System.ValueTuple<int, int> x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10) x; x = (0,1,2,3,4,5,6,7,8,9,10); x = ((0, 0.0),1,2,3,4,5,6,7,8,9,10); x = ((0, 0),1,2,3,4,5,6,7,8,9,10,11); x = ((0, 0),1,2,3,4,5,6,7,8); x = ((0, 0),1,2,3,4,5,6,7,8,9.1,10); x = ((0, 0),1,2,3,4,5,6,7,8,; x = ((0, 0),1,2,3,4,5,6,7,8,9 x = ((0, 0),1,2,3,4,oops,6,7,oopsss,9,10); x = ((0, 0),1,2,3,4,5,6,7,8,9); x = ((0, 0),1,2,3,4,5,6,7,8,(1,1,1), 10); } } " + trivial2uple + trivialRemainingTuples + tupleattributes_cs; //intentionally not including 3-tuple for usesite errors CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (13,37): error CS1525: Invalid expression term ';' // x = ((0, 0),1,2,3,4,5,6,7,8,; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 37), // (13,37): error CS1026: ) expected // x = ((0, 0),1,2,3,4,5,6,7,8,; Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(13, 37), // (14,38): error CS1026: ) expected // x = ((0, 0),1,2,3,4,5,6,7,8,9 Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(14, 38), // (14,38): error CS1002: ; expected // x = ((0, 0),1,2,3,4,5,6,7,8,9 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(14, 38), // (8,14): error CS0029: Cannot implicitly convert type 'int' to '(int, int)' // x = (0,1,2,3,4,5,6,7,8,9,10); Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "(int, int)").WithLocation(8, 14), // (9,18): error CS0029: Cannot implicitly convert type 'double' to 'int' // x = ((0, 0.0),1,2,3,4,5,6,7,8,9,10); Diagnostic(ErrorCode.ERR_NoImplicitConv, "0.0").WithArguments("double", "int").WithLocation(9, 18), // (10,13): error CS0029: Cannot implicitly convert type '((int, int), int, int, int, int, int, int, int, int, int, int, int)' to '((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)' // x = ((0, 0),1,2,3,4,5,6,7,8,9,10,11); Diagnostic(ErrorCode.ERR_NoImplicitConv, "((0, 0),1,2,3,4,5,6,7,8,9,10,11)").WithArguments("((int, int), int, int, int, int, int, int, int, int, int, int, int)", "((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)").WithLocation(10, 13), // (11,13): error CS0029: Cannot implicitly convert type '((int, int), int, int, int, int, int, int, int, int)' to '((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)' // x = ((0, 0),1,2,3,4,5,6,7,8); Diagnostic(ErrorCode.ERR_NoImplicitConv, "((0, 0),1,2,3,4,5,6,7,8)").WithArguments("((int, int), int, int, int, int, int, int, int, int)", "((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)").WithLocation(11, 13), // (12,37): error CS0029: Cannot implicitly convert type 'double' to 'int' // x = ((0, 0),1,2,3,4,5,6,7,8,9.1,10); Diagnostic(ErrorCode.ERR_NoImplicitConv, "9.1").WithArguments("double", "int").WithLocation(12, 37), // (13,13): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,; Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "((0, 0),1,2,3,4,5,6,7,8,").WithArguments("System.ValueTuple`3").WithLocation(13, 13), // (14,13): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,9 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, @"((0, 0),1,2,3,4,5,6,7,8,9 ").WithArguments("System.ValueTuple`3").WithLocation(14, 13), // (15,29): error CS0103: The name 'oops' does not exist in the current context // x = ((0, 0),1,2,3,4,oops,6,7,oopsss,9,10); Diagnostic(ErrorCode.ERR_NameNotInContext, "oops").WithArguments("oops").WithLocation(15, 29), // (15,38): error CS0103: The name 'oopsss' does not exist in the current context // x = ((0, 0),1,2,3,4,oops,6,7,oopsss,9,10); Diagnostic(ErrorCode.ERR_NameNotInContext, "oopsss").WithArguments("oopsss").WithLocation(15, 38), // (17,13): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "((0, 0),1,2,3,4,5,6,7,8,9)").WithArguments("System.ValueTuple`3").WithLocation(17, 13), // (17,13): error CS0029: Cannot implicitly convert type 'System.ValueTuple<(int, int), int, int, int, int, int, int, (int, int, int)>' to '((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)' // x = ((0, 0),1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_NoImplicitConv, "((0, 0),1,2,3,4,5,6,7,8,9)").WithArguments("System.ValueTuple<(int, int), int, int, int, int, int, int, (int, int, int)>", "((int, int) x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10)").WithLocation(17, 13), // (18,37): error CS8179: Predefined type 'System.ValueTuple`3' is not defined or imported // x = ((0, 0),1,2,3,4,5,6,7,8,(1,1,1), 10); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1,1,1)").WithArguments("System.ValueTuple`3").WithLocation(18, 37)); } [Fact] [WorkItem(11875, "https://github.com/dotnet/roslyn/issues/11875")] public void TupleImplicitConversionFail06() { var source = @" using System; class C { static void Main() { Func<string> l = ()=>1; // reference (string, Func<string>) x = (null, ()=>1); // actual error, should be the same as above. Func<(string, string)> l1 = ()=>(null, 1.1); // reference (string, Func<(string, string)>) x1 = (null, ()=>(null, 1.1)); // actual error, should be the same as above. } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (8,30): error CS0029: Cannot implicitly convert type 'int' to 'string' // Func<string> l = ()=>1; // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(8, 30), // (8,30): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<string> l = ()=>1; // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(8, 30), // (10,47): error CS0029: Cannot implicitly convert type 'int' to 'string' // (string, Func<string>) x = (null, ()=>1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(10, 47), // (10,47): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<string>) x = (null, ()=>1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(10, 47), // (12,48): error CS0029: Cannot implicitly convert type 'double' to 'string' // Func<(string, string)> l1 = ()=>(null, 1.1); // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(12, 48), // (12,41): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<(string, string)> l1 = ()=>(null, 1.1); // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(12, 41), // (14,65): error CS0029: Cannot implicitly convert type 'double' to 'string' // (string, Func<(string, string)>) x1 = (null, ()=>(null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(14, 65), // (14,58): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<(string, string)>) x1 = (null, ()=>(null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(14, 58) ); } [Fact] public void TupleExplicitConversionFail06() { var source = @" using System; class C { static void Main() { Func<string> l = (Func<string>)(()=>1); // reference (string, Func<string>) x = ((string, Func<string>))(null, () => 1); // actual error, should be the same as above. Func<(string, string)> l1 = (Func<(string, string)>)(()=>(null, 1.1)); // reference (string, Func<(string, string)>) x1 = ((string, Func<(string, string)>))(null, () => (null, 1.1)); // actual error, should be the same as above. } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (8,45): error CS0029: Cannot implicitly convert type 'int' to 'string' // Func<string> l = (Func<string>)(()=>1); // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(8, 45), // (8,45): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<string> l = (Func<string>)(()=>1); // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(8, 45), // (10,73): error CS0029: Cannot implicitly convert type 'int' to 'string' // (string, Func<string>) x = ((string, Func<string>))(null, () => 1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(10, 73), // (10,73): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<string>) x = ((string, Func<string>))(null, () => 1); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1").WithArguments("lambda expression").WithLocation(10, 73), // (12,73): error CS0029: Cannot implicitly convert type 'double' to 'string' // Func<(string, string)> l1 = (Func<(string, string)>)(()=>(null, 1.1)); // reference Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(12, 73), // (12,66): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<(string, string)> l1 = (Func<(string, string)>)(()=>(null, 1.1)); // reference Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(12, 66), // (14,101): error CS0029: Cannot implicitly convert type 'double' to 'string' // (string, Func<(string, string)>) x1 = ((string, Func<(string, string)>))(null, () => (null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_NoImplicitConv, "1.1").WithArguments("double", "string").WithLocation(14, 101), // (14,94): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // (string, Func<(string, string)>) x1 = ((string, Func<(string, string)>))(null, () => (null, 1.1)); // actual error, should be the same as above. Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "(null, 1.1)").WithArguments("lambda expression").WithLocation(14, 94) ); } [Fact] public void TupleExplicitNullableConversionWithTypelessTuple() { var source = @" class C { static void Main() { var x = ((int, string)?) (1, null); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(1, )"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declaration = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().First(); var value = declaration.Declaration.Variables.First().Initializer.Value; Assert.Equal("((int, string)?) (1, null)", value.ToString()); var castConversion = model.GetConversion(value); Assert.Equal(ConversionKind.Identity, castConversion.Kind); var tuple = ((CastExpressionSyntax)value).Expression; Assert.Equal("(1, null)", tuple.ToString()); var tupleConversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.ExplicitNullable, tupleConversion.Kind); Assert.Equal(1, tupleConversion.UnderlyingConversions.Length); Assert.Equal(ConversionKind.ExplicitTupleLiteral, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void TupleImplicitNullableConversionWithTypelessTuple() { var source = @" class C { static void Main() { (int, string)? x = (1, null); System.Console.Write(x); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(1, )"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declaration = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().First(); var value = declaration.Declaration.Variables.First().Initializer.Value; Assert.Equal("(1, null)", value.ToString()); var tupleConversion = model.GetConversion(value); Assert.Equal(ConversionKind.ImplicitNullable, tupleConversion.Kind); Assert.Equal(1, tupleConversion.UnderlyingConversions.Length); Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.UnderlyingConversions[0].Kind); } [Fact] public void TupleImplicitNullableAndCustomConversionsWithTypelessTuple() { var source = @" struct C { static void Main() { C? x = (1, null); System.Console.Write(x); var x2 = (C)(2, null); System.Console.Write(x2); var x3 = (C?)(3, null); System.Console.Write(x3); } public static implicit operator C((int, string) x) { return new C(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "CCC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuples = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); var tuple1 = tuples.ElementAt(0); Assert.Equal("(1, null)", tuple1.ToString()); Assert.Null(model.GetTypeInfo(tuple1).Type); Assert.Equal("C?", model.GetTypeInfo(tuple1).ConvertedType.ToTestDisplayString()); var conversion1 = model.GetConversion(tuple1); Assert.Equal(ConversionKind.ImplicitUserDefined, conversion1.Kind); Assert.True(conversion1.UnderlyingConversions.IsDefault); var tuple2 = tuples.ElementAt(1); Assert.Equal("(2, null)", tuple2.ToString()); Assert.Null(model.GetTypeInfo(tuple2).Type); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple2).ConvertedType.ToTestDisplayString()); var conversion2 = model.GetConversion(tuple2); Assert.Equal(ConversionKind.ImplicitTupleLiteral, conversion2.Kind); Assert.False(conversion2.UnderlyingConversions.IsDefault); var tuple3 = tuples.ElementAt(2); Assert.Equal("(3, null)", tuple3.ToString()); Assert.Null(model.GetTypeInfo(tuple3).Type); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple3).ConvertedType.ToTestDisplayString()); var conversion3 = model.GetConversion(tuple3); Assert.Equal(ConversionKind.ImplicitTupleLiteral, conversion3.Kind); Assert.False(conversion3.UnderlyingConversions.IsDefault); } [Fact] public void TupleImplicitNullableAndCustomConversionsWithTypelessTupleInAsOperator() { var source = @" struct C { static void Main() { var x4 = (1, null) as C; System.Console.Write(x4); var x5 = (2, null) as C?; System.Console.Write(x5); } public static implicit operator C((int, string) x) { return new C(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (6,18): error CS8305: The first operand of an 'as' operator may not be a tuple literal without a natural type. // var x4 = (1, null) as C; Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(1, null) as C").WithLocation(6, 18), // (8,18): error CS8305: The first operand of an 'as' operator may not be a tuple literal without a natural type. // var x5 = (2, null) as C?; Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(2, null) as C?").WithLocation(8, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuples = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); verifyTuple("(1, null)", tuples.ElementAt(0)); verifyTuple("(2, null)", tuples.ElementAt(1)); void verifyTuple(string expected, TupleExpressionSyntax tuple) { Assert.Equal(expected, tuple.ToString()); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Null(model.GetTypeInfo(tuple).ConvertedType); var conversion = model.GetConversion(tuple); Assert.Equal(ConversionKind.Identity, conversion.Kind); Assert.True(conversion.UnderlyingConversions.IsDefault); } } [Fact] public void TupleTargetTypeLambda() { var source = @" using System; class C { static void Test(Func<Func<(short, short)>> d) { Console.WriteLine(""short""); } static void Test(Func<Func<(byte, byte)>> d) { Console.WriteLine(""byte""); } static void Main() { // this works because of identity conversion Test( ()=>()=>((byte, byte))(1,1)) ; // this works because of the betterness of the targets Test(()=>()=>(1,1)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" byte byte "); } [Fact] public void TupleTargetTypeLambda1() { var source = @" using System; class C { static void Test(Func<(Func<short>, int)> d) { Console.WriteLine(""short""); } static void Test(Func<(Func<byte>, int)> d) { Console.WriteLine(""byte""); } static void Main() { // this works Test(()=>(()=>(short)1, 1)); // this works Test(()=>(()=>(byte)1, 1)); // this does not Test(()=>(()=>1, 1)); } } "; CreateCompilation(source).VerifyDiagnostics( // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Test(Func<(Func<short>, int)>)' and 'C.Test(Func<(Func<byte>, int)>)' // Test(()=>(()=>1, 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("C.Test(System.Func<(System.Func<short>, int)>)", "C.Test(System.Func<(System.Func<byte>, int)>)").WithLocation(26, 9) ); } [Fact] public void TargetTypingOverload01() { var source = @" using System; class C { static void Main() { Test((null, null)); Test((1, 1)); Test((()=>7, ()=>8), 2); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x, T y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" second first third 7 "); } [Fact] public void TargetTypingOverload02() { var source = @" using System; class C { static void Main() { Test((()=>7, ()=>8)); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" third 7 "); } [Fact] public void TargetTypingNullable01() { var source = @" using System; class C { static void Main() { var x = M1(); Test(x); } static (int a, double b)? M1() { return (1, 2); } static void Test<T>(T arg) { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(arg); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Nullable`1[System.ValueTuple`2[System.Int32,System.Double]] (1, 2) "); } [Fact] public void TargetTypingOverload01Long() { var source = @" using System; class C { static void Main() { Test((null, null, null, null, null, null, null, null, null, null)); Test((1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); Test((()=>7, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8, ()=>8), 2); } static void Test<T>((T, T, T, T, T, T, T, T, T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object, object, object, object, object, object, object, object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>, Func<T>) x, T y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, expectedOutput: @" second first third 7 "); } [Fact] public void TargetTypingNullable02() { var source = @" using System; class C { static void Main() { var x = M1(); Test(x); } static (int a, string b)? M1() { return (1, null); } static void Test<T>(T arg) { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(arg); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]] (1, ) "); } [Fact] public void TargetTypingNullable02Long() { var source = @" class C { static void Main() { var x = M1(); System.Console.WriteLine(x?.a); System.Console.WriteLine(x?.a8); Test(x); } static (int a, string b, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8)? M1() { return (1, null, 1, 2, 3, 4, 5, 6, 7, 8); } static void Test<T>(T arg) { System.Console.WriteLine(arg); } } "; var comp = CompileAndVerify(source, expectedOutput: @"1 8 (1, , 1, 2, 3, 4, 5, 6, 7, 8) "); } [Fact] public void TargetTypingNullableOverload() { var source = @" class C { static void Main() { Test((null, null, null, null, null, null, null, null, null, null)); Test((""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"", ""a"")); Test((1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); } static void Test((string, string, string, string, string, string, string, string, string, string) x) { System.Console.WriteLine(""first""); } static void Test((string, string, string, string, string, string, string, string, string, string)? x) { System.Console.WriteLine(""second""); } static void Test((int, int, int, int, int, int, int, int, int, int)? x) { System.Console.WriteLine(""third""); } static void Test((int, int, int, int, int, int, int, int, int, int) x) { System.Console.WriteLine(""fourth""); } } "; var comp = CompileAndVerify(source, expectedOutput: @" first first fourth "); } [Fact] public void TupleConversion01() { var source = @" class C { static void Main() { // error must mention (long c, long d) (int a, int b) x1 = ((long c, long d))(e: 1, f:2); // error must mention (int c, long d) (short a, short b) x2 = ((int c, int d))(e: 1, f:2); // error must mention (int e, string f) (int a, int b) x3 = ((long c, long d))(e: 1, f:""qq""); } } " + trivial2uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (7,48): warning CS8123: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(long c, long d)'. // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 1").WithArguments("e", "(long c, long d)").WithLocation(7, 48), // (7,54): warning CS8123: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(long c, long d)'. // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f:2").WithArguments("f", "(long c, long d)").WithLocation(7, 54), // (7,29): error CS0266: Cannot implicitly convert type '(long c, long d)' to '(int a, int b)'. An explicit conversion exists (are you missing a cast?) // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "((long c, long d))(e: 1, f:2)").WithArguments("(long c, long d)", "(int a, int b)").WithLocation(7, 29), // (9,50): warning CS8123: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(int c, int d)'. // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 1").WithArguments("e", "(int c, int d)").WithLocation(9, 50), // (9,56): warning CS8123: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(int c, int d)'. // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f:2").WithArguments("f", "(int c, int d)").WithLocation(9, 56), // (9,33): error CS0266: Cannot implicitly convert type '(int c, int d)' to '(short a, short b)'. An explicit conversion exists (are you missing a cast?) // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "((int c, int d))(e: 1, f:2)").WithArguments("(int c, int d)", "(short a, short b)").WithLocation(9, 33), // (12,56): error CS0030: Cannot convert type 'string' to 'long' // (int a, int b) x3 = ((long c, long d))(e: 1, f:"qq"); Diagnostic(ErrorCode.ERR_NoExplicitConv, @"""qq""").WithArguments("string", "long").WithLocation(12, 56), // (7,24): warning CS0219: The variable 'x1' is assigned but its value is never used // (int a, int b) x1 = ((long c, long d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(7, 24), // (9,28): warning CS0219: The variable 'x2' is assigned but its value is never used // (short a, short b) x2 = ((int c, int d))(e: 1, f:2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(9, 28) ); } [Fact] [WorkItem(11288, "https://github.com/dotnet/roslyn/issues/11288")] public void TupleConversion02() { var source = @" class C { static void Main() { (int a, int b) x4 = ((long c, long d))(1, null, 2); } } " + trivial2uple + trivial3uple + tupleattributes_cs; CreateCompilation(source).VerifyDiagnostics( // (6,29): error CS8135: Tuple with 3 elements cannot be converted to type '(long c, long d)'. // (int a, int b) x4 = ((long c, long d))(1, null, 2); Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "((long c, long d))(1, null, 2)").WithArguments("3", "(long c, long d)").WithLocation(6, 29) ); } [Fact] public void TupleConvertedType01() { var source = @" class C { static void Main() { (short a, string b)? x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType01insource() { var source = @" class C { static void Main() { // explicit conversion exists, cast in the code picks that. (short a, string b)? x = ((short c, string d)?)(e: 1, f: ""hello""); short? y = (short?)11; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var l11 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(2); Assert.Equal(@"11", l11.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(l11)); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d)?)(e: 1, f: ""hello"") Assert.Equal("(System.Int16 c, System.String d)?", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType01insourceImplicit() { var source = @" class C { static void Main() { (short a, string b)? x =(1, ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""hello"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); CompileAndVerify(comp); } [Fact] public void TupleConvertedType02() { var source = @" class C { static void Main() { (short a, string b)? x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType02insource00() { var source = @" class C { static void Main() { (short a, string b)? x = ((short c, string d))(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: ""hello"") Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node.Parent).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType02insource01() { var source = @" class C { static void Main() { var x = (e: 1, f: ""hello""); (object a, string b) x1 = ((long c, string d))(x); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<ParenthesizedExpressionSyntax>().Single().Parent; Assert.Equal(@"((long c, string d))(x)", node.ToString()); Assert.Equal("(System.Int64 c, System.String d)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Object a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(node).Kind); node = nodes.OfType<ParenthesizedExpressionSyntax>().Single(); Assert.Equal(@"(x)", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); } [Fact] public void TupleConvertedType02insource02() { var source = @" class C { static void Main() { var x = (e: 1, f: ""hello""); (object a, string b)? x1 = ((long c, string d))(x); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<ParenthesizedExpressionSyntax>().Single().Parent; Assert.Equal(@"((long c, string d))(x)", node.ToString()); Assert.Equal("(System.Int64 c, System.String d)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Object a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); node = nodes.OfType<ParenthesizedExpressionSyntax>().Single(); Assert.Equal(@"(x)", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); } [Fact] public void TupleConvertedType03() { var source = @" class C { static void Main() { (int a, string b)? x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType03insource() { var source = @" class C { static void Main() { (int a, string b)? x = ((int c, string d)?)(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 c, System.String d)?", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((int c, string d)?)(e: 1, f: ""hello"") Assert.Equal("(System.Int32 c, System.String d)?", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType04() { var source = @" class C { static void Main() { (int a, string b)? x = ((int c, string d))(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); // semantic model returns topmost conversion from the sequence of conversions for // ((int c, string d))(e: 1, f: ""hello"") Assert.Equal("(System.Int32 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)?", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNullable, model.GetConversion(node.Parent).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b)? x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType05() { var source = @" class C { static void Main() { (int a, string b) x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType05insource() { var source = @" class C { static void Main() { (int a, string b) x = ((int c, string d))(e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int32 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType06() { var source = @" class C { static void Main() { (short a, string b) x = (e: 1, f: ""hello""); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedType06insource() { var source = @" class C { static void Main() { (short a, string b) x = ((short c, string d))(e: 1, f: ""hello""); short y = (short)11; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var l11 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(2); Assert.Equal(@"11", l11.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(l11)); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: ""hello"")", node.ToString()); Assert.Equal("(System.Int32 e, System.String f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("System.String", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: ""hello"") Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedTypeNull01() { var source = @" class C { static void Main() { (short a, string b) x = (e: 1, f: null); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: null)", node.ToString()); Assert.Null(model.GetTypeInfo(node).Type); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedTypeNull01insource() { var source = @" class C { static void Main() { (short a, string b) x = ((short c, string d))(e: 1, f: null); string y = (string)null; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var lnull = nodes.OfType<LiteralExpressionSyntax>().ElementAt(2); Assert.Equal(@"null", lnull.ToString()); Assert.Null(model.GetTypeInfo(lnull).Type); Assert.Null(model.GetTypeInfo(lnull).ConvertedType); Assert.Equal(Conversion.Identity, model.GetConversion(lnull)); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: null)", node.ToString()); Assert.Null(model.GetTypeInfo(node).Type); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: null) Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); } [Fact] public void TupleConvertedTypeUDC01() { var source = @" class C { static void Main() { (short a, string b) x = (e: 1, f: new C1(""qq"")); System.Console.WriteLine(x.ToString()); } class C1 { private string s; public C1(string arg) { s = arg + 1; } public static implicit operator string (C1 arg) { return arg.s; } } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: new C1(""qq""))", node.ToString()); Assert.Equal("(System.Int32 e, C.C1 f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(node).Kind); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "{1, qq1}"); } [Fact] public void TupleConvertedTypeUDC01insource() { var source = @" class C { static void Main() { (short a, string b) x = ((short c, string d))(e: 1, f: new C1(""qq"")); System.Console.WriteLine(x.ToString()); } class C1 { private string s; public C1(string arg) { s = arg + 1; } public static implicit operator string (C1 arg) { return arg.s; } } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(e: 1, f: new C1(""qq""))", node.ToString()); Assert.Equal("(System.Int32 e, C.C1 f)", model.GetTypeInfo(node).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(node).Kind); ExpressionSyntax element; element = node.Arguments[0].Expression; Assert.Equal("System.Int32", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(element).Kind); element = node.Arguments[1].Expression; Assert.Equal("C.C1", model.GetTypeInfo(element).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(element).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitUserDefined, model.GetConversion(element).Kind); // semantic model returns topmost conversion from the sequence of conversions for // ((short c, string d))(e: 1, f: null) Assert.Equal("(System.Int16 c, System.String d)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()); Assert.Equal("(System.Int16 a, System.String b)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(node.Parent)); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("(System.Int16 a, System.String b) x", model.GetDeclaredSymbol(x).ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "{1, qq1}"); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC02() { var source = @" class C { static void Main() { C1 x = (1, ""qq""); System.Console.WriteLine(x.ToString()); } class C1 { private (byte, string) val; private C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { return new C1(arg); } public override string ToString() { return val.ToString(); } } } " + trivial2uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: "{1, qq}"); } [Fact] public void TupleConvertedTypeUDC03() { var source = @" class C { static void Main() { C1 x = (""1"", ""qq""); System.Console.WriteLine(x.ToString()); } class C1 { private (byte, string) val; private C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { return new C1(arg); } public override string ToString() { return val.ToString(); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS0029: Cannot implicitly convert type '(string, string)' to 'C.C1' // C1 x = ("1", "qq"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(""1"", ""qq"")").WithArguments("(string, string)", "C.C1").WithLocation(6, 16) ); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(""1"", ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.String, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, model.GetConversion(node)); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC04() { var source = @" public class C { static void Main() { C1 x = (1, ""qq""); System.Console.WriteLine(x.ToString()); } public class C1 { private (byte, string) val; public C1((byte, string) arg) { val = arg; } public override string ToString() { return val.ToString(); } } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator C.C1 ((T1, T2) arg) { return new C.C1(((byte)(int)(object)arg.Item1, (string)(object)arg.Item2)); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(1, ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: "{1, qq}"); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC05() { var source = @" public class C { static void Main() { C1 x = (1, ""qq""); System.Console.WriteLine(x.ToString()); } public class C1 { private (byte, string) val; public C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { System.Console.WriteLine(""C1""); return new C1(arg); } public override string ToString() { return val.ToString(); } } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator C.C1 ((T1, T2) arg) { System.Console.WriteLine(""VT""); return new C.C1(((byte)(int)(object)arg.Item1, (string)(object)arg.Item2)); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(1, ""qq"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: @"VT {1, qq}"); } [Fact] [WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")] public void TupleConvertedTypeUDC06() { var source = @" public class C { static void Main() { C1 x = (1, null); System.Console.WriteLine(x.ToString()); } public class C1 { private (byte, string) val; public C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { System.Console.WriteLine(""C1""); return new C1(arg); } public override string ToString() { return val.ToString(); } } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator C.C1 ((T1, T2) arg) { System.Console.WriteLine(""VT""); return new C.C1(((byte)(int)(object)arg.Item1, (string)(object)arg.Item2)); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().First(); Assert.Equal(@"(1, null)", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Null(typeInfo.Type); Assert.Equal("C.C1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitUserDefined, model.GetConversion(node).Kind); CompileAndVerify(comp, expectedOutput: @"C1 {1, }"); } [Fact] public void TupleConvertedTypeUDC07() { var source = @" class C { static void Main() { C1 x = M1(); System.Console.WriteLine(x.ToString()); } static (int, string) M1() { return (1, ""qq""); } class C1 { private (byte, string) val; private C1((byte, string) arg) { val = arg; } public static implicit operator C1 ((byte, string) arg) { return new C1(arg); } } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS0029: Cannot implicitly convert type '(int, string)' to 'C.C1' // C1 x = M1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "M1()").WithArguments("(int, string)", "C.C1").WithLocation(6, 16) ); } [Fact] public void Inference01() { var source = @" using System; class C { static void Main() { Test((null, null)); Test((1, 1)); Test((()=>7, ()=>8), 2); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x, T y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" second first third 7 "); } [Fact] public void Inference02() { var source = @" using System; class C { static void Main() { Test((()=>7, ()=>8)); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<T>, Func<T>) x) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" third 7 "); } [Fact] public void Inference02_WithoutTuple() { var source = @" using System; class C { static void Main() { Test(()=>7, ()=>8); } static void Test<T>(T x, T y) { System.Console.WriteLine(""first""); } static void Test(object x, object y) { System.Console.WriteLine(""second""); } static void Test<T>(Func<T> x, Func<T> y) { System.Console.WriteLine(""third""); System.Console.WriteLine(x().ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" third 7 "); } [Fact] public void Inference03() { var source = @" using System; class C { static void Main() { Test(((x)=>x, (x)=>x)); } static void Test<T>((T, T) x) { System.Console.WriteLine(""first""); } static void Test((object, object) x) { System.Console.WriteLine(""second""); } static void Test<T>((Func<int, T>, Func<T, T>) x) { System.Console.WriteLine(""third""); System.Console.WriteLine(x.Item1(5).ToString()); } } "; var comp = CompileAndVerify(source, expectedOutput: @" third 5 "); } [Fact] public void Inference04() { var source = @" using System; class C { static void Main() { Test( (x)=>x.y ); Test( (x)=>x.bob ); } static void Test<T>( Func<(byte x, byte y), T> x) { System.Console.WriteLine(""first""); System.Console.WriteLine(x((2,3)).ToString()); } static void Test<T>( Func<(int alice, int bob), T> x) { System.Console.WriteLine(""second""); System.Console.WriteLine(x((4,5)).ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first 3 second 5 "); } [Fact] public void Inference05() { var source = @" using System; class C { static void Main() { Test( ((x)=>x.x, (x)=>x.Item2) ); Test( ((x)=>x.bob, (x)=>x.Item1) ); } static void Test<T>( (Func<(byte x, byte y), T> f1, Func<(int, int), T> f2) x) { System.Console.WriteLine(""first""); System.Console.WriteLine(x.f1((2,3)).ToString()); System.Console.WriteLine(x.f2((2,3)).ToString()); } static void Test<T>( (Func<(int alice, int bob), T> f1, Func<(int, int), T> f2) x) { System.Console.WriteLine(""second""); System.Console.WriteLine(x.f1((4,5)).ToString()); System.Console.WriteLine(x.f2((4,5)).ToString()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first 2 3 second 5 4 "); } [WorkItem(10801, "https://github.com/dotnet/roslyn/issues/10801")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/10801")] public void Inference06() { var source = @" using System; class Program { static void Main(string[] args) { M1((() => ""qq"", null)); } static void M1((Func<object> f, object o) a) { System.Console.WriteLine(1); } static void M1((Func<string> f, object o) a) { System.Console.WriteLine(2); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" 2 "); } [Fact] public void Inference07() { var source = @" using System; class C { static void Main() { Test((x) => (x, x), (t) => 1); Test1((x) => (x, x), (t) => 1); Test2((a: 1, b: 2), (t) => (t.a, t.b)); } static void Test<U>(Func<int, ValueTuple<U, U>> f1, Func<ValueTuple<U, U>, int> f2) { System.Console.WriteLine(f2(f1(1))); } static void Test1<U>(Func<int, (U, U)> f1, Func<(U, U), int> f2) { System.Console.WriteLine(f2(f1(1))); } static void Test2<U, T>(U f1, Func<U, (T x, T y)> f2) { System.Console.WriteLine(f2(f1).y); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" 1 1 2 "); } [Fact] public void Inference08() { var source = @" using System; class C { static void Main() { Test1((a: 1, b: 2), (c: 3, d: 4)); Test2((a: 1, b: 2), (c: 3, d: 4), t => t.Item2); Test2((a: 1, b: 2), (a: 3, b: 4), t => t.a); Test2((a: 1, b: 2), (c: 3, d: 4), t => t.a); } static void Test1<T>(T x, T y) { System.Console.WriteLine(""test1""); System.Console.WriteLine(x); } static void Test2<T>(T x, T y, Func<T, int> f) { System.Console.WriteLine(""test2_1""); System.Console.WriteLine(f(x)); } static void Test2<T>(T x, object y, Func<T, int> f) { System.Console.WriteLine(""test2_2""); System.Console.WriteLine(f(x)); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" test1 {1, 2} test2_1 2 test2_1 1 test2_2 1 "); } [Fact] public void Inference08t() { var source = @" using System; class C { static void Main() { var ab = (a: 1, b: 2); var cd = (c: 3, d: 4); Test1(ab, cd); Test2(ab, cd, t => t.Item2); Test2(ab, ab, t => t.a); Test2(ab, cd, t => t.a); } static void Test1<T>(T x, T y) { System.Console.WriteLine(""test1""); System.Console.WriteLine(x); } static void Test2<T>(T x, T y, Func<T, int> f) { System.Console.WriteLine(""test2_1""); System.Console.WriteLine(f(x)); } static void Test2<T>(T x, object y, Func<T, int> f) { System.Console.WriteLine(""test2_2""); System.Console.WriteLine(f(x)); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" test1 {1, 2} test2_1 2 test2_1 1 test2_2 1 "); } [Fact] public void Inference09() { var source = @" using System; class C { static void Main() { // byval tuple, as a whole, sets a lower bound Test1((a: 1, b: 2), (ValueType)1); } static void Test1<T>(T x, T y) { System.Console.WriteLine(typeof(T)); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" System.ValueType "); } [Fact] public void Inference10() { var source = @" using System; class C { static void Main() { // byref tuple, as a whole, sets an exact bound var t = (a: 1, b: 2); Test1(ref t, (ValueType)1); } static void Test1<T>(ref T x, T y) { System.Console.WriteLine(typeof(T)); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.Test1<T>(ref T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1(ref t, (ValueType)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T>(ref T, T)").WithLocation(10, 9) ); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11() { var source = @" class C { static void Main() { object o = null; dynamic d = null; var ab = (a: 1, b: o); var ad = (a: 1, d: d); var t1 = Test1(ref ab, ad); // exact bound and lower bound var t2 = Test2(ab, ref ad); // lower bound and exact bound var t3 = Test3(ref ab, ref ad); // two exact bounds var d1 = Test1(ref o, d); var d2 = Test2(o, ref d); var d3 = Test3(ref o, ref d); } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (17,18): error CS0411: The type arguments for method 'C.Test3<T>(ref T, ref T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var d3 = Test3(ref o, ref d); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test3").WithArguments("C.Test3<T>(ref T, ref T)").WithLocation(17, 18) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("(System.Int32 a, dynamic) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("(System.Int32 a, dynamic) t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("(System.Int32 a, dynamic) t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); var d1 = names.ElementAt(7); Assert.Equal("dynamic d1", model.GetDeclaredSymbol(d1).ToTestDisplayString()); var d2 = names.ElementAt(8); Assert.Equal("dynamic d2", model.GetDeclaredSymbol(d2).ToTestDisplayString()); var d3 = names.ElementAt(9); Assert.Equal("T d3", model.GetDeclaredSymbol(d3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11InNestedType() { var source = @" class C { static void Main() { object o = null; dynamic d = null; var ab = new [] { ((a: 1, b: o), c: 2) }; var ad = new [] { ((a: 1, d: d), c: 2) }; var t1 = Test1(ref ab, ad); // exact bound and lower bound var t2 = Test2(ab, ref ad); // lower bound and exact bound var t3 = Test3(ref ab, ref ad); // two exact bounds } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("((System.Int32 a, dynamic), System.Int32 c)[] t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("((System.Int32 a, dynamic), System.Int32 c)[] t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("((System.Int32 a, dynamic), System.Int32 c)[] t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithLongTuple() { var source = @" class C { static void Main() { object o = null; dynamic d = null; var ay = (a: o, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, y: 9); var az = (a: d, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, 8, z: 10); var t1 = Test1(ref ay, az); // exact bound and lower bound var t2 = Test2(ay, ref az); // lower bound and exact bound var t3 = Test3(ref ay, ref az); // two exact bounds } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("(dynamic a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32, System.Int32) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("(dynamic a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32, System.Int32) t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("(dynamic a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32, System.Int32) t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11OnlyDynamicMismatch() { var source = @" using System.Linq; class C { static void Main() { object o = null; dynamic d = null; var doc = (new [] { ((a: d, b: o), c: 2) }).ToList(); var odc = (new [] { ((a: o, b: d), c: 2) }).ToList(); var t1 = Test1(ref doc, odc); // exact bound and lower bound var t2 = Test2(doc, ref odc); // lower bound and exact bound var t3 = Test3(ref doc, ref odc); // two exact bounds } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; static T Test3<T>(ref T x, ref T y) => x; } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(4); Assert.Equal("System.Collections.Generic.List<((dynamic a, dynamic b), System.Int32 c)> t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(5); Assert.Equal("System.Collections.Generic.List<((dynamic a, dynamic b), System.Int32 c)> t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); var t3 = names.ElementAt(6); Assert.Equal("System.Collections.Generic.List<((dynamic a, dynamic b), System.Int32 c)> t3", model.GetDeclaredSymbol(t3).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithMoreThanTwoTypes() { var source = @" class C { static void Main() { var ab = (a: 1, b: 2); var cd = (c: 1, d: 2); var de = (d: 1, e: 2); var t1 = Test1(ref ab, cd, 1, de); } static T Test1<T>(ref T x, T y, T z, T w) => x; } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'C.Test1<T>(ref T, T, T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var t1 = Test1(ref ab, cd, 1, de); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T>(ref T, T, T, T)").WithLocation(10, 18) ); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithMoreThanTwoTypes2() { var source = @" class C { static void Main() { var abc = (a: 1, b: 2, c: 3); var abd = (a: 1, b: 2, d: 3); var byz = (b: 1, y: 2, c: 3); var t1 = Test1(ref abc, abd, byz); } static T Test1<T>(ref T x, T y, T z) => x; } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var t1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); Assert.Equal("(System.Int32, System.Int32, System.Int32) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); } [Fact] public void Inference11WithUpperBound() { var source = @" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Action<IEnumerable<(int a, dynamic b)>> x1 = null; Action<IEnumerable<(int a, object notB)>> x2 = null; var t1 = Test1(ref x1, x1, x2); // one exact bound and two upper bounds on T var t2 = Test2(x1, x2); // two upper bounds } public static T Test1<T>(ref Action<T> x, Action<T> y, Action<T> z) { return default(T); } public static T Test2<T>(Action<T> x, Action<T> y) { return default(T); } } "; var comp = CreateCompilationWithMscorlib40(source, references: s_valueTupleRefs); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var t1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(2); Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 a, dynamic)> t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 a, dynamic)> t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); } [WorkItem(10800, "https://github.com/dotnet/roslyn/issues/10800")] [Fact] public void Inference11WithImplicitConversion() { var source = @" class C { static void Main() { var ab = (a: 1, b: 2); var adL = (a: 1L, d: 2L); // `adL` is an exact bound, which `ab` can convert to, so the names on `ab` are ignored var t1 = Test1(ref adL, ab); var t2 = Test2(ab, ref adL); } static T Test1<T>(ref T x, T y) => x; static T Test2<T>(T x, ref T y) => x; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var names = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); var t1 = names.ElementAt(2); Assert.Equal("(System.Int64 a, System.Int64 d) t1", model.GetDeclaredSymbol(t1).ToTestDisplayString()); var t2 = names.ElementAt(3); Assert.Equal("(System.Int64 a, System.Int64 d) t2", model.GetDeclaredSymbol(t2).ToTestDisplayString()); } [Fact] public void Inference12() { var source = @" class C { static void Main() { // nested tuple literals set lower bounds Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (object)1)); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); } static void Test1<T, U>((T, U) x, (T, U) y) { System.Console.WriteLine(typeof(U)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] "); } [Fact] public void Inference13() { var source = @" class C { static void Main() { // nested tuple literals set lower bounds Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (object)1)); Test1(Nullable((a: 1, b: (a: 1, b: 2))), (a: 1, b: (object)1)); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); } static T? Nullable<T>(T x) where T : struct { return x; } static void Test1<T, U>((T, U)? x, (T, U) y) { System.Console.WriteLine(typeof(U)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Object System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] "); } [Fact] public void Inference13_Err() { var source = @" class C { static void Main() { Test1(Nullable((a: 1, b: (a: 1, b: 2))), (a: 1, b: (object)1)); Test1((a: 1, b: (a: 1, b: 2)), Nullable((a: 1, b: (object)1))); } static T? Nullable<T>(T x) where T : struct { return x; } static void Test1<T, U>((T, U) x, (T, U) y) { System.Console.WriteLine(typeof(U)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,15): error CS1503: Argument 1: cannot convert from '(int a, (int a, int b) b)?' to '(int, object)' // Test1(Nullable((a: 1, b: (a: 1, b: 2))), (a: 1, b: (object)1)); Diagnostic(ErrorCode.ERR_BadArgType, "Nullable((a: 1, b: (a: 1, b: 2)))").WithArguments("1", "(int a, (int a, int b) b)?", "(int, object)").WithLocation(6, 15), // (7,40): error CS1503: Argument 2: cannot convert from '(int a, object b)?' to '(int, (int a, int b))' // Test1((a: 1, b: (a: 1, b: 2)), Nullable((a: 1, b: (object)1))); Diagnostic(ErrorCode.ERR_BadArgType, "Nullable((a: 1, b: (object)1))").WithArguments("2", "(int a, object b)?", "(int, (int a, int b))").WithLocation(7, 40) ); } [Fact] public void Inference14() { var source = @" class C { static void Main() { // nested tuple literals set lower bounds Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); } static void Test1<T, U>((T, U)? x, (T, U?) y) where U: struct { System.Console.WriteLine(typeof(U)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0411: The type arguments for method 'C.Test1<T, U>((T, U)?, (T, U?))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (c: 1, d: 2))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T, U>((T, U)?, (T, U?))").WithLocation(7, 9), // (8,9): error CS0411: The type arguments for method 'C.Test1<T, U>((T, U)?, (T, U?))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (1, 2))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T, U>((T, U)?, (T, U?))").WithLocation(8, 9), // (9,9): error CS0411: The type arguments for method 'C.Test1<T, U>((T, U)?, (T, U?))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test1((a: 1, b: (a: 1, b: 2)), (a: 1, b: (a: 1, b: 2))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test1").WithArguments("C.Test1<T, U>((T, U)?, (T, U?))").WithLocation(9, 9) ); } [Fact] public void Inference15() { var source = @" class C { static void Main() { Test1((a: ""q"", b: null), (a: null, b: ""w""), (x) => x.z); } static void Test1<T, U>((T, U) x, (T, U) y, System.Func<(T x, U z), T> f) { System.Console.WriteLine(typeof(U)); System.Console.WriteLine(f(y)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.String w "); } [Fact] public void Inference16() { var source = @" class C { static void Main() { // tuples set lower bounds var x = (1,2,3); Test(x); var x1 = (1,2,(long)3); Test(x1); var x2 = (1,(object)2,(long)3); Test(x2); } static void Test<T>((T, T, T) x) { System.Console.WriteLine(typeof(T)); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" System.Int32 System.Int64 System.Object "); } [Fact] public void Constraints_01() { var source = @" namespace System { public struct ValueTuple<T1, T2> where T2 : class { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C { static void Main((int, int) p) { var t0 = (1, 2); (int, int) t1 = t0; } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (14,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // static void Main((int, int) p) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "p").WithArguments("(T1, T2)", "T2", "int").WithLocation(14, 33), // (16,22): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // var t0 = (1, 2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "2").WithArguments("(T1, T2)", "T2", "int").WithLocation(16, 22), // (17,15): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // (int, int) t1 = t0; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("(T1, T2)", "T2", "int").WithLocation(17, 15) ); } [Fact] [WorkItem(15399, "https://github.com/dotnet/roslyn/issues/15399")] public void Constraints_02() { var source = @" using System; class Program { unsafe void M((int, int*) p, ValueTuple<int, int*> q) { (int, int*) t0 = p; var t1 = (1, (int*)null); var t2 = new ValueTuple<int, int*>(1, null); ValueTuple<int, int*> t3 = t2; } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: s_valueTupleRefs, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (5,31): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M((int, int*) p, ValueTuple<int, int*> q) Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(5, 31), // (5,56): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M((int, int*) p, ValueTuple<int, int*> q) Diagnostic(ErrorCode.ERR_BadTypeArgument, "q").WithArguments("int*").WithLocation(5, 56), // (7,15): error CS0306: The type 'int*' may not be used as a type argument // (int, int*) t0 = p; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(7, 15), // (8,22): error CS0306: The type 'int*' may not be used as a type argument // var t1 = (1, (int*)null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "(int*)null").WithArguments("int*").WithLocation(8, 22), // (9,38): error CS0306: The type 'int*' may not be used as a type argument // var t2 = new ValueTuple<int, int*>(1, null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(9, 38), // (10,25): error CS0306: The type 'int*' may not be used as a type argument // ValueTuple<int, int*> t3 = t2; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(10, 25), // (8,13): warning CS0219: The variable 't1' is assigned but its value is never used // var t1 = (1, (int*)null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t1").WithArguments("t1").WithLocation(8, 13) ); } [Fact] public void Constraints_03() { var source = @" using System.Collections.Generic; namespace System { public struct ValueTuple<T1, T2> where T2 : class { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C<T> { List<(T, T)> field = null; (U, U) M<U>(U x) { var t0 = new C<int>(); var t1 = M(1); return default((U, U)); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (15,12): error CS0452: The type 'U' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // (U, U) M<U>(U x) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "M").WithArguments("(T1, T2)", "T2", "U").WithLocation(15, 12), // (14,18): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // List<(T, T)> field = null; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "field").WithArguments("(T1, T2)", "T2", "T").WithLocation(14, 18), // (19,28): error CS0452: The type 'U' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // return default((U, U)); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "U").WithArguments("(T1, T2)", "T2", "U").WithLocation(19, 28), // (14,18): warning CS0414: The field 'C<T>.field' is assigned but its value is never used // List<(T, T)> field = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C<T>.field").WithLocation(14, 18) ); } [Fact] public void Constraints_04() { var source = @" using System.Collections.Generic; namespace System { public struct ValueTuple<T1, T2> where T2 : class { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C<T> where T : class { List<(T, T)> field = null; (U, U) M<U>(U x) where U : class { var t0 = new C<int>(); var t1 = M(1); return default((U, U)); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (17,24): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C<T>' // var t0 = new C<int>(); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("C<T>", "T", "int").WithLocation(17, 24), // (18,18): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C<T>.M<U>(U)' // var t1 = M(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "M").WithArguments("C<T>.M<U>(U)", "U", "int").WithLocation(18, 18), // (14,18): warning CS0414: The field 'C<T>.field' is assigned but its value is never used // List<(T, T)> field = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C<T>.field").WithLocation(14, 18) ); } [Fact] public void Constraints_05() { var source = @" using System.Collections.Generic; namespace System { public struct ValueTuple<T1, T2> where T2 : struct { public ValueTuple(T1 _1, T2 _2) => throw null; } } class C<T> where T : class { List<(T, T)> field = null; (U, U) M<U>(U x) where U : class { var t0 = new C<int>(); var t1 = M((1, 2)); return default((U, U)); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (15,12): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // (U, U) M<U>(U x) where U : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M").WithArguments("(T1, T2)", "T2", "U").WithLocation(15, 12), // (14,18): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // List<(T, T)> field = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "field").WithArguments("(T1, T2)", "T2", "T").WithLocation(14, 18), // (17,24): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C<T>' // var t0 = new C<int>(); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("C<T>", "T", "int").WithLocation(17, 24), // (18,18): error CS0452: The type '(int, int)' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C<T>.M<U>(U)' // var t1 = M((1, 2)); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "M").WithArguments("C<T>.M<U>(U)", "U", "(int, int)").WithLocation(18, 18), // (19,28): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // return default((U, U)); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "U").WithArguments("(T1, T2)", "T2", "U").WithLocation(19, 28), // (14,18): warning CS0414: The field 'C<T>.field' is assigned but its value is never used // List<(T, T)> field = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C<T>.field").WithLocation(14, 18) ); } [Fact] public void Constraints_06() { var source = @" namespace System { public struct ValueTuple<T1> where T1 : class { public T1 Item1; public ValueTuple(T1 item1) { this.Item1 = item1; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where TRest : class { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } } } class C { void M((int, int, int, int, int, int, int, int) p) { var t0 = (1, 2, 3, 4, 5, 6, 7, 8); (int, int, int, int, int, int, int, int) t1 = t0; } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source); comp.VerifyDiagnostics( // (42,53): error CS0452: The type 'ValueTuple<int>' must be a reference type in order to use it as parameter 'TRest' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' // void M((int, int, int, int, int, int, int, int) p) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "p").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "TRest", "System.ValueTuple<int>").WithLocation(42, 53), // (42,53): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method 'ValueTuple<T1>' // void M((int, int, int, int, int, int, int, int) p) Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "p").WithArguments("System.ValueTuple<T1>", "T1", "int").WithLocation(42, 53), // (44,18): error CS0452: The type 'ValueTuple<int>' must be a reference type in order to use it as parameter 'TRest' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' // var t0 = (1, 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "(1, 2, 3, 4, 5, 6, 7, 8)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "TRest", "System.ValueTuple<int>").WithLocation(44, 18), // (44,40): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method 'ValueTuple<T1>' // var t0 = (1, 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "8").WithArguments("System.ValueTuple<T1>", "T1", "int").WithLocation(44, 40), // (45,9): error CS0452: The type 'ValueTuple<int>' must be a reference type in order to use it as parameter 'TRest' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' // (int, int, int, int, int, int, int, int) t1 = t0; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "(int, int, int, int, int, int, int, int)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "TRest", "System.ValueTuple<int>").WithLocation(45, 9), // (45,45): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method 'ValueTuple<T1>' // (int, int, int, int, int, int, int, int) t1 = t0; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("System.ValueTuple<T1>", "T1", "int").WithLocation(45, 45) ); } [Fact] public void LongTupleConstraints() { var source = @" using System; class Program { unsafe void M0((int, int, int, int, int, int, int, int*) p) { (int, int, int, int, int, int, int, int*) t1 = p; var t2 = (1, 2, 3, 4, 5, 6, 7, (int*)null); var t3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> (); var t4 = new ValueTuple<int, int, int, int, int, int, int, (int, int*)> (); ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> t5 = t3; ValueTuple<int, int, int, int, int, int, int, (int, int*)> t6 = t4; } unsafe void M1((int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) q) { (int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) v1 = q; var v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (int*)null); } }"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: s_valueTupleRefs, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (15,102): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M1((int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) q) Diagnostic(ErrorCode.ERR_BadTypeArgument, "q").WithArguments("int*").WithLocation(15, 102), // (5,62): error CS0306: The type 'int*' may not be used as a type argument // unsafe void M0((int, int, int, int, int, int, int, int*) p) Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(5, 62), // (7,45): error CS0306: The type 'int*' may not be used as a type argument // (int, int, int, int, int, int, int, int*) t1 = p; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(7, 45), // (8,40): error CS0306: The type 'int*' may not be used as a type argument // var t2 = (1, 2, 3, 4, 5, 6, 7, (int*)null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "(int*)null").WithArguments("int*").WithLocation(8, 40), // (9,84): error CS0306: The type 'int*' may not be used as a type argument // var t3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> (); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(9, 84), // (10,74): error CS0306: The type 'int*' may not be used as a type argument // var t4 = new ValueTuple<int, int, int, int, int, int, int, (int, int*)> (); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(10, 74), // (11,71): error CS0306: The type 'int*' may not be used as a type argument // ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int*>> t5 = t3; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(11, 71), // (12,61): error CS0306: The type 'int*' may not be used as a type argument // ValueTuple<int, int, int, int, int, int, int, (int, int*)> t6 = t4; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(12, 61), // (8,13): warning CS0219: The variable 't2' is assigned but its value is never used // var t2 = (1, 2, 3, 4, 5, 6, 7, (int*)null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2").WithLocation(8, 13), // (17,85): error CS0306: The type 'int*' may not be used as a type argument // (int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int*) v1 = q; Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(17, 85), // (18,70): error CS0306: The type 'int*' may not be used as a type argument // var v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (int*)null); Diagnostic(ErrorCode.ERR_BadTypeArgument, "(int*)null").WithArguments("int*").WithLocation(18, 70), // (18,13): warning CS0219: The variable 'v2' is assigned but its value is never used // var v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (int*)null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "v2").WithArguments("v2").WithLocation(18, 13) ); } [Fact] public void RestrictedTypes1() { var source = @" class C { static void Main() { var x = (1, 2, new System.ArgIterator()); (int x, object y) y = (1, 2, new System.ArgIterator()); (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,24): error CS0306: The type 'ArgIterator' may not be used as a type argument // var x = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "new System.ArgIterator()").WithArguments("System.ArgIterator").WithLocation(6, 24), // (7,38): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, object y) y = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "new System.ArgIterator()").WithArguments("System.ArgIterator").WithLocation(7, 38), // (7,31): error CS0029: Cannot implicitly convert type '(int, int, System.ArgIterator)' to '(int x, object y)' // (int x, object y) y = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2, new System.ArgIterator())").WithArguments("(int, int, System.ArgIterator)", "(int x, object y)").WithLocation(7, 31), // (8,36): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "y").WithArguments("System.ArgIterator").WithLocation(8, 36), // (8,50): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_BadTypeArgument, "new System.ArgIterator()").WithArguments("System.ArgIterator").WithLocation(8, 50), // (8,43): error CS0029: Cannot implicitly convert type '(int, int, System.ArgIterator)' to '(int x, System.ArgIterator y)' // (int x, System.ArgIterator y) z = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2, new System.ArgIterator())").WithArguments("(int, int, System.ArgIterator)", "(int x, System.ArgIterator y)").WithLocation(8, 43), // (6,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = (1, 2, new System.ArgIterator()); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13) ); } [Fact] public void RestrictedTypes2() { var source = @" class C { static void Main() { (int x, System.ArgIterator y) y; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (6,36): error CS0306: The type 'ArgIterator' may not be used as a type argument // (int x, System.ArgIterator y) y; Diagnostic(ErrorCode.ERR_BadTypeArgument, "y").WithArguments("System.ArgIterator").WithLocation(6, 36), // (6,39): warning CS0168: The variable 'y' is declared but never used // (int x, System.ArgIterator y) y; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 39) ); } [Fact, WorkItem(10569, "https://github.com/dotnet/roslyn/issues/10569")] public void IncompleteInterfaceMethod() { var source = @" public interface MyInterface { (int, int) Goo() } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,21): error CS1002: ; expected // (int, int) Goo() Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(3, 21) ); } [Fact] public void ImplementInterface() { var source = @" interface I { (int Alice, string Bob) M((int x, string y) value); (int Alice, string Bob) P1 { get; } } class C : I { static void Main() { var c = new C(); var x = c.M(c.P1); System.Console.WriteLine(x); } public (int Alice, string Bob) M((int x, string y) value) { return value; } public (int Alice, string Bob) P1 => (r: 1, s: ""hello""); } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, hello) "); } [Fact] public void ImplementInterfaceExplicitly() { var source = @" interface I { (int Alice, string Bob) M((int x, string y) value); (int Alice, string Bob) P1 { get; } } class C : I { static void Main() { I c = new C(); var x = c.M(c.P1); System.Console.WriteLine(x); System.Console.WriteLine(x.Alice); } (int Alice, string Bob) I.M((int x, string y) value) { return value; } public (int Alice, string Bob) P1 => (r: 1, s: ""hello""); } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, hello) 1"); } [Fact] public void TupleTypeArguments() { var source = @" interface I<TA, TB> where TB : TA { (TA, TB) M(TA a, TB b); } class C : I<(int, string), (int Alice, string Bob)> { static void Main() { var c = new C(); var x = c.M((1, ""Australia""), (2, ""Brazil"")); System.Console.WriteLine(x); } public ((int, string), (int Alice, string Bob)) M((int, string) x, (int Alice, string Bob) y) { return (x, y); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"((1, Australia), (2, Brazil))"); } [Fact] public void LongTupleTypeArguments() { var source = @" interface I<TA, TB> where TB : TA { (TA, TB) M(TA a, TB b); } class C : I<(int, string, int, string, int, string, int, string), (int A, string B, int C, string D, int E, string F, int G, string H)> { static void Main() { var c = new C(); var x = c.M((1, ""Australia"", 2, ""Brazil"", 3, ""Columbia"", 4, ""Ecuador""), (5, ""France"", 6, ""Germany"", 7, ""Honduras"", 8, ""India"")); System.Console.WriteLine(x); } public ((int, string, int, string, int, string, int, string), (int A, string B, int C, string D, int E, string F, int G, string H)) M((int, string, int, string, int, string, int, string) a, (int A, string B, int C, string D, int E, string F, int G, string H) b) { return (a, b); } } "; var comp = CompileAndVerify(source, expectedOutput: @"((1, Australia, 2, Brazil, 3, Columbia, 4, Ecuador), (5, France, 6, Germany, 7, Honduras, 8, India))"); } [Fact] public void OverrideGenericInterfaceWithDifferentNames() { string source = @" interface I<TA, TB> where TB : TA { (TA returnA, TB returnB) M((TA paramA, TB paramB) x); } class C : I<(int b, int a), (int a, int b)> { public virtual ((int, int) x, (int, int) y) M(((int, int), (int, int)) x) { throw new System.Exception(); } } class D : C, I<(int a, int b), (int c, int d)> { public override ((int b, int a), (int b, int a)) M(((int a, int b), (int b, int a)) y) { return y; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,49): error CS8141: The tuple element names in the signature of method 'C.M(((int, int), (int, int)))' must match the tuple element names of interface method 'I<(int b, int a), (int a, int b)>.M(((int b, int a) paramA, (int a, int b) paramB))' (including on the return type). // public virtual ((int, int) x, (int, int) y) M(((int, int), (int, int)) x) Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("C.M(((int, int), (int, int)))", "I<(int b, int a), (int a, int b)>.M(((int b, int a) paramA, (int a, int b) paramB))").WithLocation(9, 49), // (17,54): error CS8139: 'D.M(((int a, int b), (int b, int a)))': cannot change tuple element names when overriding inherited member 'C.M(((int, int), (int, int)))' // public override ((int b, int a), (int b, int a)) M(((int a, int b), (int b, int a)) y) Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("D.M(((int a, int b), (int b, int a)))", "C.M(((int, int), (int, int)))").WithLocation(17, 54), // (17,54): error CS8141: The tuple element names in the signature of method 'D.M(((int a, int b), (int b, int a)))' must match the tuple element names of interface method 'I<(int a, int b), (int c, int d)>.M(((int a, int b) paramA, (int c, int d) paramB))' (including on the return type). // public override ((int b, int a), (int b, int a)) M(((int a, int b), (int b, int a)) y) Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M").WithArguments("D.M(((int a, int b), (int b, int a)))", "I<(int a, int b), (int c, int d)>.M(((int a, int b) paramA, (int c, int d) paramB))").WithLocation(17, 54) ); } [Fact] public void TupleWithoutFeatureFlag() { var source = @" class C { static void Main() { (int, int) x = (1, 1); } CS0151ERR_IntegralTypeValueExpected} " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int, int)").WithArguments("tuples", "7.0").WithLocation(6, 9), // (6,24): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // (int, int) x = (1, 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 1)").WithArguments("tuples", "7.0").WithLocation(6, 24), // (8,36): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration // CS0151ERR_IntegralTypeValueExpected} Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}").WithLocation(8, 36) ); Assert.Equal("7.0", Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()[0])); Assert.Null(Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()[2])); Assert.Throws<ArgumentNullException>(() => Compilation.GetRequiredLanguageVersion(null)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28045")] public void DefaultAndFriendlyElementNames_01() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Console.WriteLine(v1.Item1); System.Console.WriteLine(v1.Item2); var v2 = M2(); System.Console.WriteLine(v2.Item1); System.Console.WriteLine(v2.Item2); System.Console.WriteLine(v2.a2); System.Console.WriteLine(v2.b2); var v6 = M6(); System.Console.WriteLine(v6.Item1); System.Console.WriteLine(v6.Item2); System.Console.WriteLine(v6.item1); System.Console.WriteLine(v6.item2); System.Console.WriteLine(v1.ToString()); System.Console.WriteLine(v2.ToString()); System.Console.WriteLine(v6.ToString()); } static (int, int) M1() { return (1, 11); } static (int a2, int b2) M2() { return (2, 22); } static (int item1, int item2) M6() { return (6, 66); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"1 11 2 22 2 22 6 66 6 66 (1, 11) (2, 22) (6, 66) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m6Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M6").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); Assert.Equal(new string[] { ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString" }, m1Tuple.TupleData.UnderlyingDefinitionToMemberMap.Values.Select(s => s.Name).OrderBy(n => n).ToArray()); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a2, System.Int32 b2).Item1", "System.Int32 (System.Int32 a2, System.Int32 b2).a2", "System.Int32 (System.Int32 a2, System.Int32 b2).Item2", "System.Int32 (System.Int32 a2, System.Int32 b2).b2", "(System.Int32 a2, System.Int32 b2)..ctor()", "(System.Int32 a2, System.Int32 b2)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32 a2, System.Int32 b2).Equals(System.Object obj)", "System.Boolean (System.Int32 a2, System.Int32 b2).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a2, System.Int32 b2).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a2, System.Int32 b2).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a2, System.Int32 b2).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2).GetHashCode()", "System.Int32 (System.Int32 a2, System.Int32 b2).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a2, System.Int32 b2).ToString()", "System.String (System.Int32 a2, System.Int32 b2).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a2, System.Int32 b2).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a2, System.Int32 b2).System.ITupleInternal.Size { get; }"); Assert.Equal(new string[] { ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString" }, m2Tuple.TupleData.UnderlyingDefinitionToMemberMap.Values.Select(s => s.Name).OrderBy(n => n).ToArray()); AssertTestDisplayString(m6Tuple.GetMembers(), "System.Int32 (System.Int32 item1, System.Int32 item2).Item1", "System.Int32 (System.Int32 item1, System.Int32 item2).item1", "System.Int32 (System.Int32 item1, System.Int32 item2).Item2", "System.Int32 (System.Int32 item1, System.Int32 item2).item2", "(System.Int32 item1, System.Int32 item2)..ctor()", "(System.Int32 item1, System.Int32 item2)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32 item1, System.Int32 item2).Equals(System.Object obj)", "System.Boolean (System.Int32 item1, System.Int32 item2).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32 item1, System.Int32 item2).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 item1, System.Int32 item2).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 item1, System.Int32 item2).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32 item1, System.Int32 item2).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 item1, System.Int32 item2).GetHashCode()", "System.Int32 (System.Int32 item1, System.Int32 item2).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 item1, System.Int32 item2).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 item1, System.Int32 item2).ToString()", "System.String (System.Int32 item1, System.Int32 item2).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 item1, System.Int32 item2).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 item1, System.Int32 item2).System.ITupleInternal.Size { get; }"); Assert.Equal(new string[] { ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString" }, m6Tuple.TupleData.UnderlyingDefinitionToMemberMap.Values.Select(s => s.Name).OrderBy(n => n).ToArray()); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("ValueTuple", m1Tuple.Name); Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind); Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind); Assert.False(m1Tuple.IsImplicitlyDeclared); Assert.True(m1Tuple.IsTupleType); Assert.True(m1Tuple.Equals(m1Tuple.TupleUnderlyingType, TypeCompareKind.ConsiderEverything)); var tupleType = comp.Compilation.CommonGetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.Same(tupleType, m1Tuple.ConstructedFrom); Assert.False(m1Tuple.IsDefinition); Assert.Same(tupleType, m1Tuple.OriginalDefinition); AssertTupleTypeEquality(m1Tuple); Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol); Assert.Same(m1Tuple.ContainingSymbol, m1Tuple.ContainingSymbol); Assert.Null(m1Tuple.GetUseSiteDiagnostic()); Assert.Null(m1Tuple.EnumUnderlyingType); AssertEx.SetEqual(new[] { "Item1", "Item2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m1Tuple.MemberNames.ToArray()); Assert.Equal("(System.Int32 a2, System.Int32 b2)", m2Tuple.ToTestDisplayString()); AssertEx.SetEqual(new[] { "Item1", "a2", "Item2", "b2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m2Tuple.MemberNames.ToArray()); Assert.Equal(2, m1Tuple.Arity); Assert.Equal(new[] { "T1", "T2" }, m1Tuple.TypeParameters.Select(tp => tp.ToTestDisplayString())); Assert.Equal("System.ValueType", m1Tuple.BaseType().ToTestDisplayString()); Assert.Null(m1Tuple.ComImportCoClass); Assert.True(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Assert.False(m1Tuple.IsComImport); Assert.Equal(new[] { "System.Int32", "System.Int32" }, m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Select(t => t.ToTestDisplayString())); Assert.True(m1Tuple.GetAttributes().IsEmpty); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).a2", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembers().IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty); Assert.Equal(6, m1Tuple.Interfaces().Length); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Tuple.GetEarlyAttributeDecodingMembers("Item1").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty); Assert.Equal(1, m1Tuple.Locations.Length); Assert.Equal("(int, int)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("(int a2, int b2)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); AssertTupleTypeEquality(m2Tuple); AssertTupleTypeEquality(m6Tuple); Assert.False(m1Tuple.Equals(m2Tuple)); Assert.False(m1Tuple.Equals(m6Tuple)); Assert.False(m6Tuple.Equals(m2Tuple)); AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m6Tuple); AssertTupleTypeMembersEquality(m2Tuple, m6Tuple); var m1Item1 = (FieldSymbol)m1Tuple.GetMembers()[0]; var m2Item1 = (FieldSymbol)m2Tuple.GetMembers()[0]; var m2a2 = (FieldSymbol)m2Tuple.GetMembers()[1]; AssertNonvirtualTupleElementField(m1Item1); AssertNonvirtualTupleElementField(m2Item1); AssertVirtualTupleElementField(m2a2); Assert.IsType<TupleElementFieldSymbol>(m1Item1); Assert.NotSame(m1Item1, m1Item1.OriginalDefinition); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Item1.ToTestDisplayString()); Assert.Equal("T1 (T1, T2).Item1", m1Item1.OriginalDefinition.ToTestDisplayString()); Assert.True(m1Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m1Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.True(m1Item1.Equals(m1Item1)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m1Item1.AssociatedSymbol); Assert.Same(m1Tuple, m1Item1.ContainingSymbol); Assert.Same(m1Tuple, m1Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m1Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1Item1.GetAttributes().IsEmpty); Assert.Null(m1Item1.GetUseSiteDiagnostic()); Assert.False(m1Item1.Locations.IsEmpty); Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m1Item1.TupleUnderlyingField.Name); Assert.True(m1Item1.IsImplicitlyDeclared); Assert.Null(m1Item1.TypeLayoutOffset); Assert.IsType<TupleElementFieldSymbol>(m2Item1); Assert.False(m2Item1.IsDefinition); Assert.NotSame(m2Item1, m2Item1.OriginalDefinition); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Item1.ToTestDisplayString()); Assert.Equal("T1 (T1, T2).Item1", m2Item1.OriginalDefinition.ToTestDisplayString()); Assert.True(m2Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m2Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.True(m2Item1.Equals(m2Item1)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2Item1.AssociatedSymbol); Assert.False(m2Tuple.IsDefinition); Assert.Same(m2Tuple, m2Item1.ContainingSymbol); Assert.Same(m2Tuple, m2Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m2Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2Item1.GetAttributes().IsEmpty); Assert.Null(m2Item1.GetUseSiteDiagnostic()); Assert.False(m2Item1.Locations.IsEmpty); Assert.Equal("Item1", m2Item1.Name); Assert.Equal("Item1", m2Item1.TupleUnderlyingField.Name); Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()); Assert.Equal("MetadataFile(System.ValueTuple.dll)", m2Item1.TupleUnderlyingField.Locations.Single().ToString()); Assert.Equal("SourceFile([826..828))", m2Item1.Locations.Single().ToString()); Assert.True(m2Item1.IsImplicitlyDeclared); Assert.Null(m2Item1.TypeLayoutOffset); Assert.IsType<TupleVirtualElementFieldSymbol>(m2a2); Assert.True(m2a2.IsDefinition); Assert.True(m2a2.Equals(m2a2)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).a2", m2a2.ToTestDisplayString()); Assert.True(m2a2.ContainingType.OriginalDefinition.TupleElements[0].Equals(m1Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2a2.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2a2.AssociatedSymbol); Assert.Same(m2Tuple, m2a2.ContainingSymbol); Assert.Same(m2Tuple, m2a2.TupleUnderlyingField.ContainingSymbol); Assert.True(m2a2.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2a2.GetAttributes().IsEmpty); Assert.Null(m2a2.GetUseSiteDiagnostic()); Assert.False(m2a2.Locations.IsEmpty); Assert.Equal("int a2", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m2a2.TupleUnderlyingField.Name); Assert.False(m2a2.IsImplicitlyDeclared); Assert.Null(m2a2.TypeLayoutOffset); Assert.False(m6Tuple.IsDefinition); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28045")] public void DefaultAndFriendlyElementNames_LongTuple() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Console.Write(v1.Item9 + "" ""); var v1b = M1b(); System.Console.Write(v1b.Item9 + "" ""); var v2 = M2(); System.Console.Write(v2.Item9 + "" ""); System.Console.Write(v2.i2 + "" ""); var v6 = M6(); System.Console.Write(v6.item8 + "" ""); } static (int, int, int, int, int, int, int, int, int) M1() => (1, 1, 1, 11, 11, 11, 111, 111, 111); static ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>> M1b() => (1, 1, 1, 11, 11, 11, 111, 111, 111); static (int a2, int b2, int c2, int d2, int e2, int f2, int g2, int h2, int i2) M2() => (2, 2, 2, 22, 22, 22, 222, 222, 222); static (int item1, int item2, int item3, int item4, int item5, int item6, int item7, int item8) M6() => (6, 6, 6, 66, 66, 66, 666, 666); } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"111 111 222 222 666"); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; var m1bTuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1b").ReturnType; var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m6Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M6").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", "(System.Int32, System.Int32) (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item1", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).a2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).b2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item3", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).c2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item4", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).d2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item5", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).e2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item6", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).f2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item7", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).g2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item8", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).h2", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item9", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).i2", "(System.Int32, System.Int32) (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Rest", "(System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2)..ctor()", "(System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Equals(System.Object obj)", "System.Boolean (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).GetHashCode()", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).ToString()", "System.String (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).System.ITupleInternal.Size { get; }"); Assert.Equal("ValueTuple", m1Tuple.Name); Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind); Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind); Assert.False(m1Tuple.IsImplicitlyDeclared); Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString()); Assert.Equal("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", m1Tuple.OriginalDefinition.ToTestDisplayString()); Assert.Same(m1Tuple.OriginalDefinition, m1Tuple.ConstructedFrom); AssertTupleTypeEquality(m1Tuple); Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol); Assert.True(m1Tuple.TupleUnderlyingType.Equals(m1Tuple, TypeCompareKind.ConsiderEverything)); Assert.Null(m1Tuple.GetUseSiteDiagnostic()); Assert.Null(m1Tuple.EnumUnderlyingType); AssertEx.Equal(new[] { "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9" , "Rest", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m1Tuple.MemberNames.ToArray()); AssertEx.Equal(new[] { "Item1", "a2", "Item2", "b2", "Item3", "c2", "Item4", "d2", "Item5", "e2", "Item6", "f2", "Item7", "g2", "Item8", "h2", "Item9", "i2", "Rest", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size" }, m2Tuple.MemberNames.ToArray()); Assert.Equal(8, m1Tuple.Arity); AssertEx.Equal(new[] { "T1", "T2", "T3", "T4", "T5", "T6", "T7", "TRest" }, m1Tuple.TypeParameters.ToTestDisplayStrings()); Assert.Equal("System.ValueType", m1Tuple.BaseType().ToTestDisplayString()); Assert.Null(m1Tuple.ComImportCoClass); Assert.True(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Assert.False(m1Tuple.IsComImport); AssertEx.Equal(new[] { "System.Int32", "System.Int32", "System.Int32", "System.Int32", "System.Int32", "System.Int32", "System.Int32", "(System.Int32, System.Int32)" }, m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.ToTestDisplayStrings()); Assert.True(m1Tuple.GetAttributes().IsEmpty); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).Item9", m2Tuple.GetMembers("Item9").Single().ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2, System.Int32 c2, System.Int32 d2, System.Int32 e2, System.Int32 f2, System.Int32 g2, System.Int32 h2, System.Int32 i2).i2", m2Tuple.GetMembers("i2").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembers().IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty); Assert.Equal(6, m1Tuple.Interfaces().Length); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", m1Tuple.GetEarlyAttributeDecodingMembers("Item1").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty); Assert.Equal(1, m1Tuple.Locations.Length); Assert.Equal("(int, int, int, int, int, int, int, int, int)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("(int a2, int b2, int c2, int d2, int e2, int f2, int g2, int h2, int i2)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); AssertTupleTypeEquality(m2Tuple); AssertTupleTypeEquality(m6Tuple); Assert.False(m1Tuple.Equals(m2Tuple)); Assert.False(m1Tuple.Equals(m6Tuple)); Assert.False(m6Tuple.Equals(m2Tuple)); AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m6Tuple); AssertTupleTypeMembersEquality(m2Tuple, m6Tuple); var m1Item7 = (FieldSymbol)m1Tuple.GetMembers().Where(m => m.Name == "Item7").Single(); var m1Item9 = (FieldSymbol)m1Tuple.GetMembers().Where(m => m.Name == "Item9").Single(); AssertNonvirtualTupleElementField(m1Item7); AssertVirtualTupleElementField(m1Item9); var m2g2 = (FieldSymbol)m2Tuple.GetMembers().Where(m => m.Name == "g2").Single(); var m2Item9 = (FieldSymbol)m2Tuple.GetMembers().Where(m => m.Name == "Item9").Single(); var m2i2 = (FieldSymbol)m2Tuple.GetMembers().Where(m => m.Name == "i2").Single(); AssertVirtualTupleElementField(m2g2); AssertVirtualTupleElementField(m2Item9); AssertVirtualTupleElementField(m2i2); Assert.Same(m1Item9, m1Item9.OriginalDefinition); Assert.True(m1Item9.Equals(m1Item9)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item2", m1Item9.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m1Item9.AssociatedSymbol); Assert.Same(m1Tuple, m1Item9.ContainingSymbol); Assert.Same(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Last().Type, m1Item9.TupleUnderlyingField.ContainingSymbol); Assert.True(m1Item9.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1Item9.GetAttributes().IsEmpty); Assert.Null(m1Item9.GetUseSiteDiagnostic()); Assert.False(m1Item9.Locations.IsEmpty); Assert.True(m1Item9.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item2", m1Item9.TupleUnderlyingField.Name); Assert.True(m1Item9.IsImplicitlyDeclared); Assert.Null(m1Item9.TypeLayoutOffset); Assert.Same(m2Item9, m2Item9.OriginalDefinition); Assert.True(m2Item9.Equals(m2Item9)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item2", m2Item9.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2Item9.AssociatedSymbol); Assert.Same(m2Tuple, m2Item9.ContainingSymbol); Assert.Same(m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Last().Type, m2Item9.TupleUnderlyingField.ContainingSymbol); Assert.True(m2Item9.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2Item9.GetAttributes().IsEmpty); Assert.Null(m2Item9.GetUseSiteDiagnostic()); Assert.False(m2Item9.Locations.IsEmpty); Assert.Equal("Item9", m2Item9.Name); Assert.Equal("Item2", m2Item9.TupleUnderlyingField.Name); Assert.Equal("SourceFile([739..741))", m2Item9.Locations.Single().ToString()); Assert.Equal("MetadataFile(System.ValueTuple.dll)", m2Item9.TupleUnderlyingField.Locations.Single().ToString()); Assert.True(m2Item9.IsImplicitlyDeclared); Assert.Null(m2Item9.TypeLayoutOffset); Assert.Same(m2i2, m2i2.OriginalDefinition); Assert.True(m2i2.Equals(m2i2)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item2", m2i2.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2i2.AssociatedSymbol); Assert.Same(m2Tuple, m2i2.ContainingSymbol); Assert.Same(m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Last().Type, m2i2.TupleUnderlyingField.ContainingSymbol); Assert.True(m2i2.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2i2.GetAttributes().IsEmpty); Assert.Null(m2i2.GetUseSiteDiagnostic()); Assert.False(m2i2.Locations.IsEmpty); Assert.Equal("int i2", m2i2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item2", m2i2.TupleUnderlyingField.Name); Assert.False(m2i2.IsImplicitlyDeclared); Assert.Null(m2i2.TypeLayoutOffset); } private static void AssertTupleTypeEquality(TypeSymbol tuple) { Assert.True(tuple.Equals(tuple)); Assert.True(tuple.Equals(tuple, TypeCompareKind.ConsiderEverything)); Assert.True(tuple.Equals(tuple, TypeCompareKind.IgnoreDynamicAndTupleNames)); var members = tuple.GetMembers(); for (int i = 0; i < members.Length; i++) { for (int j = 0; j < members.Length; j++) { if (i != j) { Assert.NotSame(members[i], members[j]); Assert.False(members[i].Equals(members[j])); Assert.False(members[j].Equals(members[i])); } } } } private static void AssertTupleTypeMembersEquality(TypeSymbol tuple1, TypeSymbol tuple2) { Assert.NotSame(tuple1, tuple2); if (tuple1.Equals(tuple2)) { Assert.True(tuple2.Equals(tuple1)); var members1 = tuple1.GetMembers(); var members2 = tuple2.GetMembers(); Assert.Equal(members1.Length, members2.Length); for (int i = 0; i < members1.Length; i++) { Assert.NotSame(members1[i], members2[i]); Assert.True(members1[i].Equals(members2[i])); Assert.True(members2[i].Equals(members1[i])); Assert.Equal(members2[i].GetHashCode(), members1[i].GetHashCode()); if (members1[i].Kind == SymbolKind.Method) { var parameters1 = ((MethodSymbol)members1[i]).Parameters; var parameters2 = ((MethodSymbol)members2[i]).Parameters; AssertTupleMembersParametersEquality(parameters1, parameters2); var typeParameters1 = ((MethodSymbol)members1[i]).TypeParameters; var typeParameters2 = ((MethodSymbol)members2[i]).TypeParameters; Assert.Equal(typeParameters1.Length, typeParameters2.Length); for (int j = 0; j < typeParameters1.Length; j++) { Assert.NotSame(typeParameters1[j], typeParameters2[j]); Assert.True(typeParameters1[j].Equals(typeParameters2[j])); Assert.True(typeParameters2[j].Equals(typeParameters1[j])); Assert.Equal(typeParameters2[j].GetHashCode(), typeParameters1[j].GetHashCode()); } } else if (members1[i].Kind == SymbolKind.Property) { var parameters1 = ((PropertySymbol)members1[i]).Parameters; var parameters2 = ((PropertySymbol)members2[i]).Parameters; AssertTupleMembersParametersEquality(parameters1, parameters2); } } for (int i = 0; i < members1.Length; i++) { for (int j = 0; j < members2.Length; j++) { if (i != j) { Assert.NotSame(members1[i], members2[j]); Assert.False(members1[i].Equals(members2[j])); } } } } else { Assert.False(tuple2.Equals(tuple1)); var members1 = tuple1.GetMembers(); var members2 = tuple2.GetMembers(); foreach (var m in members1) { Assert.False(members2.Any(u => u.Equals(m))); Assert.False(members2.Any(u => m.Equals(u))); } } } private static void AssertTupleMembersParametersEquality(ImmutableArray<ParameterSymbol> parameters1, ImmutableArray<ParameterSymbol> parameters2) { Assert.Equal(parameters1.Length, parameters2.Length); for (int j = 0; j < parameters1.Length; j++) { Assert.NotSame(parameters1[j], parameters2[j]); Assert.True(parameters1[j].Equals(parameters2[j])); Assert.True(parameters2[j].Equals(parameters1[j])); Assert.Equal(parameters2[j].GetHashCode(), parameters1[j].GetHashCode()); } } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_02() { var source = @" using System; class C { static void Main() { var v3 = M3(); System.Console.WriteLine(v3.Item1); System.Console.WriteLine(v3.Item2); System.Console.WriteLine(v3.Item3); System.Console.WriteLine(v3.Item4); System.Console.WriteLine(v3.Item5); System.Console.WriteLine(v3.Item6); System.Console.WriteLine(v3.Item7); System.Console.WriteLine(v3.Item8); System.Console.WriteLine(v3.Item9); System.Console.WriteLine(v3.Rest.Item1); System.Console.WriteLine(v3.Rest.Item2); System.Console.WriteLine(v3.ToString()); } static (int, int, int, int, int, int, int, int, int) M3() { return (31, 32, 33, 34, 35, 36, 37, 38, 39); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"31 32 33 34 35 36 37 38 39 38 39 (31, 32, 33, 34, 35, 36, 37, 38, 39) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; AssertTupleTypeEquality(m3Tuple); AssertTestDisplayString(m3Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", "(System.Int32, System.Int32) (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); var m3Item8 = (FieldSymbol)m3Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m3Item8); Assert.Same(m3Item8, m3Item8.OriginalDefinition); Assert.True(m3Item8.Equals(m3Item8)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m3Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m3Item8.AssociatedSymbol); Assert.Same(m3Tuple, m3Item8.ContainingSymbol); Assert.NotEqual(m3Tuple.TupleUnderlyingType, m3Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m3Tuple, m3Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m3Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m3Item8.GetAttributes().IsEmpty); Assert.Null(m3Item8.GetUseSiteDiagnostic()); Assert.False(m3Item8.Locations.IsEmpty); Assert.True(m3Item8.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m3Item8.TupleUnderlyingField.Name); Assert.True(m3Item8.IsImplicitlyDeclared); Assert.Null(m3Item8.TypeLayoutOffset); var m3TupleRestTuple = (NamedTypeSymbol)((FieldSymbol)m3Tuple.GetMembers("Rest").Single()).Type; AssertTestDisplayString(m3TupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); Assert.True(m3TupleRestTuple.IsTupleType); AssertTupleTypeEquality(m3TupleRestTuple); Assert.True(m3TupleRestTuple.Locations.IsEmpty); Assert.True(m3TupleRestTuple.DeclaringSyntaxReferences.IsEmpty); foreach (var m in m3TupleRestTuple.GetMembers().OfType<FieldSymbol>()) { Assert.True(m.Locations.IsEmpty); } } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_03() { var source = @" using System; class C { static void Main() { var v4 = M4 (); System.Console.WriteLine(v4.Item1); System.Console.WriteLine(v4.Item2); System.Console.WriteLine(v4.Item3); System.Console.WriteLine(v4.Item4); System.Console.WriteLine(v4.Item5); System.Console.WriteLine(v4.Item6); System.Console.WriteLine(v4.Item7); System.Console.WriteLine(v4.Item8); System.Console.WriteLine(v4.Item9); System.Console.WriteLine(v4.Rest.Item1); System.Console.WriteLine(v4.Rest.Item2); System.Console.WriteLine(v4.a4); System.Console.WriteLine(v4.b4); System.Console.WriteLine(v4.c4); System.Console.WriteLine(v4.d4); System.Console.WriteLine(v4.e4); System.Console.WriteLine(v4.f4); System.Console.WriteLine(v4.g4); System.Console.WriteLine(v4.h4); System.Console.WriteLine(v4.i4); System.Console.WriteLine(v4.ToString()); } static (int a4, int b4, int c4, int d4, int e4, int f4, int g4, int h4, int i4) M4() { return (41, 42, 43, 44, 45, 46, 47, 48, 49); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"41 42 43 44 45 46 47 48 49 48 49 41 42 43 44 45 46 47 48 49 (41, 42, 43, 44, 45, 46, 47, 48, 49) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m4Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M4").ReturnType; AssertTupleTypeEquality(m4Tuple); AssertTestDisplayString(m4Tuple.GetMembers(), "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item1", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".a4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item2", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".b4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item3", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".c4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".d4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item5", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".e4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item6", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".f4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item7", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".g4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item8", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".h4", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Item9", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".i4", "(System.Int32, System.Int32) (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Rest", "(System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + "..ctor()", "(System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + "..ctor" + "(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Equals(System.Object obj)", "System.Boolean (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".GetHashCode()", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".ToString()", "System.String (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a4, System.Int32 b4, System.Int32 c4, System.Int32 d4, System.Int32 e4, System.Int32 f4, System.Int32 g4, System.Int32 h4, System.Int32 i4)" + ".System.ITupleInternal.Size { get; }" ); var m4Item8 = (FieldSymbol)m4Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m4Item8); Assert.Same(m4Item8, m4Item8.OriginalDefinition); Assert.True(m4Item8.Equals(m4Item8)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m4Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m4Item8.AssociatedSymbol); Assert.Same(m4Tuple, m4Item8.ContainingSymbol); Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m4Tuple, m4Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m4Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m4Item8.GetAttributes().IsEmpty); Assert.Null(m4Item8.GetUseSiteDiagnostic()); Assert.False(m4Item8.Locations.IsEmpty); Assert.Equal("Item1", m4Item8.TupleUnderlyingField.Name); Assert.True(m4Item8.IsImplicitlyDeclared); Assert.Null(m4Item8.TypeLayoutOffset); var m4h4 = (FieldSymbol)m4Tuple.GetMembers("h4").Single(); AssertVirtualTupleElementField(m4h4); Assert.Same(m4h4, m4h4.OriginalDefinition); Assert.True(m4h4.Equals(m4h4)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m4h4.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m4h4.AssociatedSymbol); Assert.Same(m4Tuple, m4h4.ContainingSymbol); Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4h4.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m4Tuple, m4h4.TupleUnderlyingField.ContainingSymbol); Assert.True(m4h4.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m4h4.GetAttributes().IsEmpty); Assert.Null(m4h4.GetUseSiteDiagnostic()); Assert.False(m4h4.Locations.IsEmpty); Assert.Equal("int h4", m4h4.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m4h4.TupleUnderlyingField.Name); Assert.False(m4h4.IsImplicitlyDeclared); Assert.Null(m4h4.TypeLayoutOffset); var m4TupleRestTuple = ((FieldSymbol)m4Tuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m4TupleRestTuple); AssertTestDisplayString(m4TupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); foreach (var m in m4TupleRestTuple.GetMembers().OfType<FieldSymbol>()) { Assert.True(m.Locations.IsEmpty); } } [Fact] public void DefaultAndFriendlyElementNames_04() { var source = @" class C { static void Main() { var v4 = M4 (); System.Console.WriteLine(v4.Rest.a4); System.Console.WriteLine(v4.Rest.b4); System.Console.WriteLine(v4.Rest.c4); System.Console.WriteLine(v4.Rest.d4); System.Console.WriteLine(v4.Rest.e4); System.Console.WriteLine(v4.Rest.f4); System.Console.WriteLine(v4.Rest.g4); System.Console.WriteLine(v4.Rest.h4); System.Console.WriteLine(v4.Rest.i4); } static (int a4, int b4, int c4, int d4, int e4, int f4, int g4, int h4, int i4) M4() { return (41, 42, 43, 44, 45, 46, 47, 48, 49); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,42): error CS1061: '(int, int)' does not contain a definition for 'a4' and no extension method 'a4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.a4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "a4").WithArguments("(int, int)", "a4").WithLocation(8, 42), // (9,42): error CS1061: '(int, int)' does not contain a definition for 'b4' and no extension method 'b4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.b4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b4").WithArguments("(int, int)", "b4").WithLocation(9, 42), // (10,42): error CS1061: '(int, int)' does not contain a definition for 'c4' and no extension method 'c4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.c4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c4").WithArguments("(int, int)", "c4").WithLocation(10, 42), // (11,42): error CS1061: '(int, int)' does not contain a definition for 'd4' and no extension method 'd4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.d4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "d4").WithArguments("(int, int)", "d4").WithLocation(11, 42), // (12,42): error CS1061: '(int, int)' does not contain a definition for 'e4' and no extension method 'e4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.e4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "e4").WithArguments("(int, int)", "e4").WithLocation(12, 42), // (13,42): error CS1061: '(int, int)' does not contain a definition for 'f4' and no extension method 'f4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.f4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "f4").WithArguments("(int, int)", "f4").WithLocation(13, 42), // (14,42): error CS1061: '(int, int)' does not contain a definition for 'g4' and no extension method 'g4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.g4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "g4").WithArguments("(int, int)", "g4").WithLocation(14, 42), // (15,42): error CS1061: '(int, int)' does not contain a definition for 'h4' and no extension method 'h4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.h4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "h4").WithArguments("(int, int)", "h4").WithLocation(15, 42), // (16,42): error CS1061: '(int, int)' does not contain a definition for 'i4' and no extension method 'i4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v4.Rest.i4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "i4").WithArguments("(int, int)", "i4").WithLocation(16, 42) ); } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_05() { var source = @" using System; class C { static void Main() { var v5 = M5(); System.Console.WriteLine(v5.Item1); System.Console.WriteLine(v5.Item2); System.Console.WriteLine(v5.Item3); System.Console.WriteLine(v5.Item4); System.Console.WriteLine(v5.Item5); System.Console.WriteLine(v5.Item6); System.Console.WriteLine(v5.Item7); System.Console.WriteLine(v5.Item8); System.Console.WriteLine(v5.Item9); System.Console.WriteLine(v5.Item10); System.Console.WriteLine(v5.Item11); System.Console.WriteLine(v5.Item12); System.Console.WriteLine(v5.Item13); System.Console.WriteLine(v5.Item14); System.Console.WriteLine(v5.Item15); System.Console.WriteLine(v5.Item16); System.Console.WriteLine(v5.Rest.Item1); System.Console.WriteLine(v5.Rest.Item2); System.Console.WriteLine(v5.Rest.Item3); System.Console.WriteLine(v5.Rest.Item4); System.Console.WriteLine(v5.Rest.Item5); System.Console.WriteLine(v5.Rest.Item6); System.Console.WriteLine(v5.Rest.Item7); System.Console.WriteLine(v5.Rest.Item8); System.Console.WriteLine(v5.Rest.Item9); System.Console.WriteLine(v5.Rest.Rest.Item1); System.Console.WriteLine(v5.Rest.Rest.Item2); System.Console.WriteLine(v5.ToString()); } static (int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8, int Item9, int Item10, int Item11, int Item12, int Item13, int Item14, int Item15, int Item16) M5() { return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 508 509 510 511 512 513 514 515 516 515 516 (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) "); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m5Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M5").ReturnType; AssertTupleTypeEquality(m5Tuple); AssertTestDisplayString(m5Tuple.GetMembers(), "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item1", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item2", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item3", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item4", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item5", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item6", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item7", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item8", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item9", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item10", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item11", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item12", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item13", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item14", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item15", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Item16", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Rest", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16)..ctor()", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) rest)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Equals(System.Object obj)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).GetHashCode()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).ToString()", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9, System.Int32 Item10, System.Int32 Item11, System.Int32 Item12, System.Int32 Item13, System.Int32 Item14, System.Int32 Item15, System.Int32 Item16).System.ITupleInternal.Size { get; }" ); var m5Item8 = (FieldSymbol)m5Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m5Item8); Assert.Same(m5Item8, m5Item8.OriginalDefinition); Assert.True(m5Item8.Equals(m5Item8)); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", m5Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m5Item8.AssociatedSymbol); Assert.Same(m5Tuple, m5Item8.ContainingSymbol); Assert.NotEqual(m5Tuple.TupleUnderlyingType, m5Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m5Tuple, m5Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m5Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m5Item8.GetAttributes().IsEmpty); Assert.Null(m5Item8.GetUseSiteDiagnostic()); Assert.False(m5Item8.Locations.IsEmpty); Assert.Equal("int Item8", m5Item8.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m5Item8.TupleUnderlyingField.Name); Assert.False(m5Item8.IsImplicitlyDeclared); Assert.Null(m5Item8.TypeLayoutOffset); var m5TupleRestTuple = ((FieldSymbol)m5Tuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m5TupleRestTuple); AssertTestDisplayString(m5TupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", "(System.Int32, System.Int32) (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); foreach (var m in m5TupleRestTuple.GetMembers().OfType<FieldSymbol>()) { if (m.Name != "Rest") { Assert.True(m.Locations.IsEmpty); } else { Assert.Equal("Rest", m.Name); } } var m5TupleRestTupleRestTuple = ((FieldSymbol)m5TupleRestTuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m5TupleRestTupleRestTuple); AssertTestDisplayString(m5TupleRestTupleRestTuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Boolean (System.Int32, System.Int32).Equals(System.Object obj)", "System.Boolean (System.Int32, System.Int32).Equals((System.Int32, System.Int32) other)", "System.Boolean (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32, System.Int32).CompareTo((System.Int32, System.Int32) other)", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32, System.Int32).GetHashCode()", "System.Int32 (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32, System.Int32).ToString()", "System.String (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size.get", "System.Int32 (System.Int32, System.Int32).System.ITupleInternal.Size { get; }"); foreach (var m in m5TupleRestTupleRestTuple.GetMembers().OfType<FieldSymbol>()) { Assert.True(m.Locations.IsEmpty); } } [Fact] public void DefaultAndFriendlyElementNames_06() { var source = @" class C { static void Main() { var v5 = M5(); System.Console.WriteLine(v5.Rest.Item10); System.Console.WriteLine(v5.Rest.Item11); System.Console.WriteLine(v5.Rest.Item12); System.Console.WriteLine(v5.Rest.Item13); System.Console.WriteLine(v5.Rest.Item14); System.Console.WriteLine(v5.Rest.Item15); System.Console.WriteLine(v5.Rest.Item16); System.Console.WriteLine(v5.Rest.Rest.Item3); System.Console.WriteLine(v5.Rest.Rest.Item4); System.Console.WriteLine(v5.Rest.Rest.Item5); System.Console.WriteLine(v5.Rest.Rest.Item6); System.Console.WriteLine(v5.Rest.Rest.Item7); System.Console.WriteLine(v5.Rest.Rest.Item8); System.Console.WriteLine(v5.Rest.Rest.Item9); System.Console.WriteLine(v5.Rest.Rest.Item10); System.Console.WriteLine(v5.Rest.Rest.Item11); System.Console.WriteLine(v5.Rest.Rest.Item12); System.Console.WriteLine(v5.Rest.Rest.Item13); System.Console.WriteLine(v5.Rest.Rest.Item14); System.Console.WriteLine(v5.Rest.Rest.Item15); System.Console.WriteLine(v5.Rest.Rest.Item16); } static (int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8, int Item9, int Item10, int Item11, int Item12, int Item13, int Item14, int Item15, int Item16) M5() { return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item10' and no extension method 'Item10' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item10); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item10").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item10").WithLocation(8, 42), // (9,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item11' and no extension method 'Item11' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item11); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item11").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item11").WithLocation(9, 42), // (10,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item12' and no extension method 'Item12' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item12); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item12").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item12").WithLocation(10, 42), // (11,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item13' and no extension method 'Item13' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item13); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item13").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item13").WithLocation(11, 42), // (12,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item14' and no extension method 'Item14' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item14); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item14").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item14").WithLocation(12, 42), // (13,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item15' and no extension method 'Item15' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item15); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item15").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item15").WithLocation(13, 42), // (14,42): error CS1061: '(int, int, int, int, int, int, int, int, int)' does not contain a definition for 'Item16' and no extension method 'Item16' accepting a first argument of type '(int, int, int, int, int, int, int, int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Item16); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item16").WithArguments("(int, int, int, int, int, int, int, int, int)", "Item16").WithLocation(14, 42), // (16,47): error CS1061: '(int, int)' does not contain a definition for 'Item3' and no extension method 'Item3' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item3); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item3").WithArguments("(int, int)", "Item3").WithLocation(16, 47), // (17,47): error CS1061: '(int, int)' does not contain a definition for 'Item4' and no extension method 'Item4' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item4); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item4").WithArguments("(int, int)", "Item4").WithLocation(17, 47), // (18,47): error CS1061: '(int, int)' does not contain a definition for 'Item5' and no extension method 'Item5' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item5); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item5").WithArguments("(int, int)", "Item5").WithLocation(18, 47), // (19,47): error CS1061: '(int, int)' does not contain a definition for 'Item6' and no extension method 'Item6' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item6); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item6").WithArguments("(int, int)", "Item6").WithLocation(19, 47), // (20,47): error CS1061: '(int, int)' does not contain a definition for 'Item7' and no extension method 'Item7' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item7); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item7").WithArguments("(int, int)", "Item7").WithLocation(20, 47), // (21,47): error CS1061: '(int, int)' does not contain a definition for 'Item8' and no extension method 'Item8' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("(int, int)", "Item8").WithLocation(21, 47), // (22,47): error CS1061: '(int, int)' does not contain a definition for 'Item9' and no extension method 'Item9' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item9); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item9").WithArguments("(int, int)", "Item9").WithLocation(22, 47), // (23,47): error CS1061: '(int, int)' does not contain a definition for 'Item10' and no extension method 'Item10' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item10); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item10").WithArguments("(int, int)", "Item10").WithLocation(23, 47), // (24,47): error CS1061: '(int, int)' does not contain a definition for 'Item11' and no extension method 'Item11' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item11); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item11").WithArguments("(int, int)", "Item11").WithLocation(24, 47), // (25,47): error CS1061: '(int, int)' does not contain a definition for 'Item12' and no extension method 'Item12' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item12); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item12").WithArguments("(int, int)", "Item12").WithLocation(25, 47), // (26,47): error CS1061: '(int, int)' does not contain a definition for 'Item13' and no extension method 'Item13' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item13); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item13").WithArguments("(int, int)", "Item13").WithLocation(26, 47), // (27,47): error CS1061: '(int, int)' does not contain a definition for 'Item14' and no extension method 'Item14' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item14); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item14").WithArguments("(int, int)", "Item14").WithLocation(27, 47), // (28,47): error CS1061: '(int, int)' does not contain a definition for 'Item15' and no extension method 'Item15' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item15); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item15").WithArguments("(int, int)", "Item15").WithLocation(28, 47), // (29,47): error CS1061: '(int, int)' does not contain a definition for 'Item16' and no extension method 'Item16' accepting a first argument of type '(int, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v5.Rest.Rest.Item16); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item16").WithArguments("(int, int)", "Item16").WithLocation(29, 47) ); } [Fact] public void DefaultAndFriendlyElementNames_07() { var source = @" class C { static void Main() { } static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() { return (701, 702, 703, 704, 705, 706, 707, 708, 709); } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): error CS8125: Tuple member name 'Item9' is only allowed at position 9. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item9").WithArguments("Item9", "9").WithLocation(9, 17), // (9,28): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(9, 28), // (9,39): error CS8125: Tuple member name 'Item2' is only allowed at position 2. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(9, 39), // (9,50): error CS8125: Tuple member name 'Item3' is only allowed at position 3. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item3").WithArguments("Item3", "3").WithLocation(9, 50), // (9,61): error CS8125: Tuple member name 'Item4' is only allowed at position 4. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item4").WithArguments("Item4", "4").WithLocation(9, 61), // (9,72): error CS8125: Tuple member name 'Item5' is only allowed at position 5. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item5").WithArguments("Item5", "5").WithLocation(9, 72), // (9,83): error CS8125: Tuple member name 'Item6' is only allowed at position 6. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item6").WithArguments("Item6", "6").WithLocation(9, 83), // (9,94): error CS8125: Tuple member name 'Item7' is only allowed at position 7. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item7").WithArguments("Item7", "7").WithLocation(9, 94), // (9,105): error CS8125: Tuple member name 'Item8' is only allowed at position 8. // static (int Item9, int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M7() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item8").WithArguments("Item8", "8").WithLocation(9, 105) ); var c = comp.GetTypeByMetadataName("C"); var m7Tuple = c.GetMember<MethodSymbol>("M7").ReturnType; AssertTupleTypeEquality(m7Tuple); AssertTestDisplayString(m7Tuple.GetMembers(), "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item1", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item9", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item2", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item1", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item3", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item2", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item4", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item3", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item5", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item4", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item6", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item5", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item7", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item6", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item8", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item7", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item9", "System.Int32 (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Item8", "(System.Int32, System.Int32) (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".Rest", "(System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + "..ctor" + "(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32, System.Int32) rest)", "System.String (System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + ".ToString()", "(System.Int32 Item9, System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)" + "..ctor()" ); } [ConditionalFact(typeof(DesktopOnly))] public void DefaultAndFriendlyElementNames_08() { var source = @" class C { static void Main() { } static (int a1, int a2, int a3, int a4, int a5, int a6, int a7, int Item1) M8() { return (801, 802, 803, 804, 805, 806, 807, 808); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,73): error CS8125: Tuple member name 'Item1' is only allowed at position 1. // static (int a1, int a2, int a3, int a4, int a5, int a6, int a7, int Item1) M8() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item1").WithArguments("Item1", "1").WithLocation(9, 73) ); var c = comp.GetTypeByMetadataName("C"); var m8Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M8").ReturnType; AssertTupleTypeEquality(m8Tuple); AssertTestDisplayString(m8Tuple.GetMembers(), "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item1", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a1", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item2", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a2", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item3", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a3", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item4", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a4", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item5", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a5", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item6", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a6", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item7", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).a7", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item8", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Item1", "System.ValueTuple<System.Int32> (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Rest", "(System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1)..ctor()", "(System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1)..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, System.ValueTuple<System.Int32> rest)", "System.Boolean (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Equals(System.Object obj)", "System.Boolean (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).GetHashCode()", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).ToString()", "System.String (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.Size.get", "System.Int32 (System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7, System.Int32 Item1).System.ITupleInternal.Size { get; }"); var m8Item8 = (FieldSymbol)m8Tuple.GetMembers("Item8").Single(); AssertVirtualTupleElementField(m8Item8); Assert.Same(m8Item8, m8Item8.OriginalDefinition); Assert.True(m8Item8.Equals(m8Item8)); Assert.Equal("System.Int32 System.ValueTuple<System.Int32>.Item1", m8Item8.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m8Item8.AssociatedSymbol); Assert.Same(m8Tuple, m8Item8.ContainingSymbol); Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item8.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m8Tuple, m8Item8.TupleUnderlyingField.ContainingSymbol); Assert.True(m8Item8.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m8Item8.GetAttributes().IsEmpty); Assert.Null(m8Item8.GetUseSiteDiagnostic()); Assert.False(m8Item8.Locations.IsEmpty); Assert.Equal("Item1", m8Item8.TupleUnderlyingField.Name); Assert.True(m8Item8.IsImplicitlyDeclared); Assert.Null(m8Item8.TypeLayoutOffset); var m8Item1 = (FieldSymbol)m8Tuple.GetMembers("Item1").Last(); AssertVirtualTupleElementField(m8Item1); Assert.Same(m8Item1, m8Item1.OriginalDefinition); Assert.True(m8Item1.Equals(m8Item1)); Assert.Equal("System.Int32 System.ValueTuple<System.Int32>.Item1", m8Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m8Item1.AssociatedSymbol); Assert.Same(m8Tuple, m8Item1.ContainingSymbol); Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item1.TupleUnderlyingField.ContainingSymbol); Assert.NotEqual(m8Tuple, m8Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m8Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m8Item1.GetAttributes().IsEmpty); Assert.Null(m8Item1.GetUseSiteDiagnostic()); Assert.False(m8Item1.Locations.IsEmpty); Assert.Equal("Item1", m8Item1.Name); Assert.Equal("Item1", m8Item1.TupleUnderlyingField.Name); Assert.NotEqual(m8Item1.Locations.Single(), m8Item1.TupleUnderlyingField.Locations.Single()); Assert.False(m8Item1.IsImplicitlyDeclared); Assert.Null(m8Item1.TypeLayoutOffset); var m8TupleRestTuple = ((FieldSymbol)m8Tuple.GetMembers("Rest").Single()).Type; AssertTupleTypeEquality(m8TupleRestTuple); AssertTestDisplayString(m8TupleRestTuple.GetMembers(), "System.Int32 System.ValueTuple<System.Int32>.Item1", "System.ValueTuple<System.Int32>..ctor()", "System.ValueTuple<System.Int32>..ctor(System.Int32 item1)", "System.Boolean System.ValueTuple<System.Int32>.Equals(System.Object obj)", "System.Boolean System.ValueTuple<System.Int32>.Equals(System.ValueTuple<System.Int32> other)", "System.Boolean System.ValueTuple<System.Int32>.System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32>.System.IComparable.CompareTo(System.Object other)", "System.Int32 System.ValueTuple<System.Int32>.CompareTo(System.ValueTuple<System.Int32> other)", "System.Int32 System.ValueTuple<System.Int32>.System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 System.ValueTuple<System.Int32>.GetHashCode()", "System.Int32 System.ValueTuple<System.Int32>.System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32>.System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String System.ValueTuple<System.Int32>.ToString()", "System.String System.ValueTuple<System.Int32>.System.ITupleInternal.ToStringEnd()", "System.Int32 System.ValueTuple<System.Int32>.System.ITupleInternal.Size.get", "System.Int32 System.ValueTuple<System.Int32>.System.ITupleInternal.Size { get; }"); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void DefaultAndFriendlyElementNames_09() { var source = @" using System; class C { static void Main() { var v1 = (1, 11); System.Console.WriteLine(v1.Item1); System.Console.WriteLine(v1.Item2); var v2 =(a2: 2, b2: 22); System.Console.WriteLine(v2.Item1); System.Console.WriteLine(v2.Item2); System.Console.WriteLine(v2.a2); System.Console.WriteLine(v2.b2); var v6 = (item1: 6, item2: 66); System.Console.WriteLine(v6.Item1); System.Console.WriteLine(v6.Item2); System.Console.WriteLine(v6.item1); System.Console.WriteLine(v6.item2); System.Console.WriteLine(v1.ToString()); System.Console.WriteLine(v2.ToString()); System.Console.WriteLine(v6.ToString()); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"1 11 2 22 2 22 6 66 6 66 {1, 11} {2, 22} {6, 66} "); var c = (CSharpCompilation)comp.Compilation; var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); var m1Tuple = model.LookupSymbols(node.SpanStart, name: "v1").OfType<ILocalSymbol>().Single().Type.GetSymbol<NamedTypeSymbol>(); var m2Tuple = model.LookupSymbols(node.SpanStart, name: "v2").OfType<ILocalSymbol>().Single().Type.GetSymbol<NamedTypeSymbol>(); var m6Tuple = model.LookupSymbols(node.SpanStart, name: "v6").OfType<ILocalSymbol>().Single().Type.GetSymbol<NamedTypeSymbol>(); AssertEx.Equal(new[] { "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "System.String (System.Int32, System.Int32).ToString()" }, m1Tuple.GetMembersUnordered().ToTestDisplayStrings().ToImmutableArray().Sort()); AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32, System.Int32).ToString()", "(System.Int32, System.Int32)..ctor()"); AssertTestDisplayString(m2Tuple.GetMembers(), "System.Int32 (System.Int32 a2, System.Int32 b2).Item1", "System.Int32 (System.Int32 a2, System.Int32 b2).a2", "System.Int32 (System.Int32 a2, System.Int32 b2).Item2", "System.Int32 (System.Int32 a2, System.Int32 b2).b2", "(System.Int32 a2, System.Int32 b2)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32 a2, System.Int32 b2).ToString()", "(System.Int32 a2, System.Int32 b2)..ctor()"); AssertTestDisplayString(m6Tuple.GetMembers(), "System.Int32 (System.Int32 item1, System.Int32 item2).Item1", "System.Int32 (System.Int32 item1, System.Int32 item2).item1", "System.Int32 (System.Int32 item1, System.Int32 item2).Item2", "System.Int32 (System.Int32 item1, System.Int32 item2).item2", "(System.Int32 item1, System.Int32 item2)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32 item1, System.Int32 item2).ToString()", "(System.Int32 item1, System.Int32 item2)..ctor()"); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("ValueTuple", m1Tuple.Name); Assert.Equal("System", m1Tuple.ContainingNamespace.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind); Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind); Assert.False(m1Tuple.IsImplicitlyDeclared); Assert.True(m1Tuple.IsTupleType); Assert.Same(m1Tuple, m1Tuple); Assert.Equal("(T1, T2)", m1Tuple.ConstructedFrom.ToTestDisplayString()); Assert.Equal("(T1, T2)", m1Tuple.OriginalDefinition.ToTestDisplayString()); Assert.NotSame(m1Tuple, m1Tuple.ConstructedFrom); Assert.NotSame(m1Tuple, m1Tuple.OriginalDefinition); AssertTupleTypeEquality(m1Tuple); Assert.Null(m1Tuple.GetUseSiteDiagnostic()); Assert.Null(m1Tuple.EnumUnderlyingType); Assert.Equal(new string[] { "Item1", "Item2", ".ctor", "ToString" }, m1Tuple.MemberNames.ToArray()); Assert.Equal(new string[] { "Item1", "a2", "Item2", "b2", ".ctor", "ToString" }, m2Tuple.MemberNames.ToArray()); Assert.Equal(2, m1Tuple.Arity); Assert.Equal(new[] { "T1", "T2" }, m1Tuple.TypeParameters.ToTestDisplayStrings()); Assert.Equal("System.ValueType", m1Tuple.BaseType().ToTestDisplayString()); Assert.Null(m1Tuple.ComImportCoClass); Assert.True(m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Assert.False(m1Tuple.IsComImport); Assert.Equal(new[] { "System.Int32", "System.Int32" }, m1Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.ToTestDisplayStrings()); Assert.True(m1Tuple.GetAttributes().IsEmpty); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).a2", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembers().IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty); Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty); Assert.True(m1Tuple.Interfaces().IsEmpty); Assert.Equal(m1Tuple.GetEarlyAttributeDecodingMembers().Select(m => m.Name).ToArray(), m1Tuple.GetEarlyAttributeDecodingMembers().Select(m => m.Name).ToArray()); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Tuple.GetEarlyAttributeDecodingMembers("Item1").Single().ToTestDisplayString()); Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty); Assert.Equal(1, m1Tuple.Locations.Length); Assert.Equal("(1, 11)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("(a2: 2, b2: 22)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.True(m1Tuple.TupleUnderlyingType.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("public struct ValueTuple<T1, T2>", m1Tuple.OriginalDefinition.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 32)); AssertTupleTypeEquality(m2Tuple); AssertTupleTypeEquality(m6Tuple); Assert.False(m1Tuple.Equals(m2Tuple)); Assert.False(m1Tuple.Equals(m6Tuple)); Assert.False(m6Tuple.Equals(m2Tuple)); AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m6Tuple); AssertTupleTypeMembersEquality(m2Tuple, m6Tuple); var m1Item1 = (FieldSymbol)m1Tuple.GetMembers()[0]; var m2Item1 = (FieldSymbol)m2Tuple.GetMembers()[0]; var m2a2 = (FieldSymbol)m2Tuple.GetMembers()[1]; AssertNonvirtualTupleElementField(m1Item1); AssertNonvirtualTupleElementField(m2Item1); AssertVirtualTupleElementField(m2a2); Assert.Equal("TupleElementFieldSymbol", m1Item1.GetType().Name); Assert.NotSame(m1Item1, m1Item1.OriginalDefinition); Assert.True(m1Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m1Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.Equal("T1 (T1, T2).Item1", m1Item1.OriginalDefinition.ToTestDisplayString()); Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(m1Item1.OriginalDefinition); Assert.True(m1Item1.Equals(m1Item1)); Assert.Equal("System.Int32 (System.Int32, System.Int32).Item1", m1Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m1Item1.AssociatedSymbol); Assert.Same(m1Tuple, m1Item1.ContainingSymbol); Assert.Same(m1Tuple, m1Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m1Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1Item1.GetAttributes().IsEmpty); Assert.Null(m1Item1.GetUseSiteDiagnostic()); Assert.False(m1Item1.Locations.IsEmpty); Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m1Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.True(m1Item1.IsImplicitlyDeclared); Assert.Null(m1Item1.TypeLayoutOffset); Assert.Equal("TupleElementFieldSymbol", m2Item1.GetType().Name); Assert.NotSame(m2Item1, m2Item1.OriginalDefinition); Assert.True(m2Item1.ContainingType.OriginalDefinition.TupleElements[0].Equals(m2Item1.OriginalDefinition, TypeCompareKind.ConsiderEverything)); Assert.Equal("T1 (T1, T2).Item1", m2Item1.OriginalDefinition.ToTestDisplayString()); Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(m2Item1.OriginalDefinition); Assert.True(m2Item1.Equals(m2Item1)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2Item1.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2Item1.AssociatedSymbol); Assert.Same(m2Tuple, m2Item1.ContainingSymbol); Assert.Same(m2Tuple, m2Item1.TupleUnderlyingField.ContainingSymbol); Assert.True(m2Item1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2Item1.GetAttributes().IsEmpty); Assert.Null(m2Item1.GetUseSiteDiagnostic()); Assert.False(m2Item1.Locations.IsEmpty); Assert.True(m2Item1.DeclaringSyntaxReferences.IsEmpty); Assert.Equal("Item1", m2Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()); Assert.Equal("SourceFile([891..896))", m2Item1.TupleUnderlyingField.Locations.Single().ToString()); Assert.Equal("SourceFile([196..198))", m2Item1.Locations.Single().ToString()); Assert.True(m2Item1.IsImplicitlyDeclared); Assert.Null(m2Item1.TypeLayoutOffset); Assert.Equal("TupleVirtualElementFieldSymbol", m2a2.GetType().Name); Assert.Same(m2a2, m2a2.OriginalDefinition); Assert.True(m2a2.Equals(m2a2)); Assert.Equal("System.Int32 (System.Int32 a2, System.Int32 b2).Item1", m2a2.TupleUnderlyingField.ToTestDisplayString()); Assert.Null(m2a2.AssociatedSymbol); Assert.Same(m2Tuple, m2a2.ContainingSymbol); Assert.Same(m2Tuple, m2a2.TupleUnderlyingField.ContainingSymbol); Assert.True(m2a2.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m2a2.GetAttributes().IsEmpty); Assert.Null(m2a2.GetUseSiteDiagnostic()); Assert.False(m2a2.Locations.IsEmpty); Assert.Equal("a2", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.Equal("Item1", m2a2.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); Assert.False(m2a2.IsImplicitlyDeclared); Assert.Null(m2a2.TypeLayoutOffset); var m1ToString = m1Tuple.GetMember<MethodSymbol>("ToString"); Assert.NotSame(m1ToString, m1ToString.OriginalDefinition); Assert.Same(m1ToString, m1ToString.ConstructedFrom); Assert.Equal("System.String (T1, T2).ToString()", m1ToString.OriginalDefinition.ToTestDisplayString()); Assert.Equal("System.String (System.Int32, System.Int32).ToString()", m1ToString.ConstructedFrom.ToTestDisplayString()); Assert.Same(m1Tuple, m1ToString.ContainingSymbol); Assert.Null(m1ToString.AssociatedSymbol); Assert.False(m1ToString.IsExplicitInterfaceImplementation); Assert.True(m1ToString.ExplicitInterfaceImplementations.IsEmpty); Assert.False(m1ToString.ReturnsVoid); Assert.True(m1ToString.TypeArgumentsWithAnnotations.IsEmpty); Assert.True(m1ToString.TypeParameters.IsEmpty); Assert.True(m1ToString.GetAttributes().IsEmpty); Assert.Null(m1ToString.GetUseSiteDiagnostic()); Assert.Equal("System.String System.ValueType.ToString()", m1ToString.OverriddenMethod.ToTestDisplayString()); Assert.False(m1ToString.Locations.IsEmpty); Assert.Equal("public override string ToString()", m1ToString.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 33)); } [Fact] public void CustomValueTupleWithStrangeThings_01() { var source = @" class C { static void Main() { var x1 = M9().Item1; var x2 = M9().Item2; var y = (int, int).C9; System.ValueTuple<int, int>.C9 z = null; System.Console.WriteLine(z); } static (int, int) M9() { return (901, 902); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { _ = new C9(); this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public class C9{} } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (10,18): error CS1525: Invalid expression term 'int' // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(10, 18), // (10,23): error CS1525: Invalid expression term 'int' // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(10, 23), // (10,28): error CS0572: 'C9': cannot reference a type through an expression; try '(int, int).C9' instead // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_BadTypeReference, "C9").WithArguments("C9", "(int, int).C9").WithLocation(10, 28) ); var c = comp.GetTypeByMetadataName("C"); var m9Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M9").ReturnType; AssertTupleTypeEquality(m9Tuple); AssertTestDisplayString(m9Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32, System.Int32).ToString()", "(System.Int32, System.Int32).C9", "(System.Int32, System.Int32)..ctor()"); Assert.True(m9Tuple.Equals(m9Tuple.TupleUnderlyingType, TypeCompareKind.ConsiderEverything)); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembers().Single().ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembers("C9").Single().ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembers("C9", 0).Single().ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32).C9", m9Tuple.GetTypeMembersUnordered().Single().ToTestDisplayString()); } [Fact] public void CustomValueTupleWithStrangeThings_01_PE() { var lib_cs = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public class C9 { } } } " + tupleattributes_cs; var source = @" class C { static void M() { var y = (int, int).C9; System.ValueTuple<int, int>.C9 z = null; System.Console.WriteLine(z); } static (int, int) M9() { return (901, 902); } } "; var libComp = CreateCompilationWithMscorlib40(lib_cs); libComp.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, references: new[] { libComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (6,18): error CS1525: Invalid expression term 'int' // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 18), // (6,23): error CS1525: Invalid expression term 'int' // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 23), // (6,28): error CS0572: 'C9': cannot reference a type through an expression; try '(int, int).C9' instead // var y = (int, int).C9; Diagnostic(ErrorCode.ERR_BadTypeReference, "C9").WithArguments("C9", "(int, int).C9").WithLocation(6, 28) ); var c = comp.GetTypeByMetadataName("C"); var m9Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M9").ReturnType; AssertTestDisplayString(m9Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32, System.Int32).ToString()", "(System.Int32, System.Int32).C9"); } [Fact] public void CustomValueTupleWithStrangeThings_02() { var source = @" partial class C { static void Main() { } public static (int, int) M10() { return (101, 102); } static (int, int, int, int, int, int, int, int, int) M101() { return (1, 1, 1, 1, 1, 1, 1, 1, 1); } I1 Test01() { return M10(); } static (int a, int b) M102() { return (1, 1); } void Test02() { System.Console.WriteLine(M10().Item1); System.Console.WriteLine(M10().Item20); System.Console.WriteLine(M102().a); } static (int a, int b, int c, int d, int e, int f, int g, int h, int Item2) M103() { return (1, 1, 1, 1, 1, 1, 1, 1, 1); } } interface I1 { void M1(); int P1 { get; set; } event System.Action E1; } namespace System { [Obsolete] public struct ValueTuple<T1, T2> : I1 { [Obsolete] public T1 Item1; [System.Runtime.InteropServices.FieldOffsetAttribute(20)] public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.Item20 = 0; this.Item21 = 0; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public class C9{} void I1.M1(){} [Obsolete] public byte Item20; [System.Runtime.InteropServices.FieldOffsetAttribute(21)] public byte Item21; [Obsolete] public void M2() {} int I1.P1 { get; set; } [Obsolete] public int P2 { get; set; } event System.Action I1.E1 {add{} remove{}} [Obsolete] public event System.Action E2; } } partial class C { static void Test03() { M10().M2(); var x = M10().P2; M10().E2 += null; } } " + trivialRemainingTuples + tupleattributes_cs; var comp = CreateCompilation(source); var c = comp.GetTypeByMetadataName("C"); // Note: we don't report on Item2 because it is considered implicitly declared (see `ClsComplianceChecker.DoNotVisit`) comp.VerifyDiagnostics( // (8,19): warning CS0612: '(T1, T2)' is obsolete // public static (int, int) M10() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(T1, T2)").WithLocation(8, 19), // (8,19): warning CS0612: '(int, int)' is obsolete // public static (int, int) M10() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(int, int)").WithLocation(8, 19), // (13,12): warning CS0612: '(T1, T2)' is obsolete // static (int, int, int, int, int, int, int, int, int) M101() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int, int, int, int, int, int, int, int)").WithArguments("(T1, T2)").WithLocation(13, 12), // (23,12): warning CS0612: '(T1, T2)' is obsolete // static (int a, int b) M102() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int a, int b)").WithArguments("(T1, T2)").WithLocation(23, 12), // (23,12): warning CS0612: '(int a, int b)' is obsolete // static (int a, int b) M102() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int a, int b)").WithArguments("(int a, int b)").WithLocation(23, 12), // (35,73): error CS8125: Tuple element name 'Item2' is only allowed at position 2. // static (int a, int b, int c, int d, int e, int f, int g, int h, int Item2) M103() Diagnostic(ErrorCode.ERR_TupleReservedElementName, "Item2").WithArguments("Item2", "2").WithLocation(35, 73), // (35,12): warning CS0612: '(T1, T2)' is obsolete // static (int a, int b, int c, int d, int e, int f, int g, int h, int Item2) M103() Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int a, int b, int c, int d, int e, int f, int g, int h, int Item2)").WithArguments("(T1, T2)").WithLocation(35, 12), // (55,10): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [System.Runtime.InteropServices.FieldOffsetAttribute(20)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffsetAttribute").WithLocation(55, 10), // (78,10): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [System.Runtime.InteropServices.FieldOffsetAttribute(21)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffsetAttribute").WithLocation(78, 10), // (10,16): warning CS0612: '(T1, T2)' is obsolete // return (101, 102); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(101, 102)").WithArguments("(T1, T2)").WithLocation(10, 16), // (15,16): warning CS0612: '(T1, T2)' is obsolete // return (1, 1, 1, 1, 1, 1, 1, 1, 1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 1, 1, 1, 1, 1, 1, 1, 1)").WithArguments("(T1, T2)").WithLocation(15, 16), // (25,16): warning CS0612: '(T1, T2)' is obsolete // return (1, 1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 1)").WithArguments("(T1, T2)").WithLocation(25, 16), // (58,16): error CS0843: Auto-implemented property '(T1, T2).I1.P1' must be fully assigned before control is returned to the caller. // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "ValueTuple").WithArguments("(T1, T2).I1.P1").WithLocation(58, 16), // (58,16): error CS0843: Auto-implemented property '(T1, T2).P2' must be fully assigned before control is returned to the caller. // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "ValueTuple").WithArguments("(T1, T2).P2").WithLocation(58, 16), // (58,16): error CS0171: Field '(T1, T2).E2' must be fully assigned before control is returned to the caller // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).E2").WithLocation(58, 16), // (30,34): warning CS0612: '(int, int).Item1' is obsolete // System.Console.WriteLine(M10().Item1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().Item1").WithArguments("(int, int).Item1").WithLocation(30, 34), // (31,34): warning CS0612: '(int, int).Item20' is obsolete // System.Console.WriteLine(M10().Item20); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().Item20").WithArguments("(int, int).Item20").WithLocation(31, 34), // (32,34): warning CS0612: '(int a, int b).a' is obsolete // System.Console.WriteLine(M102().a); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M102().a").WithArguments("(int a, int b).a").WithLocation(32, 34), // (37,16): warning CS0612: '(T1, T2)' is obsolete // return (1, 1, 1, 1, 1, 1, 1, 1, 1); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 1, 1, 1, 1, 1, 1, 1, 1)").WithArguments("(T1, T2)").WithLocation(37, 16), // (98,9): warning CS0612: '(int, int).M2()' is obsolete // M10().M2(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().M2()").WithArguments("(int, int).M2()").WithLocation(98, 9), // (99,17): warning CS0612: '(int, int).P2' is obsolete // var x = M10().P2; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().P2").WithArguments("(int, int).P2").WithLocation(99, 17), // (100,9): warning CS0612: '(int, int).E2' is obsolete // M10().E2 += null; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M10().E2").WithArguments("(int, int).E2").WithLocation(100, 9), // (90,36): warning CS0067: The event '(T1, T2).E2' is never used // public event System.Action E2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("(T1, T2).E2").WithLocation(90, 36) ); var m10Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M10").ReturnType; AssertTupleTypeEquality(m10Tuple); Assert.Equal("System.ObsoleteAttribute", m10Tuple.GetAttributes().Single().ToString()); Assert.Equal("I1", m10Tuple.Interfaces().Single().ToTestDisplayString()); var m102Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M102").ReturnType; AssertTupleTypeEquality(m102Tuple); var m10Item1 = (FieldSymbol)m10Tuple.GetMembers("Item1").Single(); var m102Item20 = (FieldSymbol)m102Tuple.GetMembers("Item20").Single(); var m102a = (FieldSymbol)m102Tuple.GetMembers("a").Single(); AssertNonvirtualTupleElementField(m10Item1); AssertTupleNonElementField(m102Item20); AssertVirtualTupleElementField(m102a); Assert.Equal("System.ObsoleteAttribute", m10Item1.GetAttributes().Single().ToString()); Assert.Equal("System.ObsoleteAttribute", m102Item20.GetAttributes().Single().ToString()); Assert.Equal("System.ObsoleteAttribute", m102a.GetAttributes().Single().ToString()); var m10Item2 = (FieldSymbol)m10Tuple.GetMembers("Item2").Single(); var m102Item21 = (FieldSymbol)m102Tuple.GetMembers("Item21").Single(); var m102Item2 = (FieldSymbol)m102Tuple.GetMembers("Item2").Single(); var m102b = (FieldSymbol)m102Tuple.GetMembers("b").Single(); AssertNonvirtualTupleElementField(m10Item2); AssertNonvirtualTupleElementField(m102Item2); AssertTupleNonElementField(m102Item21); AssertVirtualTupleElementField(m102b); Assert.Equal(20, m10Item2.TypeLayoutOffset); Assert.Equal(20, m102Item2.TypeLayoutOffset); Assert.Equal(21, m102Item21.TypeLayoutOffset); Assert.Null(m102b.TypeLayoutOffset); Assert.Equal(20, m102b.TupleUnderlyingField.TypeLayoutOffset); var m103Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M103").ReturnType; AssertTupleTypeEquality(m103Tuple); var m103Item2 = (FieldSymbol)m103Tuple.GetMembers("Item2").Last(); var m103Item9 = (FieldSymbol)m103Tuple.GetMembers("Item9").Single(); AssertVirtualTupleElementField(m103Item2); AssertVirtualTupleElementField(m103Item9); Assert.Null(m103Item2.TypeLayoutOffset); Assert.Equal(20, m103Item2.TupleUnderlyingField.TypeLayoutOffset); Assert.Null(m103Item9.TypeLayoutOffset); Assert.Equal(20, m103Item9.TupleUnderlyingField.TypeLayoutOffset); var m10I1M1 = m10Tuple.GetMember<MethodSymbol>("I1.M1"); Assert.True(m10I1M1.IsExplicitInterfaceImplementation); Assert.Equal("void I1.M1()", m10I1M1.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); var m10M2 = m10Tuple.GetMember<MethodSymbol>("M2"); Assert.Equal("System.ObsoleteAttribute", m10M2.GetAttributes().Single().ToString()); var m10I1P1 = m10Tuple.GetMember<PropertySymbol>("I1.P1"); Assert.True(m10I1P1.IsExplicitInterfaceImplementation); Assert.Equal("System.Int32 I1.P1 { get; set; }", m10I1P1.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1P1.GetMethod.IsExplicitInterfaceImplementation); Assert.Equal("System.Int32 I1.P1.get", m10I1P1.GetMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1P1.SetMethod.IsExplicitInterfaceImplementation); Assert.Equal("void I1.P1.set", m10I1P1.SetMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); var m10P2 = m10Tuple.GetMember<PropertySymbol>("P2"); Assert.Equal("System.ObsoleteAttribute", m10P2.GetAttributes().Single().ToString()); var m10I1E1 = m10Tuple.GetMember<EventSymbol>("I1.E1"); Assert.True(m10I1E1.IsExplicitInterfaceImplementation); Assert.Equal("event System.Action I1.E1", m10I1E1.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1E1.AddMethod.IsExplicitInterfaceImplementation); Assert.Equal("void I1.E1.add", m10I1E1.AddMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); Assert.True(m10I1E1.RemoveMethod.IsExplicitInterfaceImplementation); Assert.Equal("void I1.E1.remove", m10I1E1.RemoveMethod.ExplicitInterfaceImplementations.Single().ToTestDisplayString()); var m10E2 = m10Tuple.GetMember<EventSymbol>("E2"); Assert.Equal("System.ObsoleteAttribute", m10E2.GetAttributes().Single().ToString()); } [Fact, WorkItem(56327, "https://github.com/dotnet/roslyn/issues/56327")] public void CustomValueTuple_RecordStruct() { var source = @" namespace System { public record struct ValueTuple<T1, T2>(T1 Item1, T2 Item2) { } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyEmitDiagnostics(); var valuetuple = comp.GetTypeByMetadataName("System.ValueTuple`2"); AssertTestDisplayString(valuetuple.GetMembers(), "(T1, T2)..ctor(T1 Item1, T2 Item2)", "T1 (T1, T2).<Item1>k__BackingField", "readonly T1 (T1, T2).Item1.get", "void (T1, T2).Item1.set", "T1 (T1, T2).Item1 { get; set; }", "T2 (T1, T2).<Item2>k__BackingField", "readonly T2 (T1, T2).Item2.get", "void (T1, T2).Item2.set", "T2 (T1, T2).Item2 { get; set; }", "readonly System.String (T1, T2).ToString()", "readonly System.Boolean (T1, T2).PrintMembers(System.Text.StringBuilder builder)", "System.Boolean (T1, T2).op_Inequality((T1, T2) left, (T1, T2) right)", "System.Boolean (T1, T2).op_Equality((T1, T2) left, (T1, T2) right)", "readonly System.Int32 (T1, T2).GetHashCode()", "readonly System.Boolean (T1, T2).Equals(System.Object obj)", "readonly System.Boolean (T1, T2).Equals((T1, T2) other)", "readonly void (T1, T2).Deconstruct(out T1 Item1, out T2 Item2)", "(T1, T2)..ctor()", "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" ); } [Fact, WorkItem(56327, "https://github.com/dotnet/roslyn/issues/56327")] public void CustomValueTuple_Properties() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1 { get; set; } public T2 Item2 { get; set; } } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(56327, "https://github.com/dotnet/roslyn/issues/56327")] public void CustomValueTuple_RecordStructWithConstructor() { var source = @" namespace System { public record struct ValueTuple<T1, T2> { public ValueTuple(string s) { } } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyEmitDiagnostics( // (7,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(string s) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(7, 16), // (7,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(string s) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(7, 16) ); } [Fact, WorkItem(56327, "https://github.com/dotnet/roslyn/issues/56327")] public void CustomValueTuple_StructWithConstructor() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(string s) { } } } " + tupleattributes_cs; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyEmitDiagnostics( // (7,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller // public ValueTuple(string s) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(7, 16), // (7,16): error CS0171: Field '(T1, T2).Item1' must be fully assigned before control is returned to the caller // public ValueTuple(string s) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item1").WithLocation(7, 16) ); } private void AssertTupleNonElementField(FieldSymbol sym) { Assert.True(sym.ContainingType.IsTupleType); Assert.False(sym.IsVirtualTupleField); //it is not an element so index must be negative Assert.True(sym.TupleElementIndex < 0); } private void AssertVirtualTupleElementField(FieldSymbol sym) { Assert.True(sym.ContainingType.IsTupleType); Assert.True(sym.IsVirtualTupleField); //it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0); } private void AssertNonvirtualTupleElementField(FieldSymbol sym) { Assert.True(sym.ContainingType.IsTupleType); Assert.False(sym.IsVirtualTupleField); //it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0); //if it was 8th or after, it would be virtual Assert.True(sym.TupleElementIndex < NamedTypeSymbol.ValueTupleRestPosition - 1); } [Fact] public void CustomValueTupleWithGenericMethod() { var source = @" class C { static void Main() { M9().Test(""Yes""); } static (int, int) M9() { return (901, 902); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public void Test<U>(U val) { System.Console.WriteLine(typeof(U)); System.Console.WriteLine(val); } } } " + tupleattributes_cs; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.String Yes"); var c = comp.GetTypeByMetadataName("C"); var m9Tuple = c.GetMember<MethodSymbol>("M9").ReturnType; AssertTupleTypeEquality(m9Tuple); var m9Test = m9Tuple.GetMember<MethodSymbol>("Test"); Assert.NotSame(m9Test, m9Test.OriginalDefinition); Assert.Same(m9Test, m9Test.ConstructedFrom); Assert.Equal("void (T1, T2).Test<U>(U val)", m9Test.OriginalDefinition.ToTestDisplayString()); Assert.Equal("void (System.Int32, System.Int32).Test<U>(U val)", m9Test.ConstructedFrom.ToTestDisplayString()); Assert.NotSame(m9Test.TypeParameters.Single(), m9Test.TypeParameters.Single().OriginalDefinition); Assert.Same(m9Test, m9Test.TypeParameters.Single().ContainingSymbol); Assert.Same(m9Test, m9Test.Parameters.Single().ContainingSymbol); Assert.Equal(0, m9Test.TypeParameters.Single().Ordinal); Assert.Equal(1, m9Test.Arity); } [ConditionalFact(typeof(DesktopOnly))] public void CreationOfTupleSymbols_01() { var source = @" class C { static void Main() { } static (int, int) M1() { return (101, 102); } static (int, int, int, int, int, int, int, int, int) M2() { return (1, 1, 1, 1, 1, 1, 1, 1, 1); } static (int, int, int) M3() { return (101, 102, 103); } } namespace System { public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2, T3 item3) => throw null; } } "; var comp = CreateCompilation(source); var c = comp.GetTypeByMetadataName("C"); comp.VerifyDiagnostics(); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; { var t1 = NamedTypeSymbol.CreateTuple(m1Tuple); var t2 = NamedTypeSymbol.CreateTuple(m1Tuple); Assert.True(t1.Equals(t2)); AssertTupleTypeMembersEquality(t1, t2); var t3 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")); var t4 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")); var t5 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("b", "a")); Assert.False(t1.Equals(t3)); Assert.True(t1.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t3); Assert.True(t3.Equals(t4)); AssertTupleTypeMembersEquality(t3, t4); Assert.False(t5.Equals(t3)); Assert.True(t5.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t5, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t5, t3); var t6 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item1", "Item2")); var t7 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item1", "Item2")); Assert.True(t6.Equals(t7)); AssertTupleTypeMembersEquality(t6, t7); Assert.False(t1.Equals(t6)); Assert.True(t1.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t6.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t6); var t8 = NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item2", "Item1")); Assert.False(t1.Equals(t8)); Assert.True(t1.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t8); Assert.False(t6.Equals(t8)); Assert.True(t6.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t6, t8); } var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; { var t1 = NamedTypeSymbol.CreateTuple(m2Tuple, default(ImmutableArray<string>)); var t2 = NamedTypeSymbol.CreateTuple(m2Tuple, default(ImmutableArray<string>)); Assert.True(t1.Equals(t2)); AssertTupleTypeMembersEquality(t1, t2); var t3 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "h", "i")); var t4 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "h", "i")); var t5 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "i", "h")); Assert.False(t1.Equals(t3)); Assert.True(t1.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t3); Assert.True(t3.Equals(t4)); AssertTupleTypeMembersEquality(t3, t4); Assert.False(t5.Equals(t3)); Assert.True(t5.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t5, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t5, t3); var t6 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); var t7 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); Assert.True(t6.Equals(t7)); AssertTupleTypeMembersEquality(t6, t7); Assert.False(t1.Equals(t6)); Assert.True(t1.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t6.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t6); var t8 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item9", "Item8")); Assert.False(t1.Equals(t8)); Assert.True(t1.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t8); Assert.False(t6.Equals(t8)); Assert.True(t6.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t6, t8); var t9 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "Item1", "Item2")); var t10 = NamedTypeSymbol.CreateTuple(m2Tuple, ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "Item1", "Item2")); Assert.True(t9.Equals(t10)); AssertTupleTypeMembersEquality(t9, t10); var t11 = NamedTypeSymbol.CreateTuple(m2Tuple.OriginalDefinition.Construct( m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.RemoveAt(7). Add(TypeWithAnnotations.Create(NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")))) )); Assert.False(t1.Equals(t11)); AssertTupleTypeMembersEquality(t1, t11); Assert.True(t1.Equals(t11, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t11.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t1.Equals(t11)); Assert.True(t1.Equals(t11, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t11.Equals(t1)); Assert.True(t11.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTestDisplayString(t11.GetMembers(), "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item1", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item2", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item3", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item4", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item5", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item6", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item7", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item8", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Item9", "(System.Int32 a, System.Int32 b) System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Rest", "System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>..ctor()", "System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>..ctor" + "(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, " + "(System.Int32 a, System.Int32 b) rest)", "System.Boolean System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.Equals(System.Object obj)", "System.Boolean System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".Equals(System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)> other)", "System.Boolean System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.IComparable.CompareTo(System.Object other)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".CompareTo(System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)> other)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".GetHashCode()", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>.ToString()", "System.String System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.ToStringEnd()", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.Size.get", "System.Int32 System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>" + ".System.ITupleInternal.Size { get; }" ); var t12 = NamedTypeSymbol.CreateTuple(m2Tuple.OriginalDefinition.Construct( m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.RemoveAt(7). Add(TypeWithAnnotations.Create(NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("Item1", "Item2")))) ), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")); Assert.False(t1.Equals(t12)); AssertTupleTypeMembersEquality(t1, t12); Assert.True(t1.Equals(t12, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t12.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t1.TupleUnderlyingType.Equals(t12.TupleUnderlyingType)); Assert.True(t1.TupleUnderlyingType.Equals(t12.TupleUnderlyingType, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t12.TupleUnderlyingType.Equals(t1.TupleUnderlyingType)); Assert.True(t12.TupleUnderlyingType.Equals(t1.TupleUnderlyingType, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t1.Equals(t12)); Assert.True(t1.Equals(t12, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.False(t12.Equals(t1)); Assert.True(t12.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTestDisplayString(t12.GetMembers(), "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item1", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item2", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item3", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item4", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item5", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item6", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item7", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item8", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Item9", "(System.Int32 Item1, System.Int32 Item2) (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Rest", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)..ctor()", "(System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + "..ctor(System.Int32 item1, System.Int32 item2, System.Int32 item3, System.Int32 item4, System.Int32 item5, System.Int32 item6, System.Int32 item7, (System.Int32 Item1, System.Int32 Item2) rest)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).Equals(System.Object obj)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".Equals((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Boolean (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.Collections.IStructuralEquatable.Equals(System.Object other, System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.IComparable.CompareTo(System.Object other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".CompareTo((System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) other)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.Collections.IStructuralComparable.CompareTo(System.Object other, System.Collections.IComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".GetHashCode()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.GetHashCode(System.Collections.IEqualityComparer comparer)", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9).ToString()", "System.String (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.ToStringEnd()", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.Size.get", "System.Int32 (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8, System.Int32 Item9)" + ".System.ITupleInternal.Size { get; }" ); var t13 = NamedTypeSymbol.CreateTuple(m2Tuple.OriginalDefinition.Construct( m2Tuple.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.RemoveAt(7). Add(TypeWithAnnotations.Create(NamedTypeSymbol.CreateTuple(m1Tuple, ImmutableArray.Create("a", "b")))) ), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "item9")); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>", t13.ToTestDisplayString()); } var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; { var t1 = NamedTypeSymbol.CreateTuple(m3Tuple); var t2 = NamedTypeSymbol.CreateTuple(m3Tuple); Assert.True(t1.Equals(t2)); AssertTupleTypeMembersEquality(t1, t2); var t3 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("a", "b", "c")); var t4 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("a", "b", "c")); var t5 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("c", "b", "a")); Assert.False(t1.Equals(t3)); Assert.True(t1.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t3); Assert.True(t3.Equals(t4)); AssertTupleTypeMembersEquality(t3, t4); Assert.False(t5.Equals(t3)); Assert.True(t5.Equals(t3, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t3.Equals(t5, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t5, t3); var t6 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("Item1", "Item2", "Item3")); var t7 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("Item1", "Item2", "Item3")); Assert.True(t6.Equals(t7)); AssertTupleTypeMembersEquality(t6, t7); Assert.False(t1.Equals(t6)); Assert.True(t1.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t6.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t6); var t8 = NamedTypeSymbol.CreateTuple(m3Tuple, ImmutableArray.Create("Item2", "Item3", "Item1")); Assert.False(t1.Equals(t8)); Assert.True(t1.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t1, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t1, t8); Assert.False(t6.Equals(t8)); Assert.True(t6.Equals(t8, TypeCompareKind.IgnoreDynamicAndTupleNames)); Assert.True(t8.Equals(t6, TypeCompareKind.IgnoreDynamicAndTupleNames)); AssertTupleTypeMembersEquality(t6, t8); } } private static void AssertTestDisplayString(ImmutableArray<Symbol> symbols, params string[] baseLine) { AssertEx.Equal(baseLine, symbols.Select(s => s.ToTestDisplayString())); } [Fact] public void UnifyUnderlyingWithTuple_01() { var source1 = @" class C { static void Main() { var v1 = Test.M1(); System.Console.WriteLine(v1.Item8); System.Console.WriteLine(v1.Item9); } } "; var source2 = @" using System; public class Test { public static ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>> M1() { return (1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; var comp1 = CreateCompilationWithMscorlib40(source2 + source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); UnifyUnderlyingWithTuple_01_AssertCompilation(comp1); var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseDll); var comp2CompilationRef = comp2.ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib45(source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, comp2CompilationRef }, options: TestOptions.ReleaseExe); Assert.NotSame(comp2.Assembly, (AssemblySymbol)comp3.GetAssemblyOrModuleSymbol(comp2CompilationRef)); // We are interested in retargeting scenario UnifyUnderlyingWithTuple_01_AssertCompilation(comp3); var comp4 = CreateCompilationWithMscorlib40(source1, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, comp2.EmitToImageReference() }, options: TestOptions.ReleaseExe); UnifyUnderlyingWithTuple_01_AssertCompilation(comp4); } private void UnifyUnderlyingWithTuple_01_AssertCompilation(CSharpCompilation comp) { CompileAndVerify(comp, expectedOutput: @"8 9 "); var test = comp.GetTypeByMetadataName("Test"); var m1Tuple = (NamedTypeSymbol)test.GetMember<MethodSymbol>("M1").ReturnType; Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); } [Fact] public void UnifyUnderlyingWithTuple_02() { var source = @" using System; class C { static void Main() { System.Console.WriteLine(nameof(ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>>)); System.Console.WriteLine(typeof(ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>>)); System.Console.WriteLine(typeof((int, int, int, int, int, int, int, int, int))); System.Console.WriteLine(typeof((int a, int b, int c, int d, int e, int f, int g, int h, int i))); System.Console.WriteLine(typeof(ValueTuple<,>)); System.Console.WriteLine(typeof(ValueTuple<,,,,,,,>)); } } "; var comp = CompileAndVerify(source, expectedOutput: @"ValueTuple System.ValueTuple`8[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.ValueTuple`2[System.Int32,System.Int32]] System.ValueTuple`8[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.ValueTuple`2[System.Int32,System.Int32]] System.ValueTuple`8[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.ValueTuple`2[System.Int32,System.Int32]] System.ValueTuple`2[T1,T2] System.ValueTuple`8[T1,T2,T3,T4,T5,T6,T7,TRest] "); var c = (CSharpCompilation)comp.Compilation; var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); var nameofNode = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "nameof").Single(); var nameofArg = ((InvocationExpressionSyntax)nameofNode.Parent).ArgumentList.Arguments.Single().Expression; var nameofArgSymbolInfo = model.GetSymbolInfo(nameofArg); Assert.True(((ITypeSymbol)nameofArgSymbolInfo.Symbol).IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", nameofArgSymbolInfo.Symbol.ToTestDisplayString()); var typeofNodes = tree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().ToArray(); Assert.Equal(5, typeofNodes.Length); for (int i = 0; i < typeofNodes.Length; i++) { var t = typeofNodes[i]; var typeInfo = model.GetTypeInfo(t.Type); var symbolInfo = model.GetSymbolInfo(t.Type); Assert.Equal(typeInfo.Type, symbolInfo.Symbol); switch (i) { case 0: case 1: Assert.True(typeInfo.Type.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", typeInfo.Type.ToTestDisplayString()); break; case 2: Assert.True(typeInfo.Type.IsTupleType); Assert.Equal("(System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32 h, System.Int32 i)", typeInfo.Type.ToTestDisplayString()); break; default: Assert.False(typeInfo.Type.IsTupleType); Assert.True(((INamedTypeSymbol)typeInfo.Type).IsUnboundGenericType); break; } } } [Fact] public void UnifyUnderlyingWithTuple_03() { var source = @" class C { static void Main() { System.Console.WriteLine(nameof((int, int))); System.Console.WriteLine(nameof((int a, int b))); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,42): error CS1525: Invalid expression term 'int' // System.Console.WriteLine(nameof((int, int))); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 42), // (6,47): error CS1525: Invalid expression term 'int' // System.Console.WriteLine(nameof((int, int))); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 47), // (7,42): error CS8185: A declaration is not allowed in this context. // System.Console.WriteLine(nameof((int a, int b))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int a").WithLocation(7, 42), // (7,49): error CS8185: A declaration is not allowed in this context. // System.Console.WriteLine(nameof((int a, int b))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int b").WithLocation(7, 49), // (7,41): error CS8081: Expression does not have a name. // System.Console.WriteLine(nameof((int a, int b))); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(int a, int b)").WithLocation(7, 41) ); } [Fact] public void UnifyUnderlyingWithTuple_04() { var source1 = @" class C { static void Main() { var v1 = Test.M1(); System.Console.WriteLine(v1.Rest.a); System.Console.WriteLine(v1.Rest.b); } } "; var source2 = @" using System; public class Test { public static ValueTuple<int, int, int, int, int, int, int, (int a, int b)> M1() { return (1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; var comp1 = CreateCompilationWithMscorlib40(source2 + source1, references: s_valueTupleRefs, options: TestOptions.ReleaseExe); unifyUnderlyingWithTuple_04_AssertCompilation(comp1); var comp2 = CreateCompilationWithMscorlib40(source2, references: s_valueTupleRefs, options: TestOptions.ReleaseDll); var comp2CompilationRef = comp2.ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib45(source1, references: (new[] { comp2CompilationRef }).Concat(s_valueTupleRefs), options: TestOptions.ReleaseExe); Assert.NotSame(comp2.Assembly, (AssemblySymbol)comp3.GetAssemblyOrModuleSymbol(comp2CompilationRef)); // We are interested in retargeting scenario unifyUnderlyingWithTuple_04_AssertCompilation(comp3); var comp4 = CreateCompilationWithMscorlib40(source1, references: (new[] { comp2.EmitToImageReference() }).Concat(s_valueTupleRefs), options: TestOptions.ReleaseExe); unifyUnderlyingWithTuple_04_AssertCompilation(comp4); void unifyUnderlyingWithTuple_04_AssertCompilation(CSharpCompilation comp) { CompileAndVerify(comp, expectedOutput: @"8 9 "); var test = comp.GetTypeByMetadataName("Test"); var m1Tuple = (NamedTypeSymbol)test.GetMember<MethodSymbol>("M1").ReturnType; Assert.True(m1Tuple.IsTupleType); AssertEx.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>", m1Tuple.ToTestDisplayString()); } } [ConditionalFact(typeof(DesktopOnly))] public void UnifyUnderlyingWithTuple_05() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var v1 = Test<ValueTuple<int, int>>.M1((1, 2, 3, 4, 5, 6, 7, 8, 9)); System.Console.WriteLine(v1.Item8); System.Console.WriteLine(v1.Item9); var v2 = Test<(int a, int b)>.M2((1, 2, 3, 4, 5, 6, 7, 10, 11)); System.Console.WriteLine(v2.Item8); System.Console.WriteLine(v2.Item9); System.Console.WriteLine(v2.Rest.a); System.Console.WriteLine(v2.Rest.b); Test<ValueTuple<int, int>>.F1 = (1, 2, 3, 4, 5, 6, 7, 12, 13); var v3 = Test<ValueTuple<int, int>>.F1; System.Console.WriteLine(v3.Item8); System.Console.WriteLine(v3.Item9); Test<ValueTuple<int, int>>.P1 = (1, 2, 3, 4, 5, 6, 7, 14, 15); var v4 = Test<ValueTuple<int, int>>.P1; System.Console.WriteLine(v4.Item8); System.Console.WriteLine(v4.Item9); var v5 = Test<ValueTuple<int, int>>.M3((1, 2, 3, 4, 5, 6, 7, 16, 17)); System.Console.WriteLine(v5[0].Item8); System.Console.WriteLine(v5[0].Item9); var v6 = Test<ValueTuple<int, int>>.M4((1, 2, 3, 4, 5, 6, 7, 18, 19)); System.Console.WriteLine(v6[0].Item8); System.Console.WriteLine(v6[0].Item9); var v7 = (new Test33()).M5((1, 2, 3, 4, 5, 6, 7, 20, 21)); System.Console.WriteLine(v7.Item8); System.Console.WriteLine(v7.Item9); var v8 = (1, 2).M6((1, 2, 3, 4, 5, 6, 7, 22, 23)); System.Console.WriteLine(v8.Item8); System.Console.WriteLine(v8.Item9); } } class Test<T> where T : struct { public static ValueTuple<int, int, int, int, int, int, int, T> M1(ValueTuple<int, int, int, int, int, int, int, T> val) { return val; } public static ValueTuple<int, int, int, int, int, int, int, T> M2(ValueTuple<int, int, int, int, int, int, int, T> val) { return val; } public static ValueTuple<int, int, int, int, int, int, int, T> F1; public static ValueTuple<int, int, int, int, int, int, int, T> P1 {get; set;} public static ValueTuple<int, int, int, int, int, int, int, T>[] M3(ValueTuple<int, int, int, int, int, int, int, T> val) { return new [] {val}; } public static List<ValueTuple<int, int, int, int, int, int, int, T>> M4(ValueTuple<int, int, int, int, int, int, int, T> val) { return new List<ValueTuple<int, int, int, int, int, int, int, T>>() {val}; } } abstract class Test31<T> { public abstract U M5<U>(U val) where U : T; } abstract class Test32<T> : Test31<ValueTuple<int, int, int, int, int, int, int, T>> where T : struct { } class Test33 : Test32<ValueTuple<int, int>> { public override U M5<U>(U val) { return val; } } static class Test4 { public static ValueTuple<int, int, int, int, int, int, int, T> M6<T>(this T target, ValueTuple<int, int, int, int, int, int, int, T> val) where T : struct { return val; } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true), expectedOutput: @"8 9 10 11 10 11 12 13 14 15 16 17 18 19 20 21 22 23 "); var test = comp.Compilation.GetTypeByMetadataName("Test`1"); var m1Tuple = (INamedTypeSymbol)test.GetMember<IMethodSymbol>("M1").ReturnType; Assert.False(m1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", m1Tuple.ToTestDisplayString()); m1Tuple = (INamedTypeSymbol)test.GetMember<IMethodSymbol>("M1").Parameters[0].Type; Assert.False(m1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", m1Tuple.ToTestDisplayString()); var c = (CSharpCompilation)comp.Compilation; var tree = c.SyntaxTrees.Single(); var model = c.GetSemanticModel(tree); var m1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M1").Single(); var symbolInfo = model.GetSymbolInfo(m1); m1Tuple = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); m1Tuple = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).Parameters[0].Type; Assert.True(m1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", m1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var m2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M2").Single(); symbolInfo = model.GetSymbolInfo(m2); var m2Tuple = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m2Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32 a, System.Int32 b)>", m2Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32 a, System.Int32 b)", m2Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var f1Tuple = (INamedTypeSymbol)test.GetMember<IFieldSymbol>("F1").Type; Assert.False(f1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", f1Tuple.ToTestDisplayString()); var f1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "F1").First(); symbolInfo = model.GetSymbolInfo(f1); f1Tuple = (INamedTypeSymbol)((IFieldSymbol)symbolInfo.Symbol).Type; Assert.True(f1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", f1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", f1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var p1Tuple = (INamedTypeSymbol)test.GetMember<IPropertySymbol>("P1").Type; Assert.False(p1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", p1Tuple.ToTestDisplayString()); var p1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "P1").First(); symbolInfo = model.GetSymbolInfo(p1); p1Tuple = (INamedTypeSymbol)((IPropertySymbol)symbolInfo.Symbol).Type; Assert.True(p1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", p1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", p1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var m3TupleArray = (IArrayTypeSymbol)test.GetMember<IMethodSymbol>("M3").ReturnType; Assert.False(m3TupleArray.ElementType.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>[]", m3TupleArray.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IList<System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>>", m3TupleArray.Interfaces[0].ToTestDisplayString()); var m3 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M3").Single(); symbolInfo = model.GetSymbolInfo(m3); m3TupleArray = (IArrayTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m3TupleArray.ElementType.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)[]", m3TupleArray.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IList<(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)>", m3TupleArray.Interfaces[0].ToTestDisplayString()); var m4TupleList = (INamedTypeSymbol)test.GetMember<IMethodSymbol>("M4").ReturnType; Assert.False(m4TupleList.TypeArguments[0].IsTupleType); Assert.Equal("System.Collections.Generic.List<System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>>", m4TupleList.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IList<System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>>", m4TupleList.Interfaces[0].ToTestDisplayString()); var m4 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M4").Single(); symbolInfo = model.GetSymbolInfo(m4); m4TupleList = (INamedTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m4TupleList.TypeArguments[0].IsTupleType); Assert.Equal("System.Collections.Generic.List<(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)>", m4TupleList.ToTestDisplayString()); var m5 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M5").Single(); symbolInfo = model.GetSymbolInfo(m5); var m5Tuple = ((IMethodSymbol)symbolInfo.Symbol).TypeParameters[0].ConstraintTypes.Single(); Assert.True(m5Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m5Tuple.ToTestDisplayString()); var m6 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M6").Single(); symbolInfo = model.GetSymbolInfo(m6); var m6Method = (IMethodSymbol)symbolInfo.Symbol; Assert.Equal(MethodKind.ReducedExtension, m6Method.MethodKind); var m6Tuple = m6Method.ReturnType; Assert.True(m6Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m6Tuple.ToTestDisplayString()); m6Tuple = m6Method.Parameters.Last().Type; Assert.True(m6Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", m6Tuple.ToTestDisplayString()); } [Fact] public void UnifyUnderlyingWithTuple_06() { var source = @" using System; unsafe class C { static void Main() { var x = Test<ValueTuple<int, int>>.E1; var v7 = Test<ValueTuple<int, int>>.M5(); System.Console.WriteLine(v7->Item8); System.Console.WriteLine(v7->Item9); Test1<ValueTuple<int, int>> v1 = null; System.Console.WriteLine(v1.Item8); ITest2<ValueTuple<int, int>> v2 = null; System.Console.WriteLine(v2.Item8); } } unsafe class Test<T> where T : struct { public static event ValueTuple<int, int, int, int, int, int, int, T> E1; public static ValueTuple<int, int, int, int, int, int, int, T>* M5() { return null; } } class Test1<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct { } interface ITest2<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct { } "; var comp = (Compilation)CreateCompilation(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)); comp.VerifyDiagnostics( // (31,18): error CS0509: 'Test1<T>': cannot derive from sealed type 'ValueTuple<int, int, int, int, int, int, int, T>' // class Test1<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "ValueTuple<int, int, int, int, int, int, int, T>").WithArguments("Test1<T>", "System.ValueTuple<int, int, int, int, int, int, int, T>").WithLocation(31, 18), // (35,23): error CS0527: Type 'ValueTuple<int, int, int, int, int, int, int, T>' in interface list is not an interface // interface ITest2<T> : ValueTuple<int, int, int, int, int, int, int, T> where T : struct Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "ValueTuple<int, int, int, int, int, int, int, T>").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, T>").WithLocation(35, 23), // (25,69): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('ValueTuple<int, int, int, int, int, int, int, T>') // public static ValueTuple<int, int, int, int, int, int, int, T>* M5() Diagnostic(ErrorCode.ERR_ManagedAddr, "M5").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, T>").WithLocation(25, 69), // (23,74): error CS0066: 'Test<T>.E1': event must be of a delegate type // public static event ValueTuple<int, int, int, int, int, int, int, T> E1; Diagnostic(ErrorCode.ERR_EventNotDelegate, "E1").WithArguments("Test<T>.E1").WithLocation(23, 74), // (7,44): error CS0070: The event 'Test<(int, int)>.E1' can only appear on the left hand side of += or -= (except when used from within the type 'Test<(int, int)>') // var x = Test<ValueTuple<int, int>>.E1; Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("Test<(int, int)>.E1", "Test<(int, int)>").WithLocation(7, 44), // (14,37): error CS1061: 'Test1<(int, int)>' does not contain a definition for 'Item8' and no accessible extension method 'Item8' accepting a first argument of type 'Test1<(int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v1.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("Test1<(int, int)>", "Item8").WithLocation(14, 37), // (17,37): error CS1061: 'ITest2<(int, int)>' does not contain a definition for 'Item8' and no accessible extension method 'Item8' accepting a first argument of type 'ITest2<(int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v2.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("ITest2<(int, int)>", "Item8").WithLocation(17, 37) ); var test = comp.GetTypeByMetadataName("Test`1"); var e1Tuple = (INamedTypeSymbol)test.GetMember<IEventSymbol>("E1").Type; Assert.False(e1Tuple.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>", e1Tuple.ToTestDisplayString()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var e1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "E1").Single(); var symbolInfo = model.GetSymbolInfo(e1); e1Tuple = (INamedTypeSymbol)((IEventSymbol)symbolInfo.CandidateSymbols.Single()).Type; Assert.True(e1Tuple.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", e1Tuple.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", e1Tuple.GetMember<IFieldSymbol>("Rest").Type.ToTestDisplayString()); var m5TuplePointer = (IPointerTypeSymbol)test.GetMember<IMethodSymbol>("M5").ReturnType; Assert.False(m5TuplePointer.PointedAtType.IsTupleType); Assert.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, T>*", m5TuplePointer.ToTestDisplayString()); var m5 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "M5").Single(); symbolInfo = model.GetSymbolInfo(m5); m5TuplePointer = (IPointerTypeSymbol)((IMethodSymbol)symbolInfo.Symbol).ReturnType; Assert.True(m5TuplePointer.PointedAtType.IsTupleType); Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)*", m5TuplePointer.ToTestDisplayString()); var v1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "v1").Single(); symbolInfo = model.GetSymbolInfo(v1); var v1Type = ((ILocalSymbol)symbolInfo.Symbol).Type; Assert.Equal("Test1<(System.Int32, System.Int32)>", v1Type.ToTestDisplayString()); var v1Tuple = v1Type.BaseType; Assert.False(v1Tuple.IsTupleType); Assert.Equal("System.Object", v1Tuple.ToTestDisplayString()); var v2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "v2").Single(); symbolInfo = model.GetSymbolInfo(v2); var v2Type = ((ILocalSymbol)symbolInfo.Symbol).Type; Assert.Equal("ITest2<(System.Int32, System.Int32)>", v2Type.ToTestDisplayString()); Assert.True(v2Type.Interfaces.IsEmpty); } [Fact] public void UnifyUnderlyingWithTuple_07() { var source1 = @" using System; public class Test<T> { public static ValueTuple<int, int, int, int, int, int, int, T> M1() { throw new NotImplementedException(); } } " + trivialRemainingTuples + tupleattributes_cs; var source2 = @" class C { static void Main() { var v1 = Test<(int, int, int, int, int, int, int, int, int)>.M1(); System.Console.WriteLine(v1.Item8); System.Console.WriteLine(v1.Item9); System.Console.WriteLine(v1.Rest.Item8); System.Console.WriteLine(v1.Rest.Item9); } } " + trivial2uple + trivialRemainingTuples + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40(source1, options: TestOptions.ReleaseDll); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { comp1.ToMetadataReference() }, options: TestOptions.ReleaseExe); comp2.VerifyDiagnostics( // (7,37): error CS1061: 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' does not contain a definition for 'Item8' and no extension method 'Item8' accepting a first argument of type 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v1.Item8); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item8").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>", "Item8").WithLocation(7, 37), // (8,37): error CS1061: 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' does not contain a definition for 'Item9' and no extension method 'Item9' accepting a first argument of type 'ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>' could be found (are you missing a using directive or an assembly reference?) // System.Console.WriteLine(v1.Item9); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item9").WithArguments("System.ValueTuple<int, int, int, int, int, int, int, (int, int, int, int, int, int, int, int, int)>", "Item9").WithLocation(8, 37) ); } [Fact] public void UnifyUnderlyingWithTuple_08() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string) y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string(ValueTuple<T1, T2> arg) { return arg.ToString(); } public static explicit operator long(ValueTuple<T1, T2> arg) { return ((long)(int)(object)arg.Item1 + (long)(int)(object)arg.Item2); } public static implicit operator ValueTuple<T1, T2>(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return new ValueTuple<T1, T2>(arg.Key, arg.Value); } public static explicit operator ValueTuple<T1, T2>(string arg) { return new ValueTuple<T1, T2>((T1)(object)arg, (T2)(object)arg); } public static ValueTuple<T1, T2> operator +(ValueTuple<T1, T2> arg) { return arg; } public static long operator -(ValueTuple<T1, T2> arg) { return -(long)arg; } public static bool operator !(ValueTuple<T1, T2> arg) { return (long)arg == 0; } public static long operator ~(ValueTuple<T1, T2> arg) { return -(long)arg; } public static ValueTuple<T1, T2> operator ++(ValueTuple<T1, T2> arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1+1), (T2)(object)((int)(object)arg.Item2+1)); } public static ValueTuple<T1, T2> operator --(ValueTuple<T1, T2> arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1 - 1), (T2)(object)((int)(object)arg.Item2 - 1)); } public static bool operator true(ValueTuple<T1, T2> arg) { return (long)arg != 0; } public static bool operator false(ValueTuple<T1, T2> arg) { return (long)arg == 0; } public static long operator + (ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |(ValueTuple<T1, T2> arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=(ValueTuple<T1, T2> arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib40(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnifyUnderlyingWithTuple_09() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string) y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string((T1, T2) arg) { return arg.ToString(); } public static explicit operator long((T1, T2) arg) { return ((long)(int)(object)arg.Item1 + (long)(int)(object)arg.Item2); } public static implicit operator (T1, T2)(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return (arg.Key, arg.Value); } public static explicit operator (T1, T2)(string arg) { return ((T1)(object)arg, (T2)(object)arg); } public static (T1, T2) operator +((T1, T2) arg) { return arg; } public static long operator -((T1, T2) arg) { return -(long)arg; } public static bool operator !((T1, T2) arg) { return (long)arg == 0; } public static long operator ~((T1, T2) arg) { return -(long)arg; } public static (T1, T2) operator ++((T1, T2) arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1+1), (T2)(object)((int)(object)arg.Item2+1)); } public static (T1, T2) operator --((T1, T2) arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Item1 - 1), (T2)(object)((int)(object)arg.Item2 - 1)); } public static bool operator true((T1, T2) arg) { return (long)arg != 0; } public static bool operator false((T1, T2) arg) { return (long)arg == 0; } public static long operator + ((T1, T2) arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -((T1, T2) arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *((T1, T2) arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /((T1, T2) arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %((T1, T2) arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &((T1, T2) arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |((T1, T2) arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^((T1, T2) arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<((T1, T2) arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>((T1, T2) arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==((T1, T2) arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=((T1, T2) arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >((T1, T2) arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <((T1, T2) arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=((T1, T2) arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=((T1, T2) arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib40(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] [WorkItem(11530, "https://github.com/dotnet/roslyn/issues/11530")] public void UnifyUnderlyingWithTuple_10() { var source = @" using System.Collections.Generic; class Test { static void Main() { var a = new KeyValuePair<int, long>(1, 2); (int, long) b = a; System.Console.WriteLine(b.Item1); System.Console.WriteLine(b.Item2); b.Item1++; b.Item2++; a = b; System.Console.WriteLine(a.Key); System.Console.WriteLine(a.Value); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static implicit operator KeyValuePair<T1, T2>(ValueTuple<T1, T2> tuple) { T1 k; T2 v; (k, v) = tuple; return new KeyValuePair<T1, T2>(k, v); } public static implicit operator ValueTuple<T1, T2>(KeyValuePair<T1, T2> kvp) { return (kvp.Key, kvp.Value); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, options: TestOptions.ReleaseExe, expectedOutput: @"1 2 2 3"); } [Fact] [WorkItem(11986, "https://github.com/dotnet/roslyn/issues/11986")] public void UnifyUnderlyingWithTuple_11() { var source = @" using System.Collections.Generic; class Test { static void Main() { var a = (1, 2); System.Console.WriteLine((int)a); System.Console.WriteLine((long)a); System.Console.WriteLine((string)a); System.Console.WriteLine((double)a); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static explicit operator int((T1, T2)? source) { return 1; } public static explicit operator long(Nullable<(T1, T2)> source) { return 2; } public static explicit operator string(Nullable<ValueTuple<T1, T2>> source) { return ""3""; } public static explicit operator double(ValueTuple<T1, T2>? source) { return 4; } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, options: TestOptions.ReleaseExe, expectedOutput: @"1 2 3 4"); } [Fact] public void UnifyUnderlyingWithTuple_12() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { (int, int)? x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string)? y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string(ValueTuple<T1, T2>? arg) { return arg.ToString(); } public static explicit operator long(ValueTuple<T1, T2>? arg) { return ((long)(int)(object)arg.Value.Item1 + (long)(int)(object)arg.Value.Item2); } public static implicit operator ValueTuple<T1, T2>?(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return new ValueTuple<T1, T2>(arg.Key, arg.Value); } public static explicit operator ValueTuple<T1, T2>?(string arg) { return new ValueTuple<T1, T2>((T1)(object)arg, (T2)(object)arg); } public static ValueTuple<T1, T2>? operator +(ValueTuple<T1, T2>? arg) { return arg; } public static long operator -(ValueTuple<T1, T2>? arg) { return -(long)arg; } public static bool operator !(ValueTuple<T1, T2>? arg) { return (long)arg == 0; } public static long operator ~(ValueTuple<T1, T2>? arg) { return -(long)arg; } public static ValueTuple<T1, T2>? operator ++(ValueTuple<T1, T2>? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1+1), (T2)(object)((int)(object)arg.Value.Item2+1)); } public static ValueTuple<T1, T2>? operator --(ValueTuple<T1, T2>? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1 - 1), (T2)(object)((int)(object)arg.Value.Item2 - 1)); } public static bool operator true(ValueTuple<T1, T2>? arg) { return (long)arg != 0; } public static bool operator false(ValueTuple<T1, T2>? arg) { return (long)arg == 0; } public static long operator + (ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |(ValueTuple<T1, T2>? arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=(ValueTuple<T1, T2>? arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib46(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnifyUnderlyingWithTuple_13() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { (int, int)? x = (1, 3); string s = x; System.Console.WriteLine(s); System.Console.WriteLine((long)x); (int, string)? y = new KeyValuePair<int, string>(2, ""4""); System.Console.WriteLine(y); System.Console.WriteLine((ValueTuple<string, string>)""5""); System.Console.WriteLine(+x); System.Console.WriteLine(-x); System.Console.WriteLine(!x); System.Console.WriteLine(~x); System.Console.WriteLine(++x); System.Console.WriteLine(--x); System.Console.WriteLine(x ? true : false); System.Console.WriteLine(!x ? true : false); System.Console.WriteLine(x + 1); System.Console.WriteLine(x - 1); System.Console.WriteLine(x * 3); System.Console.WriteLine(x / 2); System.Console.WriteLine(x % 3); System.Console.WriteLine(x & 3); System.Console.WriteLine(x | 15); System.Console.WriteLine(x ^ 4); System.Console.WriteLine(x << 1); System.Console.WriteLine(x >> 1); System.Console.WriteLine(x == 1); System.Console.WriteLine(x != 1); System.Console.WriteLine(x > 1); System.Console.WriteLine(x < 1); System.Console.WriteLine(x >= 1); System.Console.WriteLine(x <= 1); } } "; var tuple = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public static implicit operator string((T1, T2)? arg) { return arg.ToString(); } public static explicit operator long((T1, T2)? arg) { return ((long)(int)(object)arg.Value.Item1 + (long)(int)(object)arg.Value.Item2); } public static implicit operator (T1, T2)?(System.Collections.Generic.KeyValuePair<T1, T2> arg) { return (arg.Key, arg.Value); } public static explicit operator (T1, T2)?(string arg) { return ((T1)(object)arg, (T2)(object)arg); } public static (T1, T2)? operator +((T1, T2)? arg) { return arg; } public static long operator -((T1, T2)? arg) { return -(long)arg; } public static bool operator !((T1, T2)? arg) { return (long)arg == 0; } public static long operator ~((T1, T2)? arg) { return -(long)arg; } public static (T1, T2)? operator ++((T1, T2)? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1+1), (T2)(object)((int)(object)arg.Value.Item2+1)); } public static (T1, T2)? operator --((T1, T2)? arg) { return new ValueTuple<T1, T2>((T1)(object)((int)(object)arg.Value.Item1 - 1), (T2)(object)((int)(object)arg.Value.Item2 - 1)); } public static bool operator true((T1, T2)? arg) { return (long)arg != 0; } public static bool operator false((T1, T2)? arg) { return (long)arg == 0; } public static long operator + ((T1, T2)? arg1, int arg2) { return (long)arg1 + arg2; } public static long operator -((T1, T2)? arg1, int arg2) { return (long)arg1 - arg2; } public static long operator *((T1, T2)? arg1, int arg2) { return (long)arg1 * arg2; } public static long operator /((T1, T2)? arg1, int arg2) { return (long)arg1 / arg2; } public static long operator %((T1, T2)? arg1, int arg2) { return (long)arg1 % arg2; } public static long operator &((T1, T2)? arg1, int arg2) { return (long)arg1 & arg2; } public static long operator |((T1, T2)? arg1, long arg2) { return (long)arg1 | arg2; } public static long operator ^((T1, T2)? arg1, int arg2) { return (long)arg1 ^ arg2; } public static long operator <<((T1, T2)? arg1, int arg2) { return (long)arg1 << arg2; } public static long operator >>((T1, T2)? arg1, int arg2) { return (long)arg1 >> arg2; } public static bool operator ==((T1, T2)? arg1, int arg2) { return (long)arg1 == arg2; } public static bool operator !=((T1, T2)? arg1, int arg2) { return (long)arg1 != arg2; } public static bool operator >((T1, T2)? arg1, int arg2) { return (long)arg1 > arg2; } public static bool operator <((T1, T2)? arg1, int arg2) { return (long)arg1 < arg2; } public static bool operator >=((T1, T2)? arg1, int arg2) { return (long)arg1 >= arg2; } public static bool operator <=((T1, T2)? arg1, int arg2) { return (long)arg1 <= arg2; } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } } "; var expectedOutput = @"{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False -4 {2, 4} {1, 3} True False 5 3 12 2 1 0 15 0 8 2 False True True False True False "; var lib = CreateCompilationWithMscorlib46(tuple, options: TestOptions.ReleaseDll); lib.VerifyDiagnostics(); var consumer1 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.ToMetadataReference() }); CompileAndVerify(consumer1, expectedOutput: expectedOutput).VerifyDiagnostics(); var consumer2 = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe, references: new[] { lib.EmitToImageReference() }); CompileAndVerify(consumer2, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void ConstructorInvocation_01() { var source = @" using System; using System.Collections.Generic; class C { static void Main() { var v1 = new ValueTuple<int, int>(1, 2); System.Console.WriteLine(v1.ToString()); var v2 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int>> (10, 20, 30, 40, 50, 60, 70, new ValueTuple<int, int>(80, 90)); System.Console.WriteLine(v2.ToString()); var v3 = new ValueTuple<int, int, int, int, int, int, int, (int, int)> (100, 200, 300, 400, 500, 600, 700, (800, 900)); System.Console.WriteLine(v3.ToString()); } } "; var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"(1, 2) (10, 20, 30, 40, 50, 60, 70, 80, 90) (100, 200, 300, 400, 500, 600, 700, 800, 900) "); } [Fact] public void PropertiesAsMembers_01() { var source = @" using System; class C { static void Main() { var v1 = M1(); v1.P1 = 33; System.Console.WriteLine(v1.P1); System.Console.WriteLine(v1[-1, -2]); } static (int, int) M1() { return (1, 11); } static (int a2, int b2) M2() { return (2, 22); } static (int, int) M3() { return (6, 66); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.P1 = 0; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public int P1 {get; set;} public int this[int a, int b] { get { return 44; } } } } "; var comp = CompileAndVerify(source, expectedOutput: @"33 44"); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int32).Item1", "System.Int32 (System.Int32, System.Int32).Item2", "(System.Int32, System.Int32)..ctor(System.Int32 item1, System.Int32 item2)", "System.String (System.Int32, System.Int32).ToString()", "System.Int32 (System.Int32, System.Int32).<P1>k__BackingField", "System.Int32 (System.Int32, System.Int32).P1 { readonly get; set; }", "readonly System.Int32 (System.Int32, System.Int32).P1.get", "void (System.Int32, System.Int32).P1.set", "System.Int32 (System.Int32, System.Int32).this[System.Int32 a, System.Int32 b] { get; }", "System.Int32 (System.Int32, System.Int32).this[System.Int32 a, System.Int32 b].get", "(System.Int32, System.Int32)..ctor()"); AssertTupleTypeEquality(m1Tuple); Assert.Equal(new string[] { "Item1", "Item2", ".ctor", "ToString", "<P1>k__BackingField", "P1", "get_P1", "set_P1", "this[]", "get_Item"}, m1Tuple.MemberNames.ToArray()); Assert.Equal("System.Int32 (System.Int32, System.Int32).P1 { readonly get; set; }", m1Tuple.GetEarlyAttributeDecodingMembers("P1").Single().ToTestDisplayString()); var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m3Tuple); var m1P1 = m1Tuple.GetMember<PropertySymbol>("P1"); var m1P1Get = m1Tuple.GetMember<MethodSymbol>("get_P1"); var m1P1Set = m1Tuple.GetMember<MethodSymbol>("set_P1"); Assert.Equal(SymbolKind.Property, m1P1.Kind); Assert.NotSame(m1P1, m1P1.OriginalDefinition); Assert.True(m1P1.Equals(m1P1)); Assert.Equal("System.Int32 (System.Int32, System.Int32).P1 { readonly get; set; }", m1P1.ToTestDisplayString()); Assert.Same(m1Tuple, m1P1.ContainingSymbol); Assert.True(m1P1.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1P1.GetAttributes().IsEmpty); Assert.Null(m1P1.GetUseSiteDiagnostic()); Assert.False(m1P1.IsImplicitlyDeclared); Assert.True(m1P1.Parameters.IsEmpty); Assert.True(m1P1Get.Equals(m1P1.GetMethod, TypeCompareKind.ConsiderEverything)); Assert.True(m1P1Set.Equals(m1P1.SetMethod, TypeCompareKind.ConsiderEverything)); Assert.False(m1P1.IsExplicitInterfaceImplementation); Assert.True(m1P1.ExplicitInterfaceImplementations.IsEmpty); Assert.False(m1P1.IsIndexer); Assert.Null(m1P1.OverriddenProperty); Assert.True(m1P1.Equals(m1P1Get.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1P1Get.IsImplicitlyDeclared); Assert.True(m1P1.Equals(m1P1Set.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1P1Set.IsImplicitlyDeclared); var m1P1BackingField = m1Tuple.GetMember<FieldSymbol>("<P1>k__BackingField"); Assert.True(m1P1.Equals(m1P1BackingField.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1P1BackingField.IsImplicitlyDeclared); Assert.True(m1P1BackingField.TupleUnderlyingField.IsImplicitlyDeclared); var m1this = m1Tuple.GetMember<PropertySymbol>("this[]"); var m1thisGet = m1Tuple.GetMember<MethodSymbol>("get_Item"); Assert.Equal(SymbolKind.Property, m1this.Kind); Assert.NotSame(m1this, m1this.OriginalDefinition); Assert.True(m1this.Equals(m1this)); Assert.Same(m1Tuple, m1this.ContainingSymbol); Assert.True(m1this.TypeWithAnnotations.CustomModifiers.IsEmpty); Assert.True(m1this.GetAttributes().IsEmpty); Assert.Null(m1this.GetUseSiteDiagnostic()); Assert.False(m1this.IsImplicitlyDeclared); Assert.Equal(2, m1this.Parameters.Length); Assert.True(m1thisGet.Equals(m1this.GetMethod, TypeCompareKind.ConsiderEverything)); Assert.Null(m1this.SetMethod); Assert.False(m1this.IsExplicitInterfaceImplementation); Assert.True(m1this.ExplicitInterfaceImplementations.IsEmpty); Assert.True(m1this.IsIndexer); Assert.Null(m1this.OverriddenProperty); Assert.False(m1this.IsDefinition); Assert.False(m1thisGet.IsImplicitlyDeclared); } private class SyntaxReferenceEqualityComparer : IEqualityComparer<SyntaxReference> { public static readonly SyntaxReferenceEqualityComparer Instance = new SyntaxReferenceEqualityComparer(); private SyntaxReferenceEqualityComparer() { } public bool Equals(SyntaxReference x, SyntaxReference y) { return x.GetSyntax().Equals(y.GetSyntax()); } public int GetHashCode(SyntaxReference obj) { return obj.GetHashCode(); } } [Fact] public void EventsAsMembers_01() { var source = @" using System; class C { static void Main() { var v1 = M1(); System.Action<int> d1 = (int i1) => System.Console.WriteLine(i1); v1.Test(v1, d1); System.Action<long> d2 = (long i2) => System.Console.WriteLine(i2); v1.E1 += d1; v1.RaiseE1(); v1.E1 -= d1; v1.RaiseE1(); v1.E2 += d2; v1.RaiseE2(); v1.E2 -= d2; v1.RaiseE2(); } static (int, long) M1() { return (1, 11); } static (int a2, long b2) M2() { return (2, 22); } static (int, long) M3() { return (6, 66); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this._e2 = null; } public event System.Action<T1> E1; private System.Action<T2> _e2; public event System.Action<T2> E2 { add { _e2 += value; } remove { _e2 -= value; } } public void RaiseE1() { System.Console.WriteLine(""-""); if (E1 == null) { System.Console.WriteLine(""null""); } else { E1(Item1); } System.Console.WriteLine(""-""); } public void RaiseE2() { System.Console.WriteLine(""--""); if (_e2 == null) { System.Console.WriteLine(""null""); } else { _e2(Item2); } System.Console.WriteLine(""--""); } public void Test((T1, T2) val, System.Action<T1> d) { val.E1 += d; System.Console.WriteLine(val.E1); val.E1(val.Item1); val.E1 -= d; System.Console.WriteLine(val.E1 == null); } } } " + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @"System.Action`1[System.Int32] 1 True - 1 - - null - -- 11 -- -- null --"); var c = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C"); var m1Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M1").ReturnType; AssertTestDisplayString(m1Tuple.GetMembers(), "System.Int32 (System.Int32, System.Int64).Item1", "System.Int64 (System.Int32, System.Int64).Item2", "(System.Int32, System.Int64)..ctor(System.Int32 item1, System.Int64 item2)", "void (System.Int32, System.Int64).E1.add", "void (System.Int32, System.Int64).E1.remove", "event System.Action<System.Int32> (System.Int32, System.Int64).E1", "System.Action<System.Int64> (System.Int32, System.Int64)._e2", "event System.Action<System.Int64> (System.Int32, System.Int64).E2", "void (System.Int32, System.Int64).E2.add", "void (System.Int32, System.Int64).E2.remove", "void (System.Int32, System.Int64).RaiseE1()", "void (System.Int32, System.Int64).RaiseE2()", "void (System.Int32, System.Int64).Test((System.Int32, System.Int64) val, System.Action<System.Int32> d)", "(System.Int32, System.Int64)..ctor()"); AssertTupleTypeEquality(m1Tuple); Assert.Equal(new string[] { "Item1", "Item2", ".ctor", "add_E1", "remove_E1", "E1", "_e2", "E2", "add_E2", "remove_E2", "RaiseE1", "RaiseE2", "Test" }, m1Tuple.MemberNames.ToArray()); Assert.Equal("event System.Action<System.Int32> (System.Int32, System.Int64).E1", m1Tuple.GetEarlyAttributeDecodingMembers("E1").Single().ToTestDisplayString()); Assert.Equal("event System.Action<System.Int64> (System.Int32, System.Int64).E2", m1Tuple.GetEarlyAttributeDecodingMembers("E2").Single().ToTestDisplayString()); var m2Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M2").ReturnType; var m3Tuple = (NamedTypeSymbol)c.GetMember<MethodSymbol>("M3").ReturnType; AssertTupleTypeMembersEquality(m1Tuple, m2Tuple); AssertTupleTypeMembersEquality(m1Tuple, m3Tuple); var m1E1 = m1Tuple.GetMember<EventSymbol>("E1"); var m1E1Add = m1Tuple.GetMember<MethodSymbol>("add_E1"); var m1E1Remove = m1Tuple.GetMember<MethodSymbol>("remove_E1"); Assert.Equal(SymbolKind.Event, m1E1.Kind); Assert.NotSame(m1E1, m1E1.OriginalDefinition); Assert.Equal("event System.Action<System.Int32> (System.Int32, System.Int64).E1", m1E1.ToTestDisplayString()); Assert.Equal("event System.Action<T1> (T1, T2).E1", m1E1.OriginalDefinition.ToTestDisplayString()); Assert.True(m1E1.Equals(m1E1)); Assert.Equal("event System.Action<System.Int32> (System.Int32, System.Int64).E1", m1E1.ToTestDisplayString()); Assert.Same(m1Tuple, m1E1.ContainingSymbol); Assert.True(m1E1.GetAttributes().IsEmpty); Assert.Null(m1E1.GetUseSiteDiagnostic()); Assert.True(m1E1.DeclaringSyntaxReferences.SequenceEqual(m1E1.DeclaringSyntaxReferences, SyntaxReferenceEqualityComparer.Instance)); Assert.False(m1E1.IsImplicitlyDeclared); Assert.True(m1E1Add.Equals(m1E1.AddMethod, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1Remove.Equals(m1E1.RemoveMethod, TypeCompareKind.ConsiderEverything)); Assert.False(m1E1.IsExplicitInterfaceImplementation); Assert.True(m1E1.ExplicitInterfaceImplementations.IsEmpty); Assert.Null(m1E1.OverriddenEvent); Assert.True(m1E1.Equals(m1E1Add.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1Add.IsImplicitlyDeclared); Assert.True(m1E1.Equals(m1E1Remove.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1Remove.IsImplicitlyDeclared); var m1E1BackingField = m1E1.AssociatedField; Assert.Equal("System.Action<System.Int32> (System.Int32, System.Int64).E1", m1E1BackingField.ToTestDisplayString()); Assert.Same(m1Tuple, m1E1BackingField.ContainingSymbol); Assert.True(m1E1.Equals(m1E1BackingField.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.True(m1E1BackingField.IsImplicitlyDeclared); Assert.True(m1E1BackingField.TupleUnderlyingField.IsImplicitlyDeclared); var m1E2 = m1Tuple.GetMember<EventSymbol>("E2"); var m1E2Add = m1Tuple.GetMember<MethodSymbol>("add_E2"); var m1E2Remove = m1Tuple.GetMember<MethodSymbol>("remove_E2"); Assert.Equal(SymbolKind.Event, m1E2.Kind); Assert.Equal("event System.Action<System.Int64> (System.Int32, System.Int64).E2", m1E2.ToTestDisplayString()); Assert.Equal("event System.Action<T2> (T1, T2).E2", m1E2.OriginalDefinition.ToTestDisplayString()); Assert.Same(m1Tuple, m1E2.ContainingSymbol); Assert.True(m1E2.GetAttributes().IsEmpty); Assert.Null(m1E2.GetUseSiteDiagnostic()); Assert.True(m1E2.DeclaringSyntaxReferences.SequenceEqual(m1E2.DeclaringSyntaxReferences, SyntaxReferenceEqualityComparer.Instance)); Assert.False(m1E2.IsImplicitlyDeclared); Assert.NotSame(m1E2Add, m1E2.AddMethod); Assert.True(m1E2Add.Equals(m1E2.AddMethod, TypeCompareKind.ConsiderEverything)); Assert.NotSame(m1E2Remove, m1E2.RemoveMethod); Assert.True(m1E2Remove.Equals(m1E2.RemoveMethod, TypeCompareKind.ConsiderEverything)); Assert.False(m1E2.IsExplicitInterfaceImplementation); Assert.True(m1E2.ExplicitInterfaceImplementations.IsEmpty); Assert.Null(m1E2.OverriddenEvent); Assert.Null(m1E2.AssociatedField); Assert.NotSame(m1E2, m1E2Add.AssociatedSymbol); Assert.True(m1E2.Equals(m1E2Add.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1E2Add.IsImplicitlyDeclared); Assert.NotSame(m1E2, m1E2Remove.AssociatedSymbol); Assert.True(m1E2.Equals(m1E2Remove.AssociatedSymbol, TypeCompareKind.ConsiderEverything)); Assert.False(m1E2Remove.IsImplicitlyDeclared); } [Fact] public void EventsAsMembers_02() { var source = @" class C { static void Main() { var v1 = M1(); v1.E1(); } static (int, long) M1() { return (1, 11); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; this.E1 = null; this.E1(); } public event System.Action E1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,12): error CS0070: The event '(int, long).E1' can only appear on the left hand side of += or -= (except when used from within the type '(int, long)') // v1.E1(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("(int, long).E1", "(int, long)").WithLocation(7, 12) ); } [Fact] public void TupleTypeWithPatternIs() { var source = @" class C { void Match(object o) { if (o is (int, int) t) { } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,19): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (o is (int, int) t) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(6, 19), // (6,24): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // if (o is (int, int) t) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(6, 24), // (6,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // if (o is (int, int) t) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int, int)").WithArguments("object", "2").WithLocation(6, 18) ); } [Fact] public void TupleAsStatement() { var source = @" class C { void M(int x) { (x, x); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (x, x); Diagnostic(ErrorCode.ERR_IllegalStatement, "(x, x)").WithLocation(6, 9) ); } [Fact] public void TupleTypeWithPatternIs2() { var source = @" class C { void Match(object o) { if (o is (int a, int b)) { } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // if (o is (int a, int b)) { } Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(int a, int b)").WithArguments("object", "Deconstruct").WithLocation(6, 18), // (6,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // if (o is (int a, int b)) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int a, int b)").WithArguments("object", "2").WithLocation(6, 18) ); } [Fact] public void TupleDeclarationWithPatternIs() { var source = @" class C { void Match(object o) { if (o is (1, 2)) { } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // if (o is (1, 2)) { } Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(6, 18), // (6,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // if (o is (1, 2)) { } Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(6, 18) ); } [Fact] public void TupleTypeWithPatternSwitch() { var source = @" class C { void Match(object o) { switch(o) { case (int, int) tuple: return; } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,19): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // case (int, int) tuple: return; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(7, 19), // (7,24): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // case (int, int) tuple: return; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(7, 24), // (7,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (int, int) tuple: return; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int, int)").WithArguments("object", "2").WithLocation(7, 18) ); } [Fact] public void TupleLiteralWithPatternSwitch() { var source = @" class C { void Match(object o) { switch(o) { case (1, 1): return; } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 1): return; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 1)").WithArguments("object", "Deconstruct").WithLocation(7, 18), // (7,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 1): return; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 1)").WithArguments("object", "2").WithLocation(7, 18) ); } [Fact] public void TupleLiteralWithPatternSwitch2() { var source = @" class C { void Match(object o) { switch(o) { case (1, 1) t: return; } } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // case (1, 1) t: return; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 1)").WithArguments("object", "Deconstruct").WithLocation(7, 18), // (7,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type. // case (1, 1) t: return; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 1)").WithArguments("object", "2").WithLocation(7, 18) ); } [Fact] public void TupleAsStatement2() { var source = @" class C { void M() { (1, 1); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (1, 1); Diagnostic(ErrorCode.ERR_IllegalStatement, "(1, 1)").WithLocation(6, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/11282 + https://github.com/dotnet/roslyn/issues/11291")] [WorkItem(11282, "https://github.com/dotnet/roslyn/issues/11282")] [WorkItem(11291, "https://github.com/dotnet/roslyn/issues/11291")] public void TargetTyping_01() { var source = @" class C { static void Main() { var x0 = new {tuple = (null, null)}; System.Console.WriteLine(x0.ToString()); System.ValueType x1 = (null, ""1""); } [TestAttribute((null, ""2""))] [TestAttribute((3, ""3""))] [TestAttribute(Val = (null, ""4""))] [TestAttribute(Val = (5, ""5""))] static void AttributeTarget1(){} async System.Threading.Tasks.Task AsyncTest() { await (null, ""6""); await (7, ""7""); } static void Default((int, string) val1 = (8, null), (int, string) val2 = (9, ""9""), (int, string) val3 = (""10"", ""10"")) {} [TestAttribute((""11"", ""11""))] [TestAttribute(Val = (""12"", ""12""))] static void AttributeTarget2(){} enum TestEnum { V1 = (13, null), V2 = (14, ""14""), V3 = (""15"", ""15""), } static void Test2() { var x = (16, (16 , null)); System.Console.WriteLine(x); var u = __refvalue((17, null), (int, string)); var v = __refvalue((18, ""18""), (int, string)); var w = __refvalue((""19"", ""19""), (int, string)); } } class TestAttribute : System.Attribute { public TestAttribute() {} public TestAttribute((int, string) val) {} public (int, string) Val {get; set;} } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, references: new[] { SystemRef }); comp.VerifyDiagnostics( // (6,32): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // var x0 = new {tuple = (null, null)}; Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(6, 32), // (6,38): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // var x0 = new {tuple = (null, null)}; Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(6, 38), // (8,31): error CS8330: Cannot implicitly convert tuple expression to 'ValueType' // System.ValueType x1 = (null, "1"); Diagnostic(ErrorCode.Unknown, @"(null, ""1"")").WithArguments("System.ValueType").WithLocation(8, 31), // (11,20): error CS1503: Argument 1: cannot convert from '<tuple>' to '(int, string)' // [TestAttribute((null, "2"))] Diagnostic(ErrorCode.ERR_BadArgType, @"(null, ""2"")").WithArguments("1", "<tuple>", "(int, string)").WithLocation(11, 20), // (12,6): error CS0181: Attribute constructor parameter 'val' has type '(int, string)', which is not a valid attribute parameter type // [TestAttribute((3, "3"))] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "TestAttribute").WithArguments("val", "(int, string)").WithLocation(12, 6), // (13,20): error CS0655: 'Val' is not a valid named attribute argument because it is not a valid attribute parameter type // [TestAttribute(Val = (null, "4"))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "Val").WithArguments("Val").WithLocation(13, 20), // (14,20): error CS0655: 'Val' is not a valid named attribute argument because it is not a valid attribute parameter type // [TestAttribute(Val = (5, "5"))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "Val").WithArguments("Val").WithLocation(14, 20), // (19,16): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // await (null, "6"); Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(19, 16), // (20,9): error CS1061: '(int, string)' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // await (7, "7"); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, @"await (7, ""7"")").WithArguments("(int, string)", "GetAwaiter").WithLocation(20, 9), // (23,46): error CS1736: Default parameter value for 'val1' must be a compile-time constant // static void Default((int, string) val1 = (8, null), Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(8, null)").WithArguments("val1").WithLocation(23, 46), // (24,46): error CS1736: Default parameter value for 'val2' must be a compile-time constant // (int, string) val2 = (9, "9")) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"(9, ""9"")").WithArguments("val2").WithLocation(24, 46), // (25,46): error CS1736: Default parameter value for 'val3' must be a compile-time constant // (int, string) val3 = ("10", "10")) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"(""10"", ""10"")").WithArguments("val3").WithLocation(25, 46), // (28,20): error CS1503: Argument 1: cannot convert from '<tuple>' to '(int, string)' // [TestAttribute(("11", "11"))] Diagnostic(ErrorCode.ERR_BadArgType, @"(""11"", ""11"")").WithArguments("1", "<tuple>", "(int, string)").WithLocation(28, 20), // (29,20): error CS0655: 'Val' is not a valid named attribute argument because it is not a valid attribute parameter type // [TestAttribute(Val = ("12", "12"))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "Val").WithArguments("Val").WithLocation(29, 20), // (34,14): error CS8330: Cannot implicitly convert tuple expression to 'int' // V1 = (13, null), Diagnostic(ErrorCode.Unknown, "(13, null)").WithArguments("int").WithLocation(34, 14), // (35,14): error CS8330: Cannot implicitly convert tuple expression to 'int' // V2 = (14, "14"), Diagnostic(ErrorCode.Unknown, @"(14, ""14"")").WithArguments("int").WithLocation(35, 14), // (36,14): error CS8330: Cannot implicitly convert tuple expression to 'int' // V3 = ("15", "15"), Diagnostic(ErrorCode.Unknown, @"(""15"", ""15"")").WithArguments("int").WithLocation(36, 14), // (41,28): error CS8129: Type of the tuple element cannot be inferred from '<null>'. // var x = (16, (16 , null)); Diagnostic(ErrorCode.Unknown, "null").WithArguments("<null>").WithLocation(41, 28), // (44,17): error CS8330: Cannot implicitly convert tuple expression to 'TypedReference' // var u = __refvalue((17, null), (int, string)); Diagnostic(ErrorCode.Unknown, "__refvalue((17, null), (int, string))").WithArguments("System.TypedReference").WithLocation(44, 17), // (45,17): error CS8330: Cannot implicitly convert tuple expression to 'TypedReference' // var v = __refvalue((18, "18"), (int, string)); Diagnostic(ErrorCode.Unknown, @"__refvalue((18, ""18""), (int, string))").WithArguments("System.TypedReference").WithLocation(45, 17), // (46,17): error CS8330: Cannot implicitly convert tuple expression to 'TypedReference' // var w = __refvalue(("19", "19"), (int, string)); Diagnostic(ErrorCode.Unknown, @"__refvalue((""19"", ""19""), (int, string))").WithArguments("System.TypedReference").WithLocation(46, 17) ); } [Fact] public void TargetTyping_02() { var source = @" class C { static void Print<T>(T val) { System.Console.WriteLine($""{typeof(T)} - {val.ToString()}""); } static void Main() { var x0 = new {tuple = (1, ""s"")}; Print(x0.tuple); System.ValueType x1 = (2, ""s""); Print(x1); (int, (int, string)) x2 = (3, (3 , null)); Print(x2); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.ValueTuple`2[System.Int32,System.String] - {1, s} System.ValueType - {2, s} System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.String]] - {3, {3, }} "); } [Fact] public void TargetTyping_03() { var source = @" class Class { void Method() { tuple = (1, ""hello""); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,31): error CS0103: The name 'tuple' does not exist in the current context // class Class { void Method() { tuple = (1, "hello"); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "tuple").WithArguments("tuple").WithLocation(2, 31) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal(@"(1, ""hello"")", node.ToString()); var typeInfo = model.GetTypeInfo(node); Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.String)", typeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind); } [Fact] public void MissingUnderlyingType() { string source = @" class C { void M() { (int, int) x = (1, 1); } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = (INamedTypeSymbol)((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; Assert.True(xSymbol.IsTupleType); Assert.Equal("(System.Int32, System.Int32)[missing]", xSymbol.ToTestDisplayString()); Assert.Null(xSymbol.TupleUnderlyingType); Assert.True(xSymbol.IsErrorType()); Assert.True(xSymbol.IsReferenceType); AssertEx.Equal(new[] { "System.Int32 (System.Int32, System.Int32)[missing].Item1", "System.Int32 (System.Int32, System.Int32)[missing].Item2" }, ((ErrorTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembersUnordered().ToTestDisplayStrings().ToImmutableArray().Sort()); AssertEx.Equal("System.Int32 (System.Int32, System.Int32)[missing].Item1", ((NamedTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembers("Item1").Single().ToTestDisplayString()); } [Fact] public void MissingUnderlyingType_WithNames() { string source = @" class C { void M() { (int a, int b) x = (1, 1); } } "; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = (INamedTypeSymbol)((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; Assert.True(xSymbol.IsTupleType); Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", xSymbol.ToTestDisplayString()); Assert.True(xSymbol.TupleUnderlyingType.IsErrorType()); Assert.True(xSymbol.IsErrorType()); Assert.True(xSymbol.IsReferenceType); AssertEx.Equal(new[] { "System.Int32 (System.Int32 a, System.Int32 b)[missing].a", "System.Int32 (System.Int32 a, System.Int32 b)[missing].b", "System.Int32 (System.Int32 a, System.Int32 b)[missing].Item1", "System.Int32 (System.Int32 a, System.Int32 b)[missing].Item2" }, ((ErrorTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembersUnordered().ToTestDisplayStrings().ToImmutableArray().Sort()); AssertEx.Equal("System.Int32 (System.Int32 a, System.Int32 b)[missing].Item1", ((NamedTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembers("Item1").Single().ToTestDisplayString()); AssertEx.Equal("System.Int32 (System.Int32 a, System.Int32 b)[missing].a", ((NamedTypeSymbol)((Symbols.PublicModel.ErrorTypeSymbol)xSymbol).UnderlyingSymbol).GetMembers("a").Single().ToTestDisplayString()); } [Fact, CompilerTrait(CompilerFeature.LocalFunctions)] public void LocalFunction() { var source = @" class C { static void Main() { (int, int) Local((int, int) x) { return x; } System.Console.WriteLine(Local((1, 2))); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, 2)"); comp.VerifyDiagnostics(); } [Fact] public void LocalFunctionWithNamedTuple() { var source = @" class C { static void Main() { (int a, int b) Local((int c, int d) x) { return x; } System.Console.WriteLine(Local((d: 1, c: 2)).b); } } "; var comp = CompileAndVerify(source, expectedOutput: "2"); comp.VerifyDiagnostics( // (7,41): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(int c, int d)'. // System.Console.WriteLine(Local((d: 1, c: 2)).b); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 1").WithArguments("d", "(int c, int d)").WithLocation(7, 41), // (7,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int c, int d)'. // System.Console.WriteLine(Local((d: 1, c: 2)).b); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 2").WithArguments("c", "(int c, int d)").WithLocation(7, 47) ); } [Fact, CompilerTrait(CompilerFeature.LocalFunctions)] public void LocalFunctionWithLongTuple() { var source = @" class C { static void Main() { (int, string, int, string, int, string, int, string) Local((int, string, int, string, int, string, int, string) x) { return x; } System.Console.WriteLine(Local((1, ""Alice"", 2, ""Brenda"", 3, ""Chloe"", 4, ""Dylan""))); } } "; var comp = CompileAndVerify(source, expectedOutput: "(1, Alice, 2, Brenda, 3, Chloe, 4, Dylan)"); comp.VerifyDiagnostics(); } [Fact] public void TupleMembersInLambda() { var source = @" using System; class C { static Action action; static void Main() { var tuple = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8); action += () => { Console.Write(tuple.Item1 + "" "" + tuple.a + "" "" + tuple.Rest + "" "" + tuple.Item8 + "" "" + tuple.h); }; action(); } } "; var comp = CompileAndVerify(source, expectedOutput: "1 1 (8) 8 8"); comp.VerifyDiagnostics(); } [Fact] public void LongTupleConstructor() { var source = @" class C { void M() { var x = new (int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8); var y = new (int, int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8, 9); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var x = new (int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int, int, int, int, int, int, int)").WithLocation(6, 21), // (7,21): error CS8181: 'new' cannot be used with tuple type. Use a tuple literal expression instead. // var y = new (int, int, int, int, int, int, int, int, int)(1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.ERR_NewWithTupleTypeSyntax, "(int, int, int, int, int, int, int, int, int)").WithLocation(7, 21) ); } [Fact] public void TupleWithDynamicInSeparateCompilations() { var lib_cs = @" public class C { public static (dynamic, dynamic) M((dynamic, dynamic) x) { return x; } } "; var source = @" class D { static void Main() { var x = C.M((1, ""hello"")); x.Item1.DynamicMethod1(); x.Item2.DynamicMethod2(); } } "; var libComp = CreateCompilation(lib_cs, assemblyName: "lib"); libComp.VerifyDiagnostics(); var comp1 = CreateCompilation(source, references: new[] { libComp.ToMetadataReference() }); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] [WorkItem(11322, "https://github.com/dotnet/roslyn/issues/11322")] public void LiteralsAndAmbiguousVT_01() { var source = @" class C3 { public static void Main() { var x = (1, 1); System.Console.WriteLine(x.GetType().Assembly); } } "; var comp1 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp1"); var comp2 = CreateCompilationWithMscorlib40(trivial2uple, assemblyName: "comp2"); var comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); comp = CreateCompilationWithMscorlib40(source, references: new[] { comp2.ToMetadataReference(), comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,17): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // var x = (1, 1); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 17) ); comp = CreateCompilationWithMscorlib40(source, references: new[] { comp2.ToMetadataReference(ImmutableArray.Create("alias")), comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [Fact] [WorkItem(11322, "https://github.com/dotnet/roslyn/issues/11322")] public void LiteralsAndAmbiguousVT_02() { var source1 = trivial2uple; var source2 = @" public static class C2 { public static void M1(this string x, (int, string) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source3 = @" class C3 { public static void Main() { ""x"".M1((1, null)); } } "; var comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,16): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) ); comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference().WithAliases(ImmutableArray.Create("alias")), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); var source4 = @" extern alias alias1; using alias1; class C3 { public static void Main() { ""x"".M1((1, null)); } } "; comp = CreateCompilationWithMscorlib40(source4, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); } [Fact] [WorkItem(11322, "https://github.com/dotnet/roslyn/issues/11322")] public void LongLiteralsAndAmbiguousVT_02() { var source1 = trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; var source2 = @" public static class C2 { public static void M1(this string x, (int, string, int, string, int, string, int, string, int, string) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + trivial3uple + trivialRemainingTuples + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source3 = @" class C3 { public static void Main() { ""x"".M1((1, null, 1, null, 1, null, 1, null, 1, null)); } } "; var comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,16): error CS8356: Predefined type 'System.ValueTuple`3' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null, 1, null, 1, null, 1, null, 1, null)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`3", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16), // (6,16): error CS8356: Predefined type 'System.ValueTuple`8' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // "x".M1((1, null, 1, null, 1, null, 1, null, 1, null)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, null, 1, null, 1, null, 1, null, 1, null)").WithArguments("System.ValueTuple`8", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 16) ); comp = CreateCompilationWithMscorlib40(source3, references: new[] { comp1.ToMetadataReference().WithAliases(ImmutableArray.Create("alias")), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); var source4 = @" extern alias alias1; using alias1; class C3 { public static void Main() { ""x"".M1((1, null, 1, null, 1, null, 1, null, 1, null)); } } "; comp = CreateCompilationWithMscorlib40(source4, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); } [Fact] [WorkItem(11323, "https://github.com/dotnet/roslyn/issues/11323")] public void ExactlyMatchingExpression() { var source1 = @" namespace NS1 { public static class C1 { public static void M1(this string x, (int, int) y) { System.Console.WriteLine(""C1.M1""); } } } "; var source2 = @" namespace NS2 { public static class C2 { public static void M1(this string x, (int, int) y) { System.Console.WriteLine(""C2.M1""); } } } "; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, references: s_valueTupleRefs, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, references: s_valueTupleRefs, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source3 = @" extern alias alias1; using alias1::NS2; using NS1; class C3 { public static void Main() { ""x"".M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib40(source3, references: s_valueTupleRefs.Concat(new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }), parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,13): error CS0121: The call is ambiguous between the following methods or properties: 'NS2.C2.M1(string, (int, int))' and 'NS1.C1.M1(string, (int, int))' // "x".M1((1, 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("NS2.C2.M1(string, (int, int))", "NS1.C1.M1(string, (int, int))").WithLocation(10, 13) ); var source4 = @" using NS1; class C3 { public static void Main() { ""x"".M1((1, 1)); } } "; comp = CreateCompilationWithMscorlib40(source4, references: s_valueTupleRefs.Concat(new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }), parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1.M1"); var source5 = @" extern alias alias1; using alias1::NS2; class C3 { public static void Main() { ""x"".M1((1, 1)); } } "; comp = CreateCompilationWithMscorlib40(source5, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")), ValueTupleRef, SystemRuntimeFacadeRef }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2.M1"); } [Fact] public void MultipleVT_01() { var source1 = @" public class C1 { public void M1((int, int) y) { System.Console.WriteLine(""C1.M1""); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public void M1((int, int) y) { System.Console.WriteLine(""C2.M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source = @" extern alias alias1; class C3 { public static void Main() { new C1().M1((1, 1)); new alias1::C2().M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib46(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"C1.M1 C2.M1"); } [Fact] [WorkItem(11325, "https://github.com/dotnet/roslyn/issues/11325")] public void MultipleVT_02() { var source1 = @" public class C1 { public (int, int) M2() { System.Console.WriteLine(""C1.M2""); return (1, 1); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public class C2 { public void M3((int, int) y) { System.Console.WriteLine(""C2.M3""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1"); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2"); comp2.VerifyDiagnostics(); var source = @" extern alias alias1; class C3 { public static void Main() { new alias1::C2().M3(new C1().M2()); } } "; var comp = CreateCompilation(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference().WithAliases(ImmutableArray.Create("alias1")) }, parseOptions: TestOptions.Regular, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"C1.M2 C2.M3"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/11326")] [WorkItem(11326, "https://github.com/dotnet/roslyn/issues/11326")] public void GetTypeInfo_01() { var source = @" class C { static void Main() { var x1 = ((short, string))(1, ""hello""); var x2 = ((short, string))(2, null); var x3 = (short)11; var x4 = (string)null; var x5 = (System.Func<int>)(() => 12); } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); //comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var n1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal(@"(1, ""hello"")", n1.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(n1)); var n2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(2, null)", n2.ToString()); Assert.Null(model.GetTypeInfo(n2).Type); Assert.Null(model.GetTypeInfo(n2).ConvertedType); Assert.Equal(Conversion.Identity, model.GetConversion(n2)); var n3 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(4); Assert.Equal(@"11", n3.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(n3).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(n3).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, model.GetConversion(n3)); var n4 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(5); Assert.Equal(@"null", n4.ToString()); Assert.Null(model.GetTypeInfo(n4).Type); Assert.Null(model.GetTypeInfo(n4).ConvertedType); Assert.Equal(Conversion.Identity, model.GetConversion(n4)); var n5 = nodes.OfType<LambdaExpressionSyntax>().Single(); Assert.Equal(@"() => 12", n5.ToString()); Assert.Null(model.GetTypeInfo(n5).Type); Assert.Equal("System.Func<System.Int32>", model.GetTypeInfo(n5).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.AnonymousFunction, model.GetConversion(n5).Kind); } [Fact] [WorkItem(11326, "https://github.com/dotnet/roslyn/issues/11326")] public void GetTypeInfo_02() { var source = @" class C { static void Main() { (short, string) x1 = (1, ""hello""); (short, string) x2 = (2, null); short x3 = 11; string x4 = null; System.Func<int> x5 = () => 12; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); //comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var n1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal(@"(1, ""hello"")", n1.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).Type.ToTestDisplayString()); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n1).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n1).Kind); var n2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(2, null)", n2.ToString()); Assert.Null(model.GetTypeInfo(n2).Type); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n2).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n2).Kind); var n3 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(4); Assert.Equal(@"11", n3.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(n3).Type.ToTestDisplayString()); Assert.Equal("System.Int16", model.GetTypeInfo(n3).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(n3).Kind); var n4 = nodes.OfType<LiteralExpressionSyntax>().ElementAt(5); Assert.Equal(@"null", n4.ToString()); Assert.Null(model.GetTypeInfo(n4).Type); Assert.Equal("System.String", model.GetTypeInfo(n4).ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitReference, model.GetConversion(n4)); var n5 = nodes.OfType<LambdaExpressionSyntax>().Single(); Assert.Equal(@"() => 12", n5.ToString()); Assert.Null(model.GetTypeInfo(n5).Type); Assert.Equal("System.Func<System.Int32>", model.GetTypeInfo(n5).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.AnonymousFunction, model.GetConversion(n5).Kind); } [Fact] [WorkItem(36185, "https://github.com/dotnet/roslyn/issues/36185")] public void GetTypeInfo_03() { var source = @" class C { static void Main() { M((1, ""hello"")); M((2, null)); } public static void M((short, string) x) { } } " + trivial2uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var n1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal(@"(1, ""hello"")", n1.ToString()); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(n1).Type.ToTestDisplayString()); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n1).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n1).Kind); var n2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal(@"(2, null)", n2.ToString()); Assert.Null(model.GetTypeInfo(n2).Type); Assert.Equal("(System.Int16, System.String)", model.GetTypeInfo(n2).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(n2).Kind); } [Fact] [WorkItem(14600, "https://github.com/dotnet/roslyn/issues/14600")] public void GetSymbolInfo_01() { var source = @" class C { static void Main() { // error is intentional. GetSymbolInfo should still work DummyType x1 = (Alice: 1, ""hello""); var Alice = x1.Alice; } } " + trivial2uple + trivial3uple + tupleattributes_cs; var tree = Parse(source, options: TestOptions.Regular); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var nc = nodes.OfType<NameColonSyntax>().ElementAt(0); var sym = model.GetSymbolInfo(nc.Name); Assert.Equal(SymbolKind.Field, sym.Symbol.Kind); Assert.Equal("Alice", sym.Symbol.Name); Assert.Equal(nc.Name.GetLocation(), sym.Symbol.Locations[0]); } [Fact] public void GetSymbolInfo_WithInferredName() { var source = @" class C { static void Main() { string Bob = ""hello""; var x1 = (Alice: 1, Bob); var Alice = x1.Alice; var BobCopy = x1.Bob; } } "; var tree = Parse(source, options: TestOptions.Regular7_1); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1Bob = nodes.OfType<MemberAccessExpressionSyntax>().ElementAt(1); Assert.Equal("x1.Bob", x1Bob.ToString()); var x1Symbol = model.GetSymbolInfo(x1Bob.Expression).Symbol as ILocalSymbol; Assert.Equal("(System.Int32 Alice, System.String Bob)", x1Symbol.Type.ToTestDisplayString()); var bobField = x1Symbol.Type.GetMember("Bob"); Assert.Equal(SymbolKind.Field, bobField.Kind); var secondElement = nodes.OfType<TupleExpressionSyntax>().First().Arguments[1]; Assert.Equal(secondElement.GetLocation(), bobField.Locations[0]); } [Fact] [WorkItem(23651, "https://github.com/dotnet/roslyn/issues/23651")] public void GetSymbolInfo_WithDuplicateInferredName() { var source = @" class C { static object M(string Bob) { var x1 = (Bob, Bob); return x1; } } "; var tree = Parse(source, options: TestOptions.Regular7_1); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = nodes.OfType<VariableDeclaratorSyntax>().Single(); Assert.Equal("x1 = (Bob, Bob)", x1.ToString()); var x1Symbol = (ILocalSymbol)model.GetDeclaredSymbol(x1); Assert.Equal("(System.String, System.String) x1", x1Symbol.ToTestDisplayString()); Assert.True(x1Symbol.Type.GetSymbol().TupleElementNames.IsDefault); } [Fact] public void CompileTupleLib() { string additionalSource = @" namespace System { public class SR { public static string ArgumentException_ValueTupleIncorrectType { get { return """"; } } public static string ArgumentException_ValueTupleLastArgumentNotAValueTuple { get { return """"; } } } } namespace System.Diagnostics { public static class Debug { public static void Assert(bool condition) { } public static void Assert(bool condition, string message) { } } } "; var tupleComp = CreateCompilationWithMscorlib40( tuplelib_cs + tupleattributes_cs + additionalSource); tupleComp.VerifyDiagnostics(); var source = @" class C { static void Main() { var x = (1, 2); System.Console.WriteLine(x.ToString()); } } "; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "(1, 2)", references: new[] { tupleComp.ToMetadataReference() }); comp.VerifyDiagnostics(); } [Fact] public void ImplicitConversions01() { var source = @" using System; class C { static void Main() { // long tuple var x1 = (1,2,3,4,5,6,7,8,9,10,11,12); (long, long, long, long, long, long, long, long,long, long, long, long) y1 = x1; System.Console.WriteLine(y1); // long nested tuple var x2 = (1,2,3,4,5,6,7,8,9,10,11,(1,2,3,4,5,6,7,8,9,10,11,12)); (long, long, long, long, long, long, long, long,long, long, long, (long, long, long, long, long, long, long, long,long, long, long, long)) y2 = x2; System.Console.WriteLine(y2); // user defined conversion var x3 = (1,1); C1 y3 = x3; x3 = y3; System.Console.WriteLine(x3); } class C1 { static public implicit operator C1((long, long) arg) { return new C1(); } static public implicit operator (byte, byte)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, expectedOutput: @" (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) (2, 2) "); } [Fact] public void ExplicitConversions01() { var source = @" using System; class C { static void Main() { // long tuple var x1 = (1,2,3,4,5,6,7,8,9,10,11,12); (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte) y1 = ((byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte))x1; System.Console.WriteLine(y1); // long nested tuple var x2 = (1,2,3,4,5,6,7,8,9,10,11,(1,2,3,4,5,6,7,8,9,10,11,12)); (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte)) y2 = ((byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, (byte, byte, byte, byte, byte, byte, byte, byte,byte, byte, byte, byte)))x2; System.Console.WriteLine(y2); // user defined conversion var x3 = (1,1); C1 y3 = (C1)x3; x3 = ((int, int))y3; System.Console.WriteLine(x3); } class C1 { static public explicit operator C1((long, long) arg) { return new C1(); } static public explicit operator (byte, byte)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, expectedOutput: @" (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) (2, 2) "); } [Fact] public void ImplicitConversions02() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = x; x = y; System.Console.WriteLine(x); x = ((int, int))(C1)x; System.Console.WriteLine(x); } class C1 { static public implicit operator C1((long, long) arg) { return new C1(); } static public implicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2)"); comp.VerifyIL("C.Main", @" { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<byte, byte> V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0015: conv.i8 IL_0016: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_001b: call ""C.C1 C.C1.op_Implicit(System.ValueTuple<long, long>)"" IL_0020: call ""System.ValueTuple<byte, byte> C.C1.op_Implicit(C.C1)"" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_002c: ldloc.1 IL_002d: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_0032: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0037: dup IL_0038: box ""System.ValueTuple<int, int>"" IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0050: conv.i8 IL_0051: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_0056: call ""C.C1 C.C1.op_Implicit(System.ValueTuple<long, long>)"" IL_005b: call ""System.ValueTuple<byte, byte> C.C1.op_Implicit(C.C1)"" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_0067: ldloc.1 IL_0068: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_006d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0072: box ""System.ValueTuple<int, int>"" IL_0077: call ""void System.Console.WriteLine(object)"" IL_007c: ret } "); ; } [Fact] public void ExplicitConversions02() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = (C1)x; x = ((int a, int b))y; System.Console.WriteLine(x); x = ((int, int))(C1)x; System.Console.WriteLine(x); } class C1 { static public explicit operator C1((long, long) arg) { return new C1(); } static public explicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2)"); comp.VerifyIL("C.Main", @" { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<byte, byte> V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0015: conv.i8 IL_0016: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_001b: call ""C.C1 C.C1.op_Explicit(System.ValueTuple<long, long>)"" IL_0020: call ""System.ValueTuple<byte, byte> C.C1.op_Explicit(C.C1)"" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_002c: ldloc.1 IL_002d: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_0032: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0037: dup IL_0038: box ""System.ValueTuple<int, int>"" IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0050: conv.i8 IL_0051: newobj ""System.ValueTuple<long, long>..ctor(long, long)"" IL_0056: call ""C.C1 C.C1.op_Explicit(System.ValueTuple<long, long>)"" IL_005b: call ""System.ValueTuple<byte, byte> C.C1.op_Explicit(C.C1)"" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld ""byte System.ValueTuple<byte, byte>.Item1"" IL_0067: ldloc.1 IL_0068: ldfld ""byte System.ValueTuple<byte, byte>.Item2"" IL_006d: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0072: box ""System.ValueTuple<int, int>"" IL_0077: call ""void System.Console.WriteLine(object)"" IL_007c: ret } "); } [Fact] public void ImplicitConversions03() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = x; (int, int)? x1 = y; System.Console.WriteLine(x1); x1 = ((int, int)?)(C1)x; System.Console.WriteLine(x1); } class C1 { static public implicit operator C1((long, long)? arg) { return new C1(); } static public implicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2) "); } [Fact] public void ExplicitConversions03() { var source = @" using System; class C { static void Main() { var x = (a:1, b:1); C1 y = (C1)x; (int, int)? x1 = ((int, int)?)y; System.Console.WriteLine(x1); x1 = ((int, int)?)(C1)x; System.Console.WriteLine(x1); } class C1 { static public explicit operator C1((long, long)? arg) { return new C1(); } static public explicit operator (byte c, byte d)(C1 arg) { return (2, 2); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (2, 2) (2, 2) "); } [Fact] public void ImplicitConversions04() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, (1, 1)))))); C1 y = x; (int, int) x2 = y; System.Console.WriteLine(x2); (int, (int, int)) x3 = y; System.Console.WriteLine(x3); (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))) x12 = y; System.Console.WriteLine(x12); } class C1 { private byte x; static public implicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public implicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public implicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public implicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, 2) (3, (4, 5)) (6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17)))))))))))"); } [Fact] public void ExplicitConversions04Err() { // explicit conversion case similar to ImplicitConversions04 // is a compiler error since explicit tuple conversions do not stack up like // implicit tuple conversions which are in standard implicit set. var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, (1, 1)))))); C1 y = (C1)x; (int, int) x2 = ((int, int))y; System.Console.WriteLine(x2); (int, (int, int)) x3 = ((int, (int, int)))y; System.Console.WriteLine(x3); (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))) x12 = ((int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))))y; System.Console.WriteLine(x12); } class C1 { private byte x; static public explicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public explicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public explicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public explicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (8,16): error CS0030: Cannot convert type '(int, (int, (int, (int, (int, (int, int))))))' to 'C.C1' // C1 y = (C1)x; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C1)x").WithArguments("(int, (int, (int, (int, (int, (int, int))))))", "C.C1").WithLocation(8, 16), // (13,32): error CS0030: Cannot convert type 'C.C1' to '(int, (int, int))' // (int, (int, int)) x3 = ((int, (int, int)))y; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((int, (int, int)))y").WithArguments("C.C1", "(int, (int, int))").WithLocation(13, 32), // (16,96): error CS0030: Cannot convert type 'C.C1' to '(int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int)))))))))))' // (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))) x12 = ((int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))))y; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int))))))))))))y").WithArguments("C.C1", "(int, (int, (int, (int, (int, (int, (int, (int, (int, (int, (int, int)))))))))))").WithLocation(16, 96) ); } [Fact] public void ImplicitConversions05() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = y; System.Console.WriteLine(x1); } class C1 { private byte x; static public implicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public implicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public implicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public implicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, (2, (3, (4, (5, 6))))) "); } [Fact] public void ExplicitConversions05() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = (C1)((int, C1))((int, (int, C1)))((int, (int, (int, C1))))((int, (int, (int, (int, C1)))))x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = ((int, (object, (byte, (int?, (long, IComparable)?))?))?) ((int, (object, (byte, (int?, C1))?))?) ((int, (object, (byte, C1)?))?) ((int, (object, C1))?) ((int, C1)?) (C1)y; System.Console.WriteLine(x1); } class C1 { private byte x; static public explicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public explicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } static public explicit operator (byte, C1)(C1 arg) { return ((byte)(arg.x++), arg); } static public explicit operator (byte c, byte d)(C1 arg) { return ((byte)(arg.x++), (byte)(arg.x++)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, (2, (3, (4, (5, 6))))) "); } [Fact] public void ImplicitConversions05Err() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = y; System.Console.WriteLine(x1); } class C1 { private byte x; static public implicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public implicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,70): error CS0029: Cannot implicitly convert type 'C.C1' to '(int, (object, (byte, (int?, (long, System.IComparable)?))?))?' // (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y").WithArguments("C.C1", "(int, (object, (byte, (int?, (long, System.IComparable)?))?))?").WithLocation(10, 70) ); } [Fact] public void ExplicitConversions05Err() { var source = @" using System; class C { static void Main() { var x = (1, (1, (1, (1, (1, 1))))); C1 y = (C1)((int, C1))((int, (int, C1)))((int, (int, (int, C1))))((int, (int, (int, (int, C1)))))x; (int, (object, (byte, (int?, (long, IComparable)?))?))? x1 = ((int, (object, (byte, (int?, (long, IComparable)?))?))?) ((int, (object, (byte, (int?, C1))?))?) ((int, (object, (byte, C1)?))?) ((int, (object, C1))?) ((int, C1)?) (C1)y; System.Console.WriteLine(x1); } class C1 { private byte x; static public explicit operator C1((long, C1) arg) { var result = new C1(); result.x = arg.Item2.x; return result; } static public explicit operator C1((long, long) arg) { var result = new C1(); result.x = (byte)(arg.Item2); return result; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,70): error CS0030: Cannot convert type 'C.C1' to '(int, C.C1)?' // ((int, C1)?) Diagnostic(ErrorCode.ERR_NoExplicitConv, @"((int, C1)?) (C1)y").WithArguments("C.C1", "(int, C.C1)?").WithLocation(14, 70) ); } [Fact] public void ImplicitConversions06Err() { var source = @" class C { static void Main() { var x = (1, 1); (long, long) y = x; System.Console.WriteLine(y); } } namespace System { // struct with two values (missing a field) public struct ValueTuple<T1, T2> { public T1 Item1; public ValueTuple(T1 item1, T2 item2) => throw null; } } "; var comp = CreateCompilation(source, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (7,26): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (long, long) y = x; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "x").WithArguments("Item2", "(T1, T2)", "ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 26) ); } [Fact] public void ExplicitConversions06Err() { var source = @" class C { static void Main() { var x = (1, 1); (byte, byte) y = ((byte, byte))x; System.Console.WriteLine(y); } } namespace System { // struct with two values (missing a field) public struct ValueTuple<T1, T2> { public T1 Item1; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; } } } "; var comp = CreateCompilation(source, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (7,26): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (byte, byte) y = ((byte, byte))x; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "((byte, byte))x").WithArguments("Item2", "(T1, T2)", "ImplicitConversions06Err, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 26) ); } [Fact] public void ImplicitConversions07() { var source = @" using System; internal class Program { static void Main(string[] args) { var t = (1, 1); (C2, C2) aa = t; System.Console.WriteLine(aa); } // accessibility of operators. Notice Private private class C2 { public static implicit operator C2(int arg) { return new C2(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {Program+C2, Program+C2} "); } [Fact] public void ExplicitConversions07() { var source = @" using System; internal class Program { static void Main(string[] args) { var t = (1, 1); (C2, C2) aa = ((C2, C2))t; System.Console.WriteLine(aa); } // accessibility of operators. Notice Private private class C2 { public static explicit operator C2(int arg) { return new C2(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {Program+C2, Program+C2} "); } [Fact] public void ExplicitConversionsSimple01() { var source = @" using System; class C { static void Main() { var x = (a:1, b:2); var y = ((byte, byte))x; System.Console.WriteLine(y); var z = ((int, int))((long)3, (object)4); System.Console.WriteLine(z); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {1, 2} {3, 4}"); comp.VerifyIL("C.Main", @" { // Code size 65 (0x41) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: conv.u1 IL_000f: ldloc.0 IL_0010: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0015: conv.u1 IL_0016: newobj ""System.ValueTuple<byte, byte>..ctor(byte, byte)"" IL_001b: box ""System.ValueTuple<byte, byte>"" IL_0020: call ""void System.Console.WriteLine(object)"" IL_0025: ldc.i4.3 IL_0026: ldc.i4.4 IL_0027: box ""int"" IL_002c: unbox.any ""int"" IL_0031: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0036: box ""System.ValueTuple<int, int>"" IL_003b: call ""void System.Console.WriteLine(object)"" IL_0040: ret } "); ; } [Fact] public void ExplicitConversionsSimple02() { var source = @" using System; class C { static void Main() { var x = (a:1, b:2); var y = ((C2, C2))x; System.Console.WriteLine(y); var z = ((C2, C2))((object)null, 4); System.Console.WriteLine(z); } private class C2 { private int x; public static explicit operator C2(int arg) { var result = new C2(); result.x = arg + 1; return result; } public override string ToString() { return x.ToString(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" {2, 3} {, 5}"); comp.VerifyIL("C.Main", @" { // Code size 68 (0x44) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: call ""C.C2 C.C2.op_Explicit(int)"" IL_0013: ldloc.0 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0019: call ""C.C2 C.C2.op_Explicit(int)"" IL_001e: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0023: box ""System.ValueTuple<C.C2, C.C2>"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldnull IL_002e: ldc.i4.4 IL_002f: call ""C.C2 C.C2.op_Explicit(int)"" IL_0034: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0039: box ""System.ValueTuple<C.C2, C.C2>"" IL_003e: call ""void System.Console.WriteLine(object)"" IL_0043: ret } "); ; } [Fact] [WorkItem(11804, "https://github.com/dotnet/roslyn/issues/11804")] public void ExplicitConversionsSimple02Expr() { var source = @" class C { static void Main() { var x = (a:1, b:2); var y = ((C2, C2))x; System.Console.WriteLine(y); var z = ((C2, C2))(null, 4); System.Console.WriteLine(z); } private class C2 { private int x; public static explicit operator C2(int arg) { var result = new C2(); result.x = arg + 1; return result; } public override string ToString() { return x.ToString(); } } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" {2, 3} {, 5}"); comp.VerifyIL("C.Main", @" { // Code size 68 (0x44) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000e: call ""C.C2 C.C2.op_Explicit(int)"" IL_0013: ldloc.0 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0019: call ""C.C2 C.C2.op_Explicit(int)"" IL_001e: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0023: box ""System.ValueTuple<C.C2, C.C2>"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldnull IL_002e: ldc.i4.4 IL_002f: call ""C.C2 C.C2.op_Explicit(int)"" IL_0034: newobj ""System.ValueTuple<C.C2, C.C2>..ctor(C.C2, C.C2)"" IL_0039: box ""System.ValueTuple<C.C2, C.C2>"" IL_003e: call ""void System.Console.WriteLine(object)"" IL_0043: ret } "); } [WorkItem(12064, "https://github.com/dotnet/roslyn/issues/12064")] [Fact] public void ExplicitConversionsPreference01() { var source = @" using System; class B { static void Main() { C<int> x = new D<int>(""original""); D<int> y = (D<int>)x; // explicit builtin downcast is preferred Console.WriteLine(""explicit""); Console.WriteLine(y); Console.WriteLine(); y = x; // implicit user defined implicit conversion Console.WriteLine(""implicit""); Console.WriteLine(y); Console.WriteLine(); Console.WriteLine(); (C<int>, C<int>) xt = (new D<int>(""original1""), new D<int>(""original2"")); var xtxt = (xt, xt); Console.WriteLine(""explicit""); (D<int>, D<int>) yt = ((D<int>, D<int>))xt; // explicit builtin downcast is preferred Console.WriteLine(yt); ((D<int>, D<int>),(D<int>, D<int>)) ytyt = (((D<int>, D<int>),(D<int>, D<int>)))(xt, xt); // explicit builtin downcast is preferred Console.WriteLine(ytyt); ytyt = (((D<int>, D<int>),(D<int>, D<int>)))xtxt; // explicit builtin downcast is preferred Console.WriteLine(ytyt); (D<int>, D<int>)? ytn = ((D<int>, D<int>)?)xt; // explicit builtin downcast is preferred (nullable) Console.WriteLine(ytn); Console.WriteLine(); Console.WriteLine(""implicit""); yt = xt; // implicit user defined implicit conversion Console.WriteLine(yt); ytyt = xtxt; // implicit user defined implicit conversion Console.WriteLine(ytyt); ytyt = (xt, xt); // implicit user defined implicit conversion Console.WriteLine(ytyt); ytn = xt; // implicit user defined implicit conversion Console.WriteLine(ytn); } } class C<T> { } class D<T> : C<T> { private readonly string val; public D(string val) { this.val = val; } public override string ToString() { return val; } public static implicit operator D<T>(C<int> x) { return new D<T>(""converted""); } } " + trivial2uple + tupleattributes_cs; var comp = CompileAndVerify(source, expectedOutput: @" explicit original implicit converted explicit {original1, original2} {{original1, original2}, {original1, original2}} {{original1, original2}, {original1, original2}} {original1, original2} implicit {converted, converted} {{converted, converted}, {converted, converted}} {{converted, converted}, {converted, converted}} {converted, converted} "); } [Fact] public void ExplicitConversionsPreference02() { var source = @" using System; class A { public static implicit operator A(int d) { return null; } } class B : A { public static implicit operator B(long d) { return null; } } class C { static void Main() { var x = 1; var xt = (x, x); // implicit conversions are unambiguous B b = x; (B, B) bt = xt; // the following is an error for compat reasons // explicit conversion is ambiguous and implicit conversion exists, but ignored b = (B)x; // SHOULD THIS BE AN ERROR TOO? bt = ((B, B))xt; // SHOULD THIS BE AN ERROR TOO? bt = ((B, B)?)xt; } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ImplicitConversions06Err"); comp.VerifyEmitDiagnostics( // (28,13): error CS0457: Ambiguous user defined conversions 'B.implicit operator B(long)' and 'A.implicit operator A(int)' when converting from 'int' to 'B' // b = (B)x; Diagnostic(ErrorCode.ERR_AmbigUDConv, "(B)x").WithArguments("B.implicit operator B(long)", "A.implicit operator A(int)", "int", "B").WithLocation(28, 13), // (31,14): error CS0030: Cannot convert type '(int, int)' to '(B, B)' // bt = ((B, B))xt; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((B, B))xt").WithArguments("(int, int)", "(B, B)").WithLocation(31, 14), // (34,14): error CS0030: Cannot convert type '(int, int)' to '(B, B)?' // bt = ((B, B)?)xt; Diagnostic(ErrorCode.ERR_NoExplicitConv, "((B, B)?)xt").WithArguments("(int, int)", "(B, B)?").WithLocation(34, 14) ); } [Fact] public void ConversionsOverload02() { var source = @" using System; class C { static void Main() { (long, long) x = (1,1); Test(x); (int, int) y = (1,1); Test(y); Test((1, 1)); } static void Test((long, long) x) { System.Console.WriteLine(""first""); } static void Test((long?, long?) x) { System.Console.WriteLine(""second""); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first first first "); } [Fact] public void ConversionsOverload03() { var source = @" using System; class C { static void Main() { Test((1, 1)); (int, int)? y = (1,1); Test(y); (long, long)? x = (1,1); Test(x); } static void Test((long?, long?)? x) { System.Console.WriteLine(""second""); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" second second second "); } [Fact] public void ConversionsOverload04() { var source = @" using System; class C { static void Main() { Test((1, 1)); (int, int)? y = (1,1); Test(y); (long, long)? x = (1,1); Test(x); } static void Test((long, long) x) { System.Console.WriteLine(""first""); } static void Test((long?, long?)? x) { System.Console.WriteLine(""second""); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" first second second "); } [Fact] public void ConversionsOverload05() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Program { static void Main(string[] args) { Action<IEnumerable> x = null; Action<IEnumerable<int>> x1 = null; // valid and T is IEnumerable<int> // Action<in T> is introducing upper bound on T Test(x, x1); (Action<IEnumerable> x, Action<IEnumerable> y) z = (null, null); (Action<IEnumerable<int>> x, Action<IEnumerable<int>> y) z1 = (null, null); // inference fails // (T, T) is introducing exact bound on T even in an 'in' param position Test(z, z1); // evidently, this is an error. Test<(IEnumerable<int>, IEnumerable <int>)> (z, z1); } public static void Test<T>(Action<T> x, Action<T> y) { System.Console.WriteLine(typeof(T)); } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,9): error CS0411: The type arguments for method 'Program.Test<T>(Action<T>, Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test(z, z1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Test").WithArguments("Program.Test<T>(System.Action<T>, System.Action<T>)").WithLocation(22, 9), // (25,54): error CS1503: Argument 1: cannot convert from '(System.Action<System.Collections.IEnumerable> x, System.Action<System.Collections.IEnumerable> y)' to 'System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>' // Test<(IEnumerable<int>, IEnumerable <int>)> (z, z1); Diagnostic(ErrorCode.ERR_BadArgType, "z").WithArguments("1", "(System.Action<System.Collections.IEnumerable> x, System.Action<System.Collections.IEnumerable> y)", "System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>").WithLocation(25, 54), // (25,57): error CS1503: Argument 2: cannot convert from '(System.Action<System.Collections.Generic.IEnumerable<int>> x, System.Action<System.Collections.Generic.IEnumerable<int>> y)' to 'System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>' // Test<(IEnumerable<int>, IEnumerable <int>)> (z, z1); Diagnostic(ErrorCode.ERR_BadArgType, "z1").WithArguments("2", "(System.Action<System.Collections.Generic.IEnumerable<int>> x, System.Action<System.Collections.Generic.IEnumerable<int>> y)", "System.Action<(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)>").WithLocation(25, 57) ); } [Fact] public void ClassifyConversionIdentity01() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var int_string1 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_stringNamed = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("a", "b")); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_stringNamed).Kind); } [Fact] public void ClassifyConversionIdentity02() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var int_string1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_string2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_stringNamed = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("a", "b")); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string1, int_stringNamed).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.Identity, comp.ClassifyConversion(int_stringNamed, int_string1).Kind); } [Fact] public void ClassifyConversionNone01() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); var int_int = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType)); var int_int_int = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType, intType)); var string_string = comp.CreateTupleTypeSymbol(ImmutableArray.Create(stringType, stringType)); var int_int1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int, int_int_int).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int, string_string).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int1, string_string).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int1, int_int_int).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(string_string, int_int1).Kind); Assert.Equal(ConversionKind.NoConversion, comp.ClassifyConversion(int_int_int, int_int1).Kind); } [Fact] public void ClassifyConversionImplicit01() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); TypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); TypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); TypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string).Kind); } [Fact] public void ClassifyConversionImplicit02() { var tupleComp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object1 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); var int_string2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_object2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, objectType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object2).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object2, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object1, int_string2).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object2, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03u() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Null(int_string1.TupleUnderlyingType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03uu() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Null(int_string1.TupleUnderlyingType); Assert.Null(int_string2.TupleUnderlyingType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit03uuu() { var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tupleComp2 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var comp = (Compilation)CSharpCompilation.Create("test", references: new[] { MscorlibRef, tupleComp1.ToMetadataReference(), tupleComp2.ToMetadataReference() }); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_string2 = tupleComp2.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); Assert.Null(int_string1.TupleUnderlyingType); Assert.Null(int_string2.TupleUnderlyingType); Assert.Null(int_object.TupleUnderlyingType); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_string2).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_string1).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string1, int_object).Kind); Assert.Equal(ConversionKind.ImplicitTuple, comp.ClassifyConversion(int_string2, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string1).Kind); Assert.Equal(ConversionKind.ExplicitTuple, comp.ClassifyConversion(int_object, int_string2).Kind); } [Fact] public void ClassifyConversionImplicit04() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, ""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilationWithMscorlib40(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { (MetadataReference)Net40.mscorlib, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); var int_object_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType, objectType)); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.ImplicitTuple, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void ClassifyConversionImplicit05() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, (object)""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilationWithMscorlib40(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { (MetadataReference)Net40.mscorlib, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType)); var int_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType)); var int_object_object = tupleComp1.CreateTupleTypeSymbol(ImmutableArray.Create(intType, objectType, objectType)); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void ClassifyConversionImplicit06() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, ""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { MscorlibRef, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, objectType); var int_object_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, objectType, objectType); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.ImplicitTuple, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void ClassifyConversionImplicit07() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { var x = (1, (object)""qq""); var i = /*<bind0>*/x/*</bind0>*/; } }"; var tupleComp1 = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples); var tree = Parse(text); var comp = (Compilation)CSharpCompilation.Create("test", syntaxTrees: new[] { tree }, references: new[] { MscorlibRef, tupleComp1.ToMetadataReference() }); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); ITypeSymbol intType = comp.GetSpecialType(SpecialType.System_Int32); ITypeSymbol stringType = comp.GetSpecialType(SpecialType.System_String); ITypeSymbol objectType = comp.GetSpecialType(SpecialType.System_Object); var int_string1 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType); var int_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, objectType); var int_object_object = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, objectType, objectType); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object).Kind); Assert.Equal(ConversionKind.ExplicitTuple, model.ClassifyConversion(expr1, int_string1, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.Identity, model.ClassifyConversion(expr1, int_object, isExplicitInSource: true).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object).Kind); Assert.Equal(ConversionKind.NoConversion, model.ClassifyConversion(expr1, int_object_object, isExplicitInSource: true).Kind); } [Fact] public void TernaryTypeInferenceWithDynamicAndTupleNames() { var source = @" public class C { public void M() { bool flag = true; var x1 = flag ? (a: 1, b: 2) : (a: 1, c: 2); dynamic d = null; var t1 = (a: 1, b: 2); var t2 = (a: 1, c: d); var x2 = flag ? t1 : t2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,32): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int a, int)'. // var x1 = flag ? (a: 1, b: 2) : (a: 1, c: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(7, 32), // (7,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int)'. // var x1 = flag ? (a: 1, b: 2) : (a: 1, c: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 2").WithArguments("c", "(int a, int)").WithLocation(7, 47) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First()); Assert.Equal("(System.Int32 a, System.Int32) x1", x1.ToTestDisplayString()); var x2 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(5).First()); Assert.Equal("(System.Int32 a, dynamic c) x2", x2.ToTestDisplayString()); } [Fact] [WorkItem(16825, "https://github.com/dotnet/roslyn/issues/16825")] public void NullCoalescingOperatorWithTupleNames() { // See section 7.13 of the spec, regarding the null-coalescing operator var source = @" public class C { public void M() { (int a, int b)? nab = (1, 2); (int a, int c)? nac = (1, 3); var x1 = nab ?? nac; // (a, b)? var x2 = nab ?? nac.Value; // (a, b) var x3 = new C() ?? nac; // C var x4 = new D() ?? nac; // (a, c)? var x5 = nab != null ? nab : nac; // (a, )? var x6 = nab ?? (a: 1, c: 3); // (a, b) var x7 = nab ?? (a: 1, c: 3); // (a, b) var x8 = new C() ?? (a: 1, c: 3); // C var x9 = new D() ?? (a: 1, c: 3); // (a, c) var x6double = nab ?? (d: 1.1, c: 3); // (a, c) } public static implicit operator C((int, int) x) { throw null; } } public class D { public static implicit operator (int d1, int d2) (D x) { throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,32): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int b)'. // var x6 = nab ?? (a: 1, c: 3); // (a, b)? Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int b)").WithLocation(16, 32), // (17,32): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int b)'. // var x7 = nab ?? (a: 1, c: 3); // (a, b) Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int b)").WithLocation(17, 32), // (18,30): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(int, int)'. // var x8 = new C() ?? (a: 1, c: 3); // C Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(int, int)").WithLocation(18, 30), // (18,36): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int, int)'. // var x8 = new C() ?? (a: 1, c: 3); // C Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int, int)").WithLocation(18, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2)); Assert.Equal("(System.Int32 a, System.Int32 b)? x1", x1.ToTestDisplayString()); var x2 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(3)); Assert.Equal("(System.Int32 a, System.Int32 b) x2", x2.ToTestDisplayString()); var x3 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(4)); Assert.Equal("C x3", x3.ToTestDisplayString()); var x4 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(5)); Assert.Equal("(System.Int32 a, System.Int32 c)? x4", x4.ToTestDisplayString()); var x5 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(6)); Assert.Equal("(System.Int32 a, System.Int32)? x5", x5.ToTestDisplayString()); var x6 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(7)); Assert.Equal("(System.Int32 a, System.Int32 b) x6", x6.ToTestDisplayString()); var x7 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(8)); Assert.Equal("(System.Int32 a, System.Int32 b) x7", x7.ToTestDisplayString()); var x8 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(9)); Assert.Equal("C x8", x8.ToTestDisplayString()); var x9 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(10)); Assert.Equal("(System.Int32 a, System.Int32 c) x9", x9.ToTestDisplayString()); var x6double = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().ElementAt(11)); Assert.Equal("(System.Double d, System.Int32 c) x6double", x6double.ToTestDisplayString()); } [Fact] public void TernaryTypeInferenceWithNoNames() { var source = @" public class C { public void M() { bool flag = true; var x1 = flag ? (a: 1, b: 2) : (1, 2); var x2 = flag ? (1, 2) : (a: 1, b: 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,26): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(int, int)'. // var x1 = flag ? (a: 1, b: 2) : (1, 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(int, int)").WithLocation(7, 26), // (7,32): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int, int)'. // var x1 = flag ? (a: 1, b: 2) : (1, 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int, int)").WithLocation(7, 32), // (8,35): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(int, int)'. // var x2 = flag ? (1, 2) : (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(int, int)").WithLocation(8, 35), // (8,41): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int, int)'. // var x2 = flag ? (1, 2) : (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int, int)").WithLocation(8, 41) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First()); Assert.Equal("(System.Int32, System.Int32) x1", x1.ToTestDisplayString()); var x2 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(2).First()); Assert.Equal("(System.Int32, System.Int32) x2", x2.ToTestDisplayString()); } [Fact] public void TernaryTypeInferenceDropsCandidates() { var source = @" public class C { public void M() { bool flag = true; var x1 = flag ? (a: 1, b: (long)2) : (a: (byte)1, c: 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,59): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, long b)'. // var x1 = flag ? (a: 1, b: (long)2) : (a: (byte)1, c: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 2").WithArguments("c", "(int a, long b)").WithLocation(7, 59) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First()); Assert.Equal("(System.Int32 a, System.Int64 b) x1", x1.ToTestDisplayString()); } [Fact] public void LambdaTypeInferenceWithTupleNames() { var source = @" public class C { public void M() { var x1 = M2(() => { bool flag = true; if (flag) { return (a: 1, b: 2); } else { if (flag) { return (a: 1, c: 3); } else { return (a: 1, d: 4); } } }); } public T M2<T>(System.Func<T> f) { return f(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,43): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int a, int)'. // return (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(11, 43), // (17,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int)'. // return (a: 1, c: 3); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int)").WithLocation(17, 47), // (21,47): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(int a, int)'. // return (a: 1, d: 4); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(int a, int)").WithLocation(21, 47) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("(System.Int32 a, System.Int32) x1", x1.ToTestDisplayString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaTypeInferenceWithDynamic() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @" public class C { public void M() { var x1 = M2(() => { bool flag = true; dynamic d = null; if (flag) { return (a: 1, b: 2); } else { if (flag) { return (a: d, c: 3); } else { return (a: d, d: 4); } } }); } public T M2<T>(System.Func<T> f) { return f(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,43): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(dynamic a, int)'. // return (a: 1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(dynamic a, int)").WithLocation(12, 43), // (18,47): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(dynamic a, int)'. // return (a: d, c: 3); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(dynamic a, int)").WithLocation(18, 47), // (22,47): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(dynamic a, int)'. // return (a: d, d: 4); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(dynamic a, int)").WithLocation(22, 47) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = model.GetDeclaredSymbol(nodes.OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("(dynamic a, System.Int32) x1", x1.ToTestDisplayString()); } [Fact] public void LambdaTypeInferenceFails() { var source = @" public class C { public void M() { var x1 = M2(() => { bool flag = true; dynamic d = null; if (flag) { return (a: 1, b: d); } else { if (flag) { return (a: d, c: 3); } else { return (a: d, d: 4); } } }); } public T M2<T>(System.Func<T> f) { return f(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0411: The type arguments for method 'C.M2<T>(Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var x1 = M2(() => Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(System.Func<T>)").WithLocation(6, 18) ); } [Fact] public void WarnForDroppingNamesInConversion() { var source = @" public class C { public void M() { (int a, int) x1 = (1, b: 2); (int a, string) x2 = (1, b: null); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): warning CS8123: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(int a, int)'. // (int a, int) x1 = (1, b: 2); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(6, 31), // (7,34): warning CS8123: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(int a, string)'. // (int a, string) x2 = (1, b: null); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: null").WithArguments("b", "(int a, string)").WithLocation(7, 34), // (6,22): warning CS0219: The variable 'x1' is assigned but its value is never used // (int a, int) x1 = (1, b: 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 22), // (7,25): warning CS0219: The variable 'x2' is assigned but its value is never used // (int a, string) x2 = (1, b: null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 25) ); } [Fact] public void MethodTypeInferenceMergesTupleNames() { var source = @" public class C { public void M() { var t = M2((a: 1, b: 2), (a: 1, c: 3)); System.Console.Write(t.a); System.Console.Write(t.b); System.Console.Write(t.c); M2((1, 2), (c: 1, d: 3)); M2(new[] { (a: 1, b: 2) }, new[] { (1, 3) }); } public T M2<T>(T x1, T x2) { return x1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,27): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(int a, int)'. // var t = M2((a: 1, b: 2), (a: 1, c: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(int a, int)").WithLocation(6, 27), // (6,41): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int)'. // var t = M2((a: 1, b: 2), (a: 1, c: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(int a, int)").WithLocation(6, 41), // (8,32): error CS1061: '(int a, int)' does not contain a definition for 'b' and no extension method 'b' accepting a first argument of type '(int a, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(t.b); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "b").WithArguments("(int a, int)", "b").WithLocation(8, 32), // (9,32): error CS1061: '(int a, int)' does not contain a definition for 'c' and no extension method 'c' accepting a first argument of type '(int a, int)' could be found (are you missing a using directive or an assembly reference?) // System.Console.Write(t.c); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c").WithArguments("(int a, int)", "c").WithLocation(9, 32), // (10,21): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int, int)'. // M2((1, 2), (c: 1, d: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 1").WithArguments("c", "(int, int)").WithLocation(10, 21), // (10,27): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(int, int)'. // M2((1, 2), (c: 1, d: 3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 3").WithArguments("d", "(int, int)").WithLocation(10, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation1 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().First()); Assert.Equal("(System.Int32 a, System.Int32)", ((IMethodSymbol)invocation1.Symbol).ReturnType.ToTestDisplayString()); var invocation2 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(4).First()); Assert.Equal("(System.Int32, System.Int32)", ((IMethodSymbol)invocation2.Symbol).ReturnType.ToTestDisplayString()); var invocation3 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(5).First()); Assert.Equal("(System.Int32, System.Int32)[]", ((IMethodSymbol)invocation3.Symbol).ReturnType.ToTestDisplayString()); } [Fact] public void MethodTypeInferenceDropsCandidates() { var source = @" public class C { public void M() { M2((a: 1, b: 2), (a: (byte)1, c: (byte)3)); M2(((long)1, b: 2), (c: 1, d: (byte)3)); M2((a: (long)1, b: 2), ((byte)1, 3)); } public T M2<T>(T x1, T x2) { return x1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,39): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(int a, int b)'. // M2((a: 1, b: 2), (a: (byte)1, c: (byte)3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: (byte)3").WithArguments("c", "(int a, int b)").WithLocation(6, 39), // (7,30): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, int b)'. // M2(((long)1, b: 2), (c: 1, d: (byte)3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 1").WithArguments("c", "(long, int b)").WithLocation(7, 30), // (7,36): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, int b)'. // M2(((long)1, b: 2), (c: 1, d: (byte)3)); Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: (byte)3").WithArguments("d", "(long, int b)").WithLocation(7, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation1 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().First()); Assert.Equal("(System.Int32 a, System.Int32 b) C.M2<(System.Int32 a, System.Int32 b)>((System.Int32 a, System.Int32 b) x1, (System.Int32 a, System.Int32 b) x2)", invocation1.Symbol.ToTestDisplayString()); var invocation2 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(1).First()); Assert.Equal("(System.Int64, System.Int32 b) C.M2<(System.Int64, System.Int32 b)>((System.Int64, System.Int32 b) x1, (System.Int64, System.Int32 b) x2)", invocation2.Symbol.ToTestDisplayString()); var invocation3 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().Skip(2).First()); Assert.Equal("(System.Int64 a, System.Int32 b) C.M2<(System.Int64 a, System.Int32 b)>((System.Int64 a, System.Int32 b) x1, (System.Int64 a, System.Int32 b) x2)", invocation3.Symbol.ToTestDisplayString()); } [Fact] public void MethodTypeInferenceMergesDynamic() { var source = @" public class C { public void M() { (dynamic[] a, object[] b) x1 = (null, null); (object[] a, dynamic[] c) x2 = (null, null); M2(x1, x2); } public void M2<T>(T x1, T x2) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var invocation1 = model.GetSymbolInfo(nodes.OfType<InvocationExpressionSyntax>().First()); Assert.Equal("void C.M2<(dynamic[] a, dynamic[])>((dynamic[] a, dynamic[]) x1, (dynamic[] a, dynamic[]) x2)", invocation1.Symbol.ToTestDisplayString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/12267")] [WorkItem(12267, "https://github.com/dotnet/roslyn/issues/12267")] public void ConstraintsAndNames() { var source1 = @" using System.Collections.Generic; public abstract class Base { public abstract void M<T>(T x) where T : IEnumerable<(int a, int b)>; } "; var source2 = @" class Derived : Base { public override void M<T>(T x) { foreach (var y in x) { System.Console.WriteLine(y.a); } } }"; var comp1 = CreateCompilation(source1 + trivial2uple + source2); comp1.VerifyDiagnostics(); var comp2 = CreateCompilationWithMscorlib45(source1 + trivial2uple); comp2.VerifyDiagnostics(); // Retargeting (different version of mscorlib) var comp3 = CreateCompilationWithMscorlib46(source2, references: new[] { new CSharpCompilationReference(comp2) }); comp3.VerifyDiagnostics(); // Metadata var comp4 = CreateCompilationWithMscorlib45(source2, references: new[] { comp2.EmitToImageReference() }); comp4.VerifyDiagnostics(); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInReturn() { var source = @" public class Base { public virtual (int a, int b) M1() { return (1, 2); } public virtual (int a, int b) M2() { return (1, 2); } public virtual (int a, int b)[] M3() { return new[] { (1, 2) }; } public virtual System.Nullable<(int a, int b)> M4() { return (1, 2); } public virtual ((int a, int b) c, int d) M5() { return ((1, 2), 3); } public virtual (dynamic a, dynamic b) M6() { return (1, 2); } } public class Derived : Base { public override (int a, int b) M1() { return (1, 2); } public override (int notA, int notB) M2() { return (1, 2); } public override (int notA, int notB)[] M3() { return new[] { (1, 2) }; } public override System.Nullable<(int notA, int notB)> M4() { return (1, 2); } public override ((int notA, int notB) c, int d) M5() { return ((1, 2), 3); } public override (dynamic notA, dynamic) M6() { return (1, 2); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef, SystemCoreRef }); comp.VerifyDiagnostics( // (14,42): error CS8139: 'Derived.M2()': cannot change tuple element names when overriding inherited member 'Base.M2()' // public override (int notA, int notB) M2() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()").WithLocation(14, 42), // (15,44): error CS8139: 'Derived.M3()': cannot change tuple element names when overriding inherited member 'Base.M3()' // public override (int notA, int notB)[] M3() { return new[] { (1, 2) }; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3()", "Base.M3()").WithLocation(15, 44), // (16,59): error CS8139: 'Derived.M4()': cannot change tuple element names when overriding inherited member 'Base.M4()' // public override System.Nullable<(int notA, int notB)> M4() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()").WithLocation(16, 59), // (17,53): error CS8139: 'Derived.M5()': cannot change tuple element names when overriding inherited member 'Base.M5()' // public override ((int notA, int notB) c, int d) M5() { return ((1, 2), 3); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M5").WithArguments("Derived.M5()", "Base.M5()").WithLocation(17, 53), // (18,45): error CS8139: 'Derived.M6()': cannot change tuple element names when overriding inherited member 'Base.M6()' // public override (dynamic notA, dynamic) M6() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M6").WithArguments("Derived.M6()", "Base.M6()").WithLocation(18, 45) ); var m3 = comp.GetMember<MethodSymbol>("Derived.M3").ReturnType; Assert.Equal("(System.Int32 notA, System.Int32 notB)[]", m3.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IList<(System.Int32 notA, System.Int32 notB)>" }, m3.Interfaces().SelectAsArray(t => t.ToTestDisplayString())); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInReturnUsingTypeArg() { var source = @" public class Base { public virtual (T a, T b) M1<T>() { return (default(T), default(T)); } public virtual (T a, T b) M2<T>() { return (default(T), default(T)); } public virtual (T a, T b)[] M3<T>() { return new[] { (default(T), default(T)) }; } public virtual System.Nullable<(T a, T b)> M4<T>() { return (default(T), default(T)); } public virtual ((T a, T b) c, T d) M5<T>() { return ((default(T), default(T)), default(T)); } public virtual (dynamic a, dynamic b) M6<T>() { return (default(T), default(T)); } } public class Derived : Base { public override (T a, T b) M1<T>() { return (default(T), default(T)); } public override (T notA, T notB) M2<T>() { return (default(T), default(T)); } public override (T notA, T notB)[] M3<T>() { return new[] { (default(T), default(T)) }; } public override System.Nullable<(T notA, T notB)> M4<T>() { return (default(T), default(T)); } public override ((T notA, T notB) c, T d) M5<T>() { return ((default(T), default(T)), default(T)); } public override (dynamic notA, dynamic) M6<T>() { return (default(T), default(T)); } } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (14,38): error CS8139: 'Derived.M2<T>()': cannot change tuple element names when overriding inherited member 'Base.M2<T>()' // public override (T notA, T notB) M2<T>() { return (default(T), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2<T>()", "Base.M2<T>()").WithLocation(14, 38), // (15,40): error CS8139: 'Derived.M3<T>()': cannot change tuple element names when overriding inherited member 'Base.M3<T>()' // public override (T notA, T notB)[] M3<T>() { return new[] { (default(T), default(T)) }; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3<T>()", "Base.M3<T>()").WithLocation(15, 40), // (16,55): error CS8139: 'Derived.M4<T>()': cannot change tuple element names when overriding inherited member 'Base.M4<T>()' // public override System.Nullable<(T notA, T notB)> M4<T>() { return (default(T), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4<T>()", "Base.M4<T>()").WithLocation(16, 55), // (17,47): error CS8139: 'Derived.M5<T>()': cannot change tuple element names when overriding inherited member 'Base.M5<T>()' // public override ((T notA, T notB) c, T d) M5<T>() { return ((default(T), default(T)), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M5").WithArguments("Derived.M5<T>()", "Base.M5<T>()").WithLocation(17, 47), // (18,45): error CS8139: 'Derived.M6<T>()': cannot change tuple element names when overriding inherited member 'Base.M6<T>()' // public override (dynamic notA, dynamic) M6<T>() { return (default(T), default(T)); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M6").WithArguments("Derived.M6<T>()", "Base.M6<T>()").WithLocation(18, 45) ); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInParameters() { var source = @" public class Base { public virtual void M1((int a, int b) x) { } public virtual void M2((int a, int b)[] x) { } public virtual void M3(System.Nullable<(int a, int b)> x) { } public virtual void M4(((int a, int b) c, int d) x) { } } public class Derived : Base { public override void M1((int notA, int notB) y) { } public override void M2((int notA, int notB)[] x) { } public override void M3(System.Nullable<(int notA, int notB)> x) { } public override void M4(((int notA, int notB) c, int d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,26): error CS8139: 'Derived.M2((int notA, int notB)[])': cannot change tuple element names when overriding inherited member 'Base.M2((int a, int b)[])' // public override void M2((int notA, int notB)[] x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2((int notA, int notB)[])", "Base.M2((int a, int b)[])").WithLocation(12, 26), // (13,26): error CS8139: 'Derived.M3((int notA, int notB)?)': cannot change tuple element names when overriding inherited member 'Base.M3((int a, int b)?)' // public override void M3(System.Nullable<(int notA, int notB)> x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3((int notA, int notB)?)", "Base.M3((int a, int b)?)").WithLocation(13, 26), // (14,26): error CS8139: 'Derived.M4(((int notA, int notB) c, int d))': cannot change tuple element names when overriding inherited member 'Base.M4(((int a, int b) c, int d))' // public override void M4(((int notA, int notB) c, int d) x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4(((int notA, int notB) c, int d))", "Base.M4(((int a, int b) c, int d))").WithLocation(14, 26), // (11,26): error CS8139: 'Derived.M1((int notA, int notB))': cannot change tuple element names when overriding inherited member 'Base.M1((int a, int b))' // public override void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M1").WithArguments("Derived.M1((int notA, int notB))", "Base.M1((int a, int b))").WithLocation(11, 26) ); } [Fact] public void OverriddenMethodWithDifferentTupleNamesInParametersUsingTypeArg() { var source = @" public class Base { public virtual void M1<T>((T a, T b) x) { } public virtual void M2<T>((T a, T b)[] x) { } public virtual void M3<T>(System.Nullable<(T a, T b)> x) { } public virtual void M4<T>(((T a, T b) c, T d) x) { } } public class Derived : Base { public override void M1<T>((T notA, T notB) y) { } public override void M2<T>((T notA, T notB)[] x) { } public override void M3<T>(System.Nullable<(T notA, T notB)> x) { } public override void M4<T>(((T notA, T notB) c, T d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,26): error CS8139: 'Derived.M2<T>((T notA, T notB)[])': cannot change tuple element names when overriding inherited member 'Base.M2<T>((T a, T b)[])' // public override void M2<T>((T notA, T notB)[] x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2<T>((T notA, T notB)[])", "Base.M2<T>((T a, T b)[])").WithLocation(12, 26), // (13,26): error CS8139: 'Derived.M3<T>((T notA, T notB)?)': cannot change tuple element names when overriding inherited member 'Base.M3<T>((T a, T b)?)' // public override void M3<T>(System.Nullable<(T notA, T notB)> x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3<T>((T notA, T notB)?)", "Base.M3<T>((T a, T b)?)").WithLocation(13, 26), // (14,26): error CS8139: 'Derived.M4<T>(((T notA, T notB) c, T d))': cannot change tuple element names when overriding inherited member 'Base.M4<T>(((T a, T b) c, T d))' // public override void M4<T>(((T notA, T notB) c, T d) x) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4<T>(((T notA, T notB) c, T d))", "Base.M4<T>(((T a, T b) c, T d))").WithLocation(14, 26), // (11,26): error CS8139: 'Derived.M1<T>((T notA, T notB))': cannot change tuple element names when overriding inherited member 'Base.M1<T>((T a, T b))' // public override void M1<T>((T notA, T notB) y) { } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M1").WithArguments("Derived.M1<T>((T notA, T notB))", "Base.M1<T>((T a, T b))").WithLocation(11, 26) ); } [Fact] public void OverriddenPropertiesWithDifferentTupleNames() { var source = @" public class Base { public virtual (int a, int b) P1 { get { return (1, 2); } set { } } public virtual (int a, int b)[] P2 { get; set; } public virtual (int a, int b)? P3 { get { return (1, 2); } set { } } public virtual ((int a, int b) c, int d) P4 { get; set; } } public class Derived : Base { public override (int notA, int notB) P1 { get { return (1, 2); } set { } } public override (int notA, int notB)[] P2 { get; set; } public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } public override ((int notA, int notB) c, int d) P4 { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,44): error CS8139: 'Derived.P2': cannot change tuple element names when overriding inherited member 'Base.P2' // public override (int notA, int notB)[] P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P2").WithArguments("Derived.P2", "Base.P2").WithLocation(12, 44), // (12,49): error CS8139: 'Derived.P2.get': cannot change tuple element names when overriding inherited member 'Base.P2.get' // public override (int notA, int notB)[] P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P2.get", "Base.P2.get").WithLocation(12, 49), // (12,54): error CS8139: 'Derived.P2.set': cannot change tuple element names when overriding inherited member 'Base.P2.set' // public override (int notA, int notB)[] P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P2.set", "Base.P2.set").WithLocation(12, 54), // (13,43): error CS8139: 'Derived.P3': cannot change tuple element names when overriding inherited member 'Base.P3' // public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P3").WithArguments("Derived.P3", "Base.P3").WithLocation(13, 43), // (13,48): error CS8139: 'Derived.P3.get': cannot change tuple element names when overriding inherited member 'Base.P3.get' // public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P3.get", "Base.P3.get").WithLocation(13, 48), // (13,71): error CS8139: 'Derived.P3.set': cannot change tuple element names when overriding inherited member 'Base.P3.set' // public override (int notA, int notB)? P3 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P3.set", "Base.P3.set").WithLocation(13, 71), // (14,53): error CS8139: 'Derived.P4': cannot change tuple element names when overriding inherited member 'Base.P4' // public override ((int notA, int notB) c, int d) P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P4").WithArguments("Derived.P4", "Base.P4").WithLocation(14, 53), // (14,58): error CS8139: 'Derived.P4.get': cannot change tuple element names when overriding inherited member 'Base.P4.get' // public override ((int notA, int notB) c, int d) P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P4.get", "Base.P4.get").WithLocation(14, 58), // (14,63): error CS8139: 'Derived.P4.set': cannot change tuple element names when overriding inherited member 'Base.P4.set' // public override ((int notA, int notB) c, int d) P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P4.set", "Base.P4.set").WithLocation(14, 63), // (11,42): error CS8139: 'Derived.P1': cannot change tuple element names when overriding inherited member 'Base.P1' // public override (int notA, int notB) P1 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P1").WithArguments("Derived.P1", "Base.P1").WithLocation(11, 42), // (11,47): error CS8139: 'Derived.P1.get': cannot change tuple element names when overriding inherited member 'Base.P1.get' // public override (int notA, int notB) P1 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P1.get", "Base.P1.get").WithLocation(11, 47), // (11,70): error CS8139: 'Derived.P1.set': cannot change tuple element names when overriding inherited member 'Base.P1.set' // public override (int notA, int notB) P1 { get { return (1, 2); } set { } } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P1.set", "Base.P1.set").WithLocation(11, 70) ); } [Fact] public void OverriddenEventsWithDifferentTupleNames() { var source = @" using System; public class Base { public virtual event Func<(int a, int b)> E1; public virtual event Func<(int a, int b)> E2; public virtual event Func<(int a, int b)[]> E3; public virtual event Func<((int a, int b) c, int d)> E4; void M() { E1(); E2(); E3(); E4(); } } public class Derived : Base { public override event Func<(int a, int b)> E1; public override event Func<(int notA, int notB)> E2; public override event Func<(int notA, int notB)[]> E3; public override event Func<((int notA, int) c, int d)> E4; void M() { E1(); E2(); E3(); E4(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,54): error CS8139: 'Derived.E2': cannot change tuple element names when overriding inherited member 'Base.E2' // public override event Func<(int notA, int notB)> E2; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E2").WithArguments("Derived.E2", "Base.E2").WithLocation(15, 54), // (15,54): error CS8139: 'Derived.E2.add': cannot change tuple element names when overriding inherited member 'Base.E2.add' // public override event Func<(int notA, int notB)> E2; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E2").WithArguments("Derived.E2.add", "Base.E2.add").WithLocation(15, 54), // (15,54): error CS8139: 'Derived.E2.remove': cannot change tuple element names when overriding inherited member 'Base.E2.remove' // public override event Func<(int notA, int notB)> E2; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E2").WithArguments("Derived.E2.remove", "Base.E2.remove").WithLocation(15, 54), // (16,56): error CS8139: 'Derived.E3': cannot change tuple element names when overriding inherited member 'Base.E3' // public override event Func<(int notA, int notB)[]> E3; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E3").WithArguments("Derived.E3", "Base.E3").WithLocation(16, 56), // (16,56): error CS8139: 'Derived.E3.add': cannot change tuple element names when overriding inherited member 'Base.E3.add' // public override event Func<(int notA, int notB)[]> E3; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E3").WithArguments("Derived.E3.add", "Base.E3.add").WithLocation(16, 56), // (16,56): error CS8139: 'Derived.E3.remove': cannot change tuple element names when overriding inherited member 'Base.E3.remove' // public override event Func<(int notA, int notB)[]> E3; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E3").WithArguments("Derived.E3.remove", "Base.E3.remove").WithLocation(16, 56), // (17,60): error CS8139: 'Derived.E4': cannot change tuple element names when overriding inherited member 'Base.E4' // public override event Func<((int notA, int) c, int d)> E4; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E4").WithArguments("Derived.E4", "Base.E4").WithLocation(17, 60), // (17,60): error CS8139: 'Derived.E4.add': cannot change tuple element names when overriding inherited member 'Base.E4.add' // public override event Func<((int notA, int) c, int d)> E4; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E4").WithArguments("Derived.E4.add", "Base.E4.add").WithLocation(17, 60), // (17,60): error CS8139: 'Derived.E4.remove': cannot change tuple element names when overriding inherited member 'Base.E4.remove' // public override event Func<((int notA, int) c, int d)> E4; Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "E4").WithArguments("Derived.E4.remove", "Base.E4.remove").WithLocation(17, 60) ); } [Fact] public void HiddenMethodsWithDifferentTupleNames() { var source = @" public class Base { public virtual int M0() { return 0; } public virtual (int a, int b) M1() { return (1, 2); } public virtual (int a, int b)[] M2() { return new[] { (1, 2) }; } public virtual System.Nullable<(int a, int b)> M3() { return null; } public virtual ((int a, int b) c, int d) M4() { return ((1, 2), 3); } } public class Derived : Base { public string M0() { return null; } public (int a, int b) M1() { return (1, 2); } public (int notA, int notB)[] M2() { return new[] { (1, 2) }; } public System.Nullable<(int notA, int notB)> M3() { return null; } public ((int notA, int notB) c, int d) M4() { return ((1, 2), 3); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,27): warning CS0114: 'Derived.M1()' hides inherited member 'Base.M1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public (int a, int b) M1() { return (1, 2); } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M1").WithArguments("Derived.M1()", "Base.M1()").WithLocation(13, 27), // (14,35): warning CS0114: 'Derived.M2()' hides inherited member 'Base.M2()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public (int notA, int notB)[] M2() { return new[] { (1, 2) }; } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M2").WithArguments("Derived.M2()", "Base.M2()").WithLocation(14, 35), // (15,50): warning CS0114: 'Derived.M3()' hides inherited member 'Base.M3()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public System.Nullable<(int notA, int notB)> M3() { return null; } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M3").WithArguments("Derived.M3()", "Base.M3()").WithLocation(15, 50), // (16,44): warning CS0114: 'Derived.M4()' hides inherited member 'Base.M4()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public ((int notA, int notB) c, int d) M4() { return ((1, 2), 3); } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M4").WithArguments("Derived.M4()", "Base.M4()").WithLocation(16, 44), // (12,19): warning CS0114: 'Derived.M0()' hides inherited member 'Base.M0()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public string M0() { return null; } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M0").WithArguments("Derived.M0()", "Base.M0()").WithLocation(12, 19) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void HiddenMethodsWithNoNames() { var source = @" public class Base { public virtual (int a, int b) M1() { return (1, 2); } } public class Derived : Base { public (int, int) M1() { return (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,23): warning CS0114: 'Derived.M1()' hides inherited member 'Base.M1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public (int, int) M1() { return (1, 2); } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M1").WithArguments("Derived.M1()", "Base.M1()").WithLocation(8, 23) ); } [Fact] public void DuplicateMethodDetectionWithDifferentTupleNames() { var source = @" public class C { public void M1((int a, int b) x) { } public void M1((int notA, int notB) x) { } public void M2((int a, int b)[] x) { } public void M2((int notA, int notB)[] x) { } public void M3(System.Nullable<(int a, int b)> x) { } public void M3(System.Nullable<(int notA, int notB)> x) { } public void M4(((int a, int b) c, int d) x) { } public void M4(((int notA, int notB) c, int d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0111: Type 'C' already defines a member called 'M1' with the same parameter types // public void M1((int notA, int notB) x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C").WithLocation(5, 17), // (8,17): error CS0111: Type 'C' already defines a member called 'M2' with the same parameter types // public void M2((int notA, int notB)[] x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C").WithLocation(8, 17), // (11,17): error CS0111: Type 'C' already defines a member called 'M3' with the same parameter types // public void M3(System.Nullable<(int notA, int notB)> x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M3").WithArguments("M3", "C").WithLocation(11, 17), // (14,17): error CS0111: Type 'C' already defines a member called 'M4' with the same parameter types // public void M4(((int notA, int notB) c, int d) x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M4").WithArguments("M4", "C").WithLocation(14, 17) ); } [Fact] public void HiddenMethodParametersWithDifferentTupleNames() { var source = @" public class Base { public virtual void M1((int a, int b) x) { } public virtual void M2((int a, int b)[] x) { } public virtual void M3(System.Nullable<(int a, int b)> x) { } public virtual void M4(((int a, int b) c, int d) x) { } } public class Derived : Base { public void M1((int notA, int notB) y) { } public void M2((int notA, int notB)[] x) { } public void M3(System.Nullable<(int notA, int notB)> x) { } public void M4(((int notA, int notB) c, int d) x) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS0114: 'Derived.M2((int notA, int notB)[])' hides inherited member 'Base.M2((int a, int b)[])'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M2((int notA, int notB)[] x) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M2").WithArguments("Derived.M2((int notA, int notB)[])", "Base.M2((int a, int b)[])").WithLocation(12, 17), // (13,17): warning CS0114: 'Derived.M3((int notA, int notB)?)' hides inherited member 'Base.M3((int a, int b)?)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M3(System.Nullable<(int notA, int notB)> x) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M3").WithArguments("Derived.M3((int notA, int notB)?)", "Base.M3((int a, int b)?)").WithLocation(13, 17), // (14,17): warning CS0114: 'Derived.M4(((int notA, int notB) c, int d))' hides inherited member 'Base.M4(((int a, int b) c, int d))'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M4(((int notA, int notB) c, int d) x) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M4").WithArguments("Derived.M4(((int notA, int notB) c, int d))", "Base.M4(((int a, int b) c, int d))").WithLocation(14, 17), // (11,17): warning CS0114: 'Derived.M1((int notA, int notB))' hides inherited member 'Base.M1((int a, int b))'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "M1").WithArguments("Derived.M1((int notA, int notB))", "Base.M1((int a, int b))").WithLocation(11, 17) ); } [Fact] public void ExplicitInterfaceImplementationWithDifferentTupleNames() { var source = @" public interface I0 { void M1((int, int b) x); void M2((int a, int b) x); (int, int b) MR1(); (int a, int b) MR2(); } public class C : I0 { void I0.M1((int notMissing, int b) z) { } void I0.M2((int notA, int notB) z) { } (int notMissing, int b) I0.MR1() { return (1, 2); } (int notA, int notB) I0.MR2() { return (1, 2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,13): error CS8141: The tuple element names in the signature of method 'C.I0.M2((int notA, int notB))' must match the tuple element names of interface method 'I0.M2((int a, int b))' (including on the return type). // void I0.M2((int notA, int notB) z) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M2").WithArguments("C.I0.M2((int notA, int notB))", "I0.M2((int a, int b))").WithLocation(12, 13), // (13,32): error CS8141: The tuple element names in the signature of method 'C.I0.MR1()' must match the tuple element names of interface method 'I0.MR1()' (including on the return type). // (int notMissing, int b) I0.MR1() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "MR1").WithArguments("C.I0.MR1()", "I0.MR1()").WithLocation(13, 32), // (14,29): error CS8141: The tuple element names in the signature of method 'C.I0.MR2()' must match the tuple element names of interface method 'I0.MR2()' (including on the return type). // (int notA, int notB) I0.MR2() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "MR2").WithArguments("C.I0.MR2()", "I0.MR2()").WithLocation(14, 29), // (11,13): error CS8141: The tuple element names in the signature of method 'C.I0.M1((int notMissing, int b))' must match the tuple element names of interface method 'I0.M1((int, int b))' (including on the return type). // void I0.M1((int notMissing, int b) z) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "M1").WithArguments("C.I0.M1((int notMissing, int b))", "I0.M1((int, int b))").WithLocation(11, 13) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ExplicitInterfaceImplementationWithNoNames() { var source = @" public interface I0 { void M1((int, int b) x); void M2((int a, int b) x); (int, int b) MR1(); (int a, int b) MR2(); (int a, int b) P { get; set; } } public class C : I0 { void I0.M1((int, int) z) { } void I0.M2((int, int) z) { } (int, int) I0.MR1() { return (1, 2); } (int, int) I0.MR2() { return (1, 2); } (int, int) I0.P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void InterfaceHidingAnotherInterfaceWithDifferentTupleNames() { var source = @" public interface I0 { void M2((int a, int b) x); (int a, int b) MR2(); } public interface I1 : I0 { void M2((int notA, int notB) z); (int notA, int notB) MR2(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,26): warning CS0108: 'I1.MR2()' hides inherited member 'I0.MR2()'. Use the new keyword if hiding was intended. // (int notA, int notB) MR2(); Diagnostic(ErrorCode.WRN_NewRequired, "MR2").WithArguments("I1.MR2()", "I0.MR2()").WithLocation(10, 26), // (9,10): warning CS0108: 'I1.M2((int notA, int notB))' hides inherited member 'I0.M2((int a, int b))'. Use the new keyword if hiding was intended. // void M2((int notA, int notB) z); Diagnostic(ErrorCode.WRN_NewRequired, "M2").WithArguments("I1.M2((int notA, int notB))", "I0.M2((int a, int b))").WithLocation(9, 10) ); } [Fact] public void HidingInterfaceMethodsWithDifferentTupleNames() { var source = @" public interface I0 { void M1((int a, int b) x); void M2((int a, int b) x); void M3((int a, int b) x); void M4((int a, int b) x); (int a, int b) M5(); (int a, int b) M6(); } public interface I1 : I0 { void M1((int notA, int notB) x); void M2((int a, int b) x); new void M3((int a, int b) x); new void M4((int notA, int notB) x); (int notA, int notB) M5(); (int a, int b) M6(); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,20): warning CS0108: 'I1.M6()' hides inherited member 'I0.M6()'. Use the new keyword if hiding was intended. // (int a, int b) M6(); Diagnostic(ErrorCode.WRN_NewRequired, "M6").WithArguments("I1.M6()", "I0.M6()").WithLocation(18, 20), // (14,10): warning CS0108: 'I1.M2((int a, int b))' hides inherited member 'I0.M2((int a, int b))'. Use the new keyword if hiding was intended. // void M2((int a, int b) x); Diagnostic(ErrorCode.WRN_NewRequired, "M2").WithArguments("I1.M2((int a, int b))", "I0.M2((int a, int b))").WithLocation(14, 10), // (17,26): warning CS0108: 'I1.M5()' hides inherited member 'I0.M5()'. Use the new keyword if hiding was intended. // (int notA, int notB) M5(); Diagnostic(ErrorCode.WRN_NewRequired, "M5").WithArguments("I1.M5()", "I0.M5()").WithLocation(17, 26), // (13,10): warning CS0108: 'I1.M1((int notA, int notB))' hides inherited member 'I0.M1((int a, int b))'. Use the new keyword if hiding was intended. // void M1((int notA, int notB) x); Diagnostic(ErrorCode.WRN_NewRequired, "M1").WithArguments("I1.M1((int notA, int notB))", "I0.M1((int a, int b))").WithLocation(13, 10) ); } [Fact] public void DuplicateInterfaceDetectionWithDifferentTupleNames_01() { var source = @" public interface I0<T> { } public class C1 : I0<(int a, int b)>, I0<(int notA, int notB)> { } public class C2 : I0<(int a, int b)>, I0<(int a, int b)> { } public class C3 : I0<int>, I0<int> { } public class C4<T, U> : I0<(int a, int b)>, I0<(T a, U b)> { } public class C5<T, U> : I0<(int a, int b)>, I0<(T notA, U notB)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0528: 'I0<int>' is already listed in interface list // public class C3 : I0<int>, I0<int> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "I0<int>").WithArguments("I0<int>").WithLocation(5, 28), // (4,39): error CS0528: 'I0<(int a, int b)>' is already listed in interface list // public class C2 : I0<(int a, int b)>, I0<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "I0<(int a, int b)>").WithArguments("I0<(int a, int b)>").WithLocation(4, 39), // (3,14): error CS8140: 'I0<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I0<(int a, int b)>'. // public class C1 : I0<(int a, int b)>, I0<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I0<(int notA, int notB)>", "I0<(int a, int b)>", "C1").WithLocation(3, 14), // (6,14): error CS0695: 'C4<T, U>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T a, U b)>' because they may unify for some type parameter substitutions // public class C4<T, U> : I0<(int a, int b)>, I0<(T a, U b)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I0<(int a, int b)>", "I0<(T a, U b)>").WithLocation(6, 14), // (7,14): error CS0695: 'C5<T, U>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T notA, U notB)>' because they may unify for some type parameter substitutions // public class C5<T, U> : I0<(int a, int b)>, I0<(T notA, U notB)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C5").WithArguments("C5<T, U>", "I0<(int a, int b)>", "I0<(T notA, U notB)>").WithLocation(7, 14) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var c1 = nodes.OfType<ClassDeclarationSyntax>().First(); Assert.Equal(2, model.GetDeclaredSymbol(c1).AllInterfaces.Count()); Assert.Equal("I0<(System.Int32 a, System.Int32 b)>", model.GetDeclaredSymbol(c1).AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I0<(System.Int32 notA, System.Int32 notB)>", model.GetDeclaredSymbol(c1).AllInterfaces[1].ToTestDisplayString()); var c2 = nodes.OfType<ClassDeclarationSyntax>().Skip(1).First(); Assert.Equal(1, model.GetDeclaredSymbol(c2).AllInterfaces.Count()); Assert.Equal("I0<(System.Int32 a, System.Int32 b)>", model.GetDeclaredSymbol(c2).AllInterfaces[0].ToTestDisplayString()); var c3 = nodes.OfType<ClassDeclarationSyntax>().Skip(2).First(); Assert.Equal(1, model.GetDeclaredSymbol(c3).AllInterfaces.Count()); Assert.Equal("I0<System.Int32>", model.GetDeclaredSymbol(c3).AllInterfaces[0].ToTestDisplayString()); } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_02() { var source = @" public interface I1<T> { void M(); } public interface I2 : I1<(int a, int b)> { } public interface I3 : I1<(int c, int d)> { } public class C1 : I2, I1<(int c, int d)> { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } public class C2 : I1<(int c, int d)>, I2 { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } public class C3 : I1<(int a, int b)>, I1<(int c, int d)> { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } public class C4 : I2, I3 { void I1<(int a, int b)>.M(){} void I1<(int c, int d)>.M(){} } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): error CS8140: 'I1<(int c, int d)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I1<(int a, int b)>'. // public class C1 : I2, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I1<(int c, int d)>", "I1<(int a, int b)>", "C1").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(int a, int b)>.M()").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(int c, int d)>.M()").WithLocation(10, 14), // (16,14): error CS8140: 'I1<(int a, int b)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I1<(int c, int d)>'. // public class C2 : I1<(int c, int d)>, I2 Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I1<(int a, int b)>", "I1<(int c, int d)>", "C2").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C2 : I1<(int c, int d)>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(int c, int d)>.M()").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C2 : I1<(int c, int d)>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(int a, int b)>.M()").WithLocation(16, 14), // (22,14): error CS8140: 'I1<(int c, int d)>' is already listed in the interface list on type 'C3' with different tuple element names, as 'I1<(int a, int b)>'. // public class C3 : I1<(int a, int b)>, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C3").WithArguments("I1<(int c, int d)>", "I1<(int a, int b)>", "C3").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C3 : I1<(int a, int b)>, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(int a, int b)>.M()").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C3 : I1<(int a, int b)>, I1<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(int c, int d)>.M()").WithLocation(22, 14), // (28,14): error CS8140: 'I1<(int c, int d)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I1<(int a, int b)>'. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I1<(int c, int d)>", "I1<(int a, int b)>", "C4").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(int a, int b)>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(int a, int b)>.M()").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(int c, int d)>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(int c, int d)>.M()").WithLocation(28, 14) ); var c1 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C1"); var c1Interfaces = c1.Interfaces; var c1AllInterfaces = c1.AllInterfaces; Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2", c1Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c1Interfaces[1].ToTestDisplayString()); Assert.Equal("I2", c1AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c1AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c1AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c1); var c2 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C2"); var c2Interfaces = c2.Interfaces; var c2AllInterfaces = c2.AllInterfaces; Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2Interfaces[0].ToTestDisplayString()); Assert.Equal("I2", c2Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I2", c2AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c2AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c2); var c3 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C3"); var c3Interfaces = c3.Interfaces; var c3AllInterfaces = c3.AllInterfaces; Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c3Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c3AllInterfaces[1].ToTestDisplayString()); assertExplicitInterfaceImplementations(c3); var c4 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C4"); var c4Interfaces = c4.Interfaces; var c4AllInterfaces = c4.AllInterfaces; Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2", c4Interfaces[0].ToTestDisplayString()); Assert.Equal("I3", c4Interfaces[1].ToTestDisplayString()); Assert.Equal("I2", c4AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c4AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I3", c4AllInterfaces[2].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c4AllInterfaces[3].ToTestDisplayString()); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(INamedTypeSymbol c) { var cMabImplementations = ((IMethodSymbol)c.GetMember("I1<(System.Int32a,System.Int32b)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<(System.Int32 a, System.Int32 b)>.M()", cMabImplementations[0].ToTestDisplayString()); var cMcdImplementations = ((IMethodSymbol)c.GetMember("I1<(System.Int32c,System.Int32d)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<(System.Int32 c, System.Int32 d)>.M()", cMcdImplementations[0].ToTestDisplayString()); } } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_03() { var source = @" public interface I1<T> { void M1(); void M2(); } public class C1 : I1<(int a, int b)> { public void M1() => System.Console.WriteLine(""C1.M1""); void I1<(int a, int b)>.M2() => System.Console.WriteLine(""C1.M2""); } public class C2 : C1, I1<(int c, int d)> { new public void M1() => System.Console.WriteLine(""C2.M1""); void I1<(int c, int d)>.M2() => System.Console.WriteLine(""C2.M2""); static void Main() { var x = (C1)new C2(); var y = (I1<(int a, int b)>)x; y.M1(); y.M2(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); Action<ModuleSymbol> validate = (m) => { bool isMetadata = m is PEModuleSymbol; var c1 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(1, c1Interfaces.Length); Assert.Equal(1, c1AllInterfaces.Length); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c1Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c1AllInterfaces[0].ToTestDisplayString()); var c2 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(1, c2Interfaces.Length); Assert.Equal(2, c2AllInterfaces.Length); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c2AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 c, System.Int32 d)>", c2AllInterfaces[1].ToTestDisplayString()); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M1")).ToTestDisplayString()); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M1")).ToTestDisplayString()); var m2 = (MethodSymbol)((TypeSymbol)c2).GetMember("I1<(System.Int32c,System.Int32d)>.M2"); var m2Implementations = m2.ExplicitInterfaceImplementations; Assert.Equal(1, m2Implementations.Length); Assert.Equal(isMetadata ? "void I1<(System.Int32, System.Int32)>.M2()" : "void I1<(System.Int32 c, System.Int32 d)>.M2()", m2Implementations[0].ToTestDisplayString()); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M2"))); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M2"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C2.M1 C2.M2 "); } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_04() { var source = @" public interface I1<T> { void M(); } public interface I2<I2T> : I1<(I2T a, I2T b)> { } public interface I3<I3T> : I1<(I3T c, I3T d)> { } public class C1<T> : I2<T>, I1<(T c, T d)> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } public class C2<T> : I1<(T c, T d)>, I2<T> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } public class C4<T> : I2<T>, I3<T> { void I1<(T a, T b)>.M(){} void I1<(T c, T d)>.M(){} } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): error CS8140: 'I1<(T c, T d)>' is already listed in the interface list on type 'C1<T>' with different tuple element names, as 'I1<(T a, T b)>'. // public class C1<T> : I2<T>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I1<(T c, T d)>", "I1<(T a, T b)>", "C1<T>").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(T a, T b)>.M()").WithLocation(10, 14), // (10,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<(T c, T d)>.M()").WithLocation(10, 14), // (16,14): error CS8140: 'I1<(T a, T b)>' is already listed in the interface list on type 'C2<T>' with different tuple element names, as 'I1<(T c, T d)>'. // public class C2<T> : I1<(T c, T d)>, I2<T> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I1<(T a, T b)>", "I1<(T c, T d)>", "C2<T>").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C2<T> : I1<(T c, T d)>, I2<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(T c, T d)>.M()").WithLocation(16, 14), // (16,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C2<T> : I1<(T c, T d)>, I2<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<(T a, T b)>.M()").WithLocation(16, 14), // (22,14): error CS8140: 'I1<(T c, T d)>' is already listed in the interface list on type 'C3<T>' with different tuple element names, as 'I1<(T a, T b)>'. // public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C3").WithArguments("I1<(T c, T d)>", "I1<(T a, T b)>", "C3<T>").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(T a, T b)>.M()").WithLocation(22, 14), // (22,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C3<T> : I1<(T a, T b)>, I1<(T c, T d)> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<(T c, T d)>.M()").WithLocation(22, 14), // (28,14): error CS8140: 'I1<(T c, T d)>' is already listed in the interface list on type 'C4<T>' with different tuple element names, as 'I1<(T a, T b)>'. // public class C4<T> : I2<T>, I3<T> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I1<(T c, T d)>", "I1<(T a, T b)>", "C4<T>").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(T a, T b)>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(T a, T b)>.M()").WithLocation(28, 14), // (28,14): error CS8646: 'I1<(T c, T d)>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<(T c, T d)>.M()").WithLocation(28, 14) ); var c1 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C1`1"); var c1Interfaces = c1.Interfaces; var c1AllInterfaces = c1.AllInterfaces; Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2<T>", c1Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c1Interfaces[1].ToTestDisplayString()); Assert.Equal("I2<T>", c1AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c1AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c1AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c1); var c2 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C2`1"); var c2Interfaces = c2.Interfaces; var c2AllInterfaces = c2.AllInterfaces; Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<(T c, T d)>", c2Interfaces[0].ToTestDisplayString()); Assert.Equal("I2<T>", c2Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c2AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I2<T>", c2AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c2AllInterfaces[2].ToTestDisplayString()); assertExplicitInterfaceImplementations(c2); var c3 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C3`1"); var c3Interfaces = c3.Interfaces; var c3AllInterfaces = c3.AllInterfaces; Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<(T a, T b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c3Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c3AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c3AllInterfaces[1].ToTestDisplayString()); assertExplicitInterfaceImplementations(c3); var c4 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C4`1"); var c4Interfaces = c4.Interfaces; var c4AllInterfaces = c4.AllInterfaces; Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2<T>", c4Interfaces[0].ToTestDisplayString()); Assert.Equal("I3<T>", c4Interfaces[1].ToTestDisplayString()); Assert.Equal("I2<T>", c4AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c4AllInterfaces[1].ToTestDisplayString()); Assert.Equal("I3<T>", c4AllInterfaces[2].ToTestDisplayString()); Assert.Equal("I1<(T c, T d)>", c4AllInterfaces[3].ToTestDisplayString()); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(INamedTypeSymbol c) { var cMabImplementations = ((IMethodSymbol)c.GetMember("I1<(Ta,Tb)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<(T a, T b)>.M()", cMabImplementations[0].ToTestDisplayString()); var cMcdImplementations = ((IMethodSymbol)c.GetMember("I1<(Tc,Td)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<(T c, T d)>.M()", cMcdImplementations[0].ToTestDisplayString()); } } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_05() { var source = @" public interface I1<T> { void M(); } public class C3<T, U> : I1<(T a, T b)>, I1<(U c, U d)> { void I1<(T a, T b)>.M(){} void I1<(U c, U d)>.M(){} } "; var comp = (Compilation)CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS0695: 'C3<T, U>' cannot implement both 'I1<(T a, T b)>' and 'I1<(U c, U d)>' because they may unify for some type parameter substitutions // public class C3<T, U> : I1<(T a, T b)>, I1<(U c, U d)> Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I1<(T a, T b)>", "I1<(U c, U d)>").WithLocation(7, 14) ); var c3 = (INamedTypeSymbol)comp.GetTypeByMetadataName("C3`2"); var c3Interfaces = c3.Interfaces; var c3AllInterfaces = c3.AllInterfaces; Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<(T a, T b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(U c, U d)>", c3Interfaces[1].ToTestDisplayString()); Assert.Equal("I1<(T a, T b)>", c3AllInterfaces[0].ToTestDisplayString()); Assert.Equal("I1<(U c, U d)>", c3AllInterfaces[1].ToTestDisplayString()); assertExplicitInterfaceImplementations(c3); void assertExplicitInterfaceImplementations(INamedTypeSymbol c) { var cMabImplementations = ((IMethodSymbol)c.GetMember("I1<(Ta,Tb)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<(T a, T b)>.M()", cMabImplementations[0].ToTestDisplayString()); var cMcdImplementations = ((IMethodSymbol)c.GetMember("I1<(Uc,Ud)>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<(U c, U d)>.M()", cMcdImplementations[0].ToTestDisplayString()); } } [Fact] [WorkItem(31977, "https://github.com/dotnet/roslyn/issues/31977")] public void DuplicateInterfaceDetectionWithDifferentTupleNames_06() { var source = @" public interface I1<T> { void M(); } public class C3 : I1<(int a, int b)> { void I1<(int c, int d)>.M(){} } public class C4 : I1<(int c, int d)> { void I1<(int c, int d)>.M(){} } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,10): error CS0540: 'C3.I1<(int c, int d)>.M()': containing type does not implement interface 'I1<(int c, int d)>' // void I1<(int c, int d)>.M(){} Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<(int c, int d)>").WithArguments("C3.I1<(int c, int d)>.M()", "I1<(int c, int d)>").WithLocation(9, 10) ); var c3 = comp.GetTypeByMetadataName("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3Interfaces[0].ToTestDisplayString()); Assert.Equal("I1<(System.Int32 a, System.Int32 b)>", c3AllInterfaces[0].ToTestDisplayString()); var mImplementations = ((MethodSymbol)c3.GetMember("I1<(System.Int32c,System.Int32d)>.M")).GetPublicSymbol().ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal("void I1<(System.Int32 c, System.Int32 d)>.M()", mImplementations[0].ToTestDisplayString()); Assert.Equal("void C3.I1<(System.Int32 c, System.Int32 d)>.M()", c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M")).ToTestDisplayString()); Assert.Equal("void C3.I1<(System.Int32 c, System.Int32 d)>.M()", c3.FindImplementationForInterfaceMember(comp.GetTypeByMetadataName("C4").InterfacesNoUseSiteDiagnostics()[0].GetMember("M")).ToTestDisplayString()); } [Fact] public void AccessCheckLooksInsideTuples() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } public class C { (C2.C3, int) M() { throw new System.Exception(); } } public class C2 { private class C3 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0122: 'C2.C3' is inaccessible due to its protection level // (C2.C3, int) M() { throw new System.Exception(); } Diagnostic(ErrorCode.ERR_BadAccess, "C3").WithArguments("C2.C3").WithLocation(11, 9) ); } [Fact] public void AccessCheckLooksInsideTuples2() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } public class C { public (C2, int) M() { throw new System.Exception(); } private class C2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,22): error CS0050: Inconsistent accessibility: return type '(C.C2, int)' is less accessible than method 'C.M()' // public (C2, int) M() { throw new System.Exception(); } Diagnostic(ErrorCode.ERR_BadVisReturnType, "M").WithArguments("C.M()", "(C.C2, int)").WithLocation(11, 22) ); } [Fact] public void ImplicitInterfaceImplementationWithDifferentTupleNames() { var source = @" public interface I0<T> { T get(); void set(T x); } public class C : I0<(int a, int b)> { public (int notA, int notB) get() { return (1, 2); } public void set((int notA, int notB) y) { } } public class D : I0<(int a, int b)> { public (int a, int b) get() { return (1, 2); } public void set((int a, int b) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): error CS8141: The tuple element names in the signature of method 'C.set((int notA, int notB))' must match the tuple element names of interface method 'I0<(int a, int b)>.set((int a, int b))'. // public void set((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "set").WithArguments("C.set((int notA, int notB))", "I0<(int a, int b)>.set((int a, int b))").WithLocation(10, 17), // (9,33): error CS8141: The tuple element names in the signature of method 'C.get()' must match the tuple element names of interface method 'I0<(int a, int b)>.get()'. // public (int notA, int notB) get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "get").WithArguments("C.get()", "I0<(int a, int b)>.get()").WithLocation(9, 33) ); } [Fact] public void ImplicitAndExplicitInterfaceImplementationWithDifferentTupleNames() { var source = @" public interface I0<T> { T get(); void set(T x); } public class C1 : I0<(int a, int b)> { public (int a, int b) get() { return (1, 2); } public void set((int a, int b) y) { } } public class C2 : C1, I0<(int a, int b)> { (int a, int b) I0<(int a, int b)>.get() { return (1, 2); } void I0<(int a, int b)>.set((int a, int b) y) { } } public class D1 : I0<(int a, int b)> { public (int notA, int notB) get() { return (1, 2); } public void set((int notA, int notB) y) { } } public class D2 : D1, I0<(int notA, int notB)> { (int a, int b) I0<(int a, int b)>.get() { return (1, 2); } void I0<(int a, int b)>.set((int a, int b) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,17): error CS8141: The tuple element names in the signature of method 'D1.set((int notA, int notB))' must match the tuple element names of interface method 'I0<(int a, int b)>.set((int a, int b))' (including on the return type). // public void set((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "set").WithArguments("D1.set((int notA, int notB))", "I0<(int a, int b)>.set((int a, int b))").WithLocation(20, 17), // (19,33): error CS8141: The tuple element names in the signature of method 'D1.get()' must match the tuple element names of interface method 'I0<(int a, int b)>.get()' (including on the return type). // public (int notA, int notB) get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "get").WithArguments("D1.get()", "I0<(int a, int b)>.get()").WithLocation(19, 33), // (25,10): error CS0540: 'D2.I0<(int a, int b)>.set((int a, int b))': containing type does not implement interface 'I0<(int a, int b)>' // void I0<(int a, int b)>.set((int a, int b) y) { } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int a, int b)>").WithArguments("D2.I0<(int a, int b)>.set((int a, int b))", "I0<(int a, int b)>").WithLocation(25, 10), // (24,20): error CS0540: 'D2.I0<(int a, int b)>.get()': containing type does not implement interface 'I0<(int a, int b)>' // (int a, int b) I0<(int a, int b)>.get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int a, int b)>").WithArguments("D2.I0<(int a, int b)>.get()", "I0<(int a, int b)>").WithLocation(24, 20) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ImplicitAndExplicitInterfaceImplementationWithNoNames() { var source = @" public interface I0<T> { T get(); void set(T x); } public class C1 : I0<(int a, int b)> { public (int a, int b) get() { return (1, 2); } public void set((int a, int b) y) { } } public class C2 : C1, I0<(int a, int b)> { (int, int) I0<(int, int)>.get() { return (1, 2); } void I0<(int, int)>.set((int, int) y) { } } public class D1 : I0<(int, int)> { public (int, int) get() { return (1, 2); } public void set((int, int) y) { } } public class D2 : D1, I0<(int, int)> { (int, int) I0<(int, int)>.get() { return (1, 2); } void I0<(int, int)>.set((int, int) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,10): error CS0540: 'C2.I0<(int, int)>.set((int, int))': containing type does not implement interface 'I0<(int, int)>' // void I0<(int, int)>.set((int, int) y) { } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int, int)>").WithArguments("C2.I0<(int, int)>.set((int, int))", "I0<(int, int)>").WithLocation(15, 10), // (14,16): error CS0540: 'C2.I0<(int, int)>.get()': containing type does not implement interface 'I0<(int, int)>' // (int, int) I0<(int, int)>.get() { return (1, 2); } Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I0<(int, int)>").WithArguments("C2.I0<(int, int)>.get()", "I0<(int, int)>").WithLocation(14, 16) ); } [Fact] public void PartialMethodsWithDifferentTupleNames() { var source = @" public partial class C { partial void M1((int a, int b) x); partial void M2((int a, int b) x); partial void M3((int a, int b) x); } public partial class C { partial void M1((int notA, int notB) y) { } partial void M2((int, int) y) { } partial void M3((int a, int b) y) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS8142: Both partial method declarations, 'C.M1((int a, int b))' and 'C.M1((int notA, int notB))', must use the same tuple element names. // partial void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentTupleNames, "M1").WithArguments("C.M1((int a, int b))", "C.M1((int notA, int notB))").WithLocation(10, 18), // (10,18): warning CS8826: Partial method declarations 'void C.M1((int a, int b) x)' and 'void C.M1((int notA, int notB) y)' have signature differences. // partial void M1((int notA, int notB) y) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M1").WithArguments("void C.M1((int a, int b) x)", "void C.M1((int notA, int notB) y)").WithLocation(10, 18), // (11,18): error CS8142: Both partial method declarations, 'C.M2((int a, int b))' and 'C.M2((int, int))', must use the same tuple element names. // partial void M2((int, int) y) { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentTupleNames, "M2").WithArguments("C.M2((int a, int b))", "C.M2((int, int))").WithLocation(11, 18), // (11,18): warning CS8826: Partial method declarations 'void C.M2((int a, int b) x)' and 'void C.M2((int, int) y)' have signature differences. // partial void M2((int, int) y) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M2").WithArguments("void C.M2((int a, int b) x)", "void C.M2((int, int) y)").WithLocation(11, 18), // (12,18): warning CS8826: Partial method declarations 'void C.M3((int a, int b) x)' and 'void C.M3((int a, int b) y)' have signature differences. // partial void M3((int a, int b) y) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M3").WithArguments("void C.M3((int a, int b) x)", "void C.M3((int a, int b) y)").WithLocation(12, 18) ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseInterfaces() { var source = @" public interface I0<T> { } public partial class C : I0<(int a, int b)> { } public partial class C : I0<(int notA, int notB)> { } public partial class C : I0<(int, int)> { } public partial class D : I0<(int a, int b)> { } public partial class D : I0<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,22): error CS8140: 'I0<(int notA, int notB)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I0<(int a, int b)>'. // public partial class C : I0<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I0<(int notA, int notB)>", "I0<(int a, int b)>", "C").WithLocation(3, 22), // (3,22): error CS8140: 'I0<(int, int)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I0<(int a, int b)>'. // public partial class C : I0<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I0<(int, int)>", "I0<(int a, int b)>", "C").WithLocation(3, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseTypes() { var source = @" public class Base<T> { } public partial class C1 : Base<(int a, int b)> { } public partial class C1 : Base<(int notA, int notB)> { } public partial class C2 : Base<(int a, int b)> { } public partial class C2 : Base<(int, int)> { } public partial class C3 : Base<(int a, int b)> { } public partial class C3 : Base<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,22): error CS0263: Partial declarations of 'C2' must not specify different base classes // public partial class C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 22), // (3,22): error CS0263: Partial declarations of 'C1' must not specify different base classes // public partial class C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 22) ); } [Fact] public void IndirectInterfaceBasesWithDifferentTupleNames() { var source = @" public interface I0<T> { } public interface I1 : I0<(int a, int b)> { } public interface I2 : I0<(int notA, int notB)> { } public interface I3 : I0<(int a, int b)> { } public class C : I1, I2 { } public class D : I1, I3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8140: 'I0<(int notA, int notB)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I0<(int a, int b)>'. // public class C : I1, I2 { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I0<(int notA, int notB)>", "I0<(int a, int b)>", "C").WithLocation(7, 14) ); } [Fact] public void InterfaceUnification() { var source = @" public interface I0<T1> { } public class C1<T2> : I0<(int, int)>, I0<(T2, T2)> { } public class C2<T2> : I0<(int, int)>, I0<System.ValueTuple<T2, T2>> { } public class C3<T2> : I0<(int a, int b)>, I0<(T2, T2)> { } public class C4<T2> : I0<(int a, int b)>, I0<(T2 a, T2 b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS0695: 'C4<T2>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T2 a, T2 b)>' because they may unify for some type parameter substitutions // public class C4<T2> : I0<(int a, int b)>, I0<(T2 a, T2 b)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T2>", "I0<(int a, int b)>", "I0<(T2 a, T2 b)>").WithLocation(6, 14), // (3,14): error CS0695: 'C1<T2>' cannot implement both 'I0<(int, int)>' and 'I0<(T2, T2)>' because they may unify for some type parameter substitutions // public class C1<T2> : I0<(int, int)>, I0<(T2, T2)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T2>", "I0<(int, int)>", "I0<(T2, T2)>").WithLocation(3, 14), // (5,14): error CS0695: 'C3<T2>' cannot implement both 'I0<(int a, int b)>' and 'I0<(T2, T2)>' because they may unify for some type parameter substitutions // public class C3<T2> : I0<(int a, int b)>, I0<(T2, T2)> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T2>", "I0<(int a, int b)>", "I0<(T2, T2)>").WithLocation(5, 14), // (4,14): error CS0695: 'C2<T2>' cannot implement both 'I0<(int, int)>' and 'I0<(T2, T2)>' because they may unify for some type parameter substitutions // public class C2<T2> : I0<(int, int)>, I0<System.ValueTuple<T2, T2>> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T2>", "I0<(int, int)>", "I0<(T2, T2)>").WithLocation(4, 14) ); } [Fact] public void ConversionToBase() { var source = @" public class Base<T> { } public class Derived : Base<(int a, int b)> { public static explicit operator Base<(int, int)>(Derived x) { return null; } public static explicit operator Derived(Base<(int, int)> x) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed // public static explicit operator Derived(Base<(int, int)> x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37), // (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed // public static explicit operator Base<(int, int)>(Derived x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37) ); } [Fact] public void InterfaceUnification2() { var source = @" public interface I0<T1> { } public class Derived<T> : I0<Derived<(T, T)>>, I0<T> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); // Didn't run out of memory in trying to substitute T with Derived<(T, T)> in a loop } [Fact] public void AmbiguousExtensionMethodWithDifferentTupleNames() { var source = @" public static class C1 { public static void M(this string self, (int, int) x) { System.Console.Write($""C1.M({x}) ""); } } public static class C2 { public static void M(this string self, (int a, int b) x) { System.Console.Write($""C2.M({x}) ""); } } public static class C3 { public static void M(this string self, (int c, int d) x) { System.Console.Write($""C3.M({x}) ""); } } public class D { public static void Main() { ""string"".M((1, 1)); ""string"".M((a: 1, b: 1)); ""string"".M((c: 1, d: 1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,18): error CS0121: The call is ambiguous between the following methods or properties: 'C1.M(string, (int, int))' and 'C2.M(string, (int a, int b))' // "string".M((1, 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C1.M(string, (int, int))", "C2.M(string, (int a, int b))").WithLocation(18, 18), // (19,18): error CS0121: The call is ambiguous between the following methods or properties: 'C1.M(string, (int, int))' and 'C2.M(string, (int a, int b))' // "string".M((a: 1, b: 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C1.M(string, (int, int))", "C2.M(string, (int a, int b))").WithLocation(19, 18), // (20,18): error CS0121: The call is ambiguous between the following methods or properties: 'C1.M(string, (int, int))' and 'C2.M(string, (int a, int b))' // "string".M((c: 1, d: 1)); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C1.M(string, (int, int))", "C2.M(string, (int a, int b))").WithLocation(20, 18) ); } [Fact] public void InheritFromMetadataWithDifferentNames() { const string ilSource = @" .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] // = (int a, int b) .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 01 61 01 62 00 00 ) // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base::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 [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Base::.ctor } // end of class Base .class public auto ansi beforefieldinit Base2 extends Base { .method public hidebysig virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] // = (int notA, int notB) .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = ( 01 00 02 00 00 00 04 6e 6f 74 41 04 6e 6f 74 42 00 00 ) // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base2::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 Base::.ctor() IL_0006: nop IL_0007: ret } // end of method Base2::.ctor } // end of class Base2 "; string sourceWithMatchingNames = @" public class C : Base2 { public override (int notA, int notB) M() { return (1, 2); } }"; var compMatching = CreateCompilationWithILAndMscorlib40(sourceWithMatchingNames, ilSource, targetFramework: TargetFramework.Mscorlib46Extended, options: TestOptions.DebugDll); compMatching.VerifyEmitDiagnostics(); string sourceWithDifferentNames1 = @" public class C : Base2 { public override (int a, int b) M() { return (1, 2); } }"; var compDifferent1 = CreateCompilationWithILAndMscorlib40(sourceWithDifferentNames1, ilSource, targetFramework: TargetFramework.Mscorlib46Extended, options: TestOptions.DebugDll); compDifferent1.VerifyDiagnostics( // (4,36): error CS8139: 'C.M()': cannot change tuple element names when overriding inherited member 'Base2.M()' // public override (int a, int b) M() { return (1, 2); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("C.M()", "Base2.M()").WithLocation(4, 36) ); string sourceWithDifferentNames2 = @" public class C : Base2 { public override (int, int) M() { return (1, 2); } }"; var compDifferent2 = CreateCompilationWithILAndMscorlib40(sourceWithDifferentNames2, ilSource, targetFramework: TargetFramework.Mscorlib46Extended, options: TestOptions.DebugDll); compDifferent2.VerifyDiagnostics(); } [Fact] public void TupleNamesInAnonymousTypes() { var source = @" public class C { public static void Main() { var x1 = new { Tuple = (a: 1, b: 2) }; var x2 = new { Tuple = (c: 1, 2) }; x2 = x1; System.Console.Write(x1.Tuple.a); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x1 = nodes.OfType<VariableDeclaratorSyntax>().First(); Assert.Equal("<anonymous type: (System.Int32 a, System.Int32 b) Tuple> x1", model.GetDeclaredSymbol(x1).ToTestDisplayString()); var x2 = nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First(); Assert.Equal("<anonymous type: (System.Int32 c, System.Int32) Tuple> x2", model.GetDeclaredSymbol(x2).ToTestDisplayString()); } [Fact] public void OverriddenPropertyWithDifferentTupleNamesInReturn() { var source = @" public class Base { public virtual (int a, int b) P1 { get; set; } public virtual (int a, int b) P2 { get; set; } public virtual (int a, int b)[] P3 { get; set; } public virtual System.Nullable<(int a, int b)> P4 { get; set; } public virtual ((int a, int b) c, int d) P5 { get; set; } public virtual (dynamic a, dynamic b) P6 { get; set; } } public class Derived : Base { public override (int a, int b) P1 { get; set; } public override (int notA, int notB) P2 { get; set; } public override (int notA, int notB)[] P3 { get; set; } public override System.Nullable<(int notA, int notB)> P4 { get; set; } public override ((int notA, int notB) c, int d) P5 { get; set; } public override (dynamic notA, dynamic) P6 { get; set; } } "; var comp = CreateCompilation(source, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (14,42): error CS8139: 'Derived.P2': cannot change tuple element names when overriding inherited member 'Base.P2' // public override (int notA, int notB) P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P2").WithArguments("Derived.P2", "Base.P2").WithLocation(14, 42), // (14,47): error CS8139: 'Derived.P2.get': cannot change tuple element names when overriding inherited member 'Base.P2.get' // public override (int notA, int notB) P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P2.get", "Base.P2.get").WithLocation(14, 47), // (14,52): error CS8139: 'Derived.P2.set': cannot change tuple element names when overriding inherited member 'Base.P2.set' // public override (int notA, int notB) P2 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P2.set", "Base.P2.set").WithLocation(14, 52), // (15,44): error CS8139: 'Derived.P3': cannot change tuple element names when overriding inherited member 'Base.P3' // public override (int notA, int notB)[] P3 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P3").WithArguments("Derived.P3", "Base.P3").WithLocation(15, 44), // (15,49): error CS8139: 'Derived.P3.get': cannot change tuple element names when overriding inherited member 'Base.P3.get' // public override (int notA, int notB)[] P3 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P3.get", "Base.P3.get").WithLocation(15, 49), // (15,54): error CS8139: 'Derived.P3.set': cannot change tuple element names when overriding inherited member 'Base.P3.set' // public override (int notA, int notB)[] P3 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P3.set", "Base.P3.set").WithLocation(15, 54), // (16,59): error CS8139: 'Derived.P4': cannot change tuple element names when overriding inherited member 'Base.P4' // public override System.Nullable<(int notA, int notB)> P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P4").WithArguments("Derived.P4", "Base.P4").WithLocation(16, 59), // (16,64): error CS8139: 'Derived.P4.get': cannot change tuple element names when overriding inherited member 'Base.P4.get' // public override System.Nullable<(int notA, int notB)> P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P4.get", "Base.P4.get").WithLocation(16, 64), // (16,69): error CS8139: 'Derived.P4.set': cannot change tuple element names when overriding inherited member 'Base.P4.set' // public override System.Nullable<(int notA, int notB)> P4 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P4.set", "Base.P4.set").WithLocation(16, 69), // (17,53): error CS8139: 'Derived.P5': cannot change tuple element names when overriding inherited member 'Base.P5' // public override ((int notA, int notB) c, int d) P5 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P5").WithArguments("Derived.P5", "Base.P5").WithLocation(17, 53), // (17,58): error CS8139: 'Derived.P5.get': cannot change tuple element names when overriding inherited member 'Base.P5.get' // public override ((int notA, int notB) c, int d) P5 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P5.get", "Base.P5.get").WithLocation(17, 58), // (17,63): error CS8139: 'Derived.P5.set': cannot change tuple element names when overriding inherited member 'Base.P5.set' // public override ((int notA, int notB) c, int d) P5 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P5.set", "Base.P5.set").WithLocation(17, 63), // (18,45): error CS8139: 'Derived.P6': cannot change tuple element names when overriding inherited member 'Base.P6' // public override (dynamic notA, dynamic) P6 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "P6").WithArguments("Derived.P6", "Base.P6").WithLocation(18, 45), // (18,50): error CS8139: 'Derived.P6.get': cannot change tuple element names when overriding inherited member 'Base.P6.get' // public override (dynamic notA, dynamic) P6 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "get").WithArguments("Derived.P6.get", "Base.P6.get").WithLocation(18, 50), // (18,55): error CS8139: 'Derived.P6.set': cannot change tuple element names when overriding inherited member 'Base.P6.set' // public override (dynamic notA, dynamic) P6 { get; set; } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "set").WithArguments("Derived.P6.set", "Base.P6.set").WithLocation(18, 55) ); } [Fact] public void DefiniteAssignment001() { var source = @" using System; class C { static void Main(string[] args) { (string A, string B) ss; ss.A = ""q""; ss.Item2 = ""w""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, w) "); } [Fact] public void DefiniteAssignment002() { var source = @" using System; class C { static void Main(string[] args) { (string A, string B) ss; ss.A = ""q""; ss.B = ""q""; ss.Item1 = ""w""; ss.Item2 = ""w""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(w, w)"); } [Fact] public void DefiniteAssignment003() { var source = @" using System; class C { static void Main(string[] args) { (string A, (string B, string C) D) ss; ss.A = ""q""; ss.D.B = ""w""; ss.D.C = ""e""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, (w, e)) "); } [Fact] public void DefiniteAssignment004() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.I8 = ""q""; ss.I9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, q, q, q) "); } [Fact] public void DefiniteAssignment005() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.Item1 = ""q""; ss.Item2 = ""q""; ss.Item3 = ""q""; ss.Item4 = ""q""; ss.Item5 = ""q""; ss.Item6 = ""q""; ss.Item7 = ""q""; ss.Item8 = ""q""; ss.Item9 = ""q""; ss.Item10 = ""q""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, q, q, q) "); } [Fact] public void DefiniteAssignment006() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.Item1 = ""q""; ss.I2 = ""q""; ss.Item3 = ""q""; ss.I4 = ""q""; ss.Item5 = ""q""; ss.I6 = ""q""; ss.Item7 = ""q""; ss.I8 = ""q""; ss.Item9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, q, q, q) "); } [Fact] public void DefiniteAssignment007() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.Item1 = ""q""; ss.I2 = ""q""; ss.Item3 = ""q""; ss.I4 = ""q""; ss.Item5 = ""q""; ss.I6 = ""q""; ss.Item7 = ""q""; ss.I8 = ""q""; ss.Item9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss.Rest); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q) "); } [Fact] public void DefiniteAssignment008() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.I8 = ""q""; ss.Item9 = ""q""; ss.I10 = ""q""; System.Console.WriteLine(ss.Rest); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q) "); } [Fact] public void DefiniteAssignment009() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; Assign(out ss.Rest); System.Console.WriteLine(ss); } static void Assign<T>(out T v) { v = default(T); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (q, q, q, q, q, q, q, , , ) "); } [Fact] public void DefiniteAssignment010() { var source = @" using System; class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8, string I9, string I10) ss; Assign(out ss.Rest, (""q"", ""w"", ""e"")); System.Console.WriteLine(ss.I9); } static void Assign<T>(out T r, T v) { r = v; } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"w"); } [Fact] public void DefiniteAssignment011() { var source = @" class C { static void Main(string[] args) { if (1.ToString() == 2.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); } else if (1.ToString() == 3.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; // ss.I8 = ""q""; System.Console.WriteLine(ss); } else { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; // ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); // should fail } } } namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { this.Item1 = item1; } } public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; // public TRest Rest; oops, Rest is missing public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; // Rest = rest; } } } " + TestResources.NetFX.ValueTuple.tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "comp", parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (8,13): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (string I1, Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, @"(string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 13), // (30,13): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (string I1, Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, @"(string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(30, 13), // (52,13): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (string I1, Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, @"(string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(52, 13), // (70,38): error CS0165: Use of unassigned local variable 'ss' // System.Console.WriteLine(ss); // should fail Diagnostic(ErrorCode.ERR_UseDefViolation, "ss").WithArguments("ss").WithLocation(70, 38) ); } [Fact] public void DefiniteAssignment012() { var source = @" class C { static void Main(string[] args) { if (1.ToString() == 2.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); } else if (1.ToString() == 3.ToString()) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; // ss.I8 = ""q""; System.Console.WriteLine(ss); // should fail1 } else { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; // ss.I7 = ""q""; ss.I8 = ""q""; System.Console.WriteLine(ss); // should fail2 } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (48,38): error CS0165: Use of unassigned local variable 'ss' // System.Console.WriteLine(ss); // should fail1 Diagnostic(ErrorCode.ERR_UseDefViolation, "ss").WithArguments("ss").WithLocation(48, 38), // (70,38): error CS0165: Use of unassigned local variable 'ss' // System.Console.WriteLine(ss); // should fail2 Diagnostic(ErrorCode.ERR_UseDefViolation, "ss").WithArguments("ss").WithLocation(70, 38) ); } [Fact] public void DefiniteAssignment013() { var source = @" class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.I2 = ""q""; ss.I3 = ""q""; ss.I4 = ""q""; ss.I5 = ""q""; ss.I6 = ""q""; ss.I7 = ""q""; ss.Item1 = ""q""; ss.Item2 = ""q""; ss.Item3 = ""q""; ss.Item4 = ""q""; ss.Item5 = ""q""; ss.Item6 = ""q""; ss.Item7 = ""q""; System.Console.WriteLine(ss.Rest); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (31,34): error CS0170: Use of possibly unassigned field 'Rest' // System.Console.WriteLine(ss.Rest); Diagnostic(ErrorCode.ERR_UseDefViolationField, "ss.Rest").WithArguments("Rest").WithLocation(31, 34) ); } [Fact] public void DefiniteAssignment014() { var source = @" class C { static void Main(string[] args) { (string I1, string I2, string I3, string I4, string I5, string I6, string I7, string I8) ss; ss.I1 = ""q""; ss.Item2 = ""aa""; System.Console.WriteLine(ss.Item1); System.Console.WriteLine(ss.I2); System.Console.WriteLine(ss.I3); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (21,34): error CS0170: Use of possibly unassigned field 'I3' // System.Console.WriteLine(ss.I3); Diagnostic(ErrorCode.ERR_UseDefViolationField, "ss.I3").WithArguments("I3").WithLocation(21, 34) ); } [Fact] public void DefiniteAssignment015() { var source = @" using System; using System.Threading.Tasks; class C { static void Main(string[] args) { var v = Test().Result; } static async Task<long> Test() { (long a, int b) v1; (byte x, int y) v2; v1.a = 5; v2.x = 5; // no need to persist across await since it is unused after it. System.Console.WriteLine(v2.Item1); await Task.Yield(); // this is assigned and persisted across await return v1.Item1; } } " + trivial2uple + tupleattributes_cs; var verifier = CompileAndVerify(source, targetFramework: TargetFramework.Mscorlib46, expectedOutput: @"5", options: TestOptions.ReleaseExe); // NOTE: !!! There should be NO IL local for " (long a, int b) v1 " , it should be captured instead // NOTE: !!! There should be an IL local for " (byte x, int y) v2 " , it should not be captured verifier.VerifyIL("C.<Test>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 193 (0xc1) .maxstack 3 .locals init (int V_0, long V_1, System.ValueTuple<byte, int> V_2, //v2 System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3, System.Runtime.CompilerServices.YieldAwaitable V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Test>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: ldarg.0 IL_000b: ldflda ""System.ValueTuple<long, int> C.<Test>d__1.<v1>5__2"" IL_0010: ldc.i4.5 IL_0011: conv.i8 IL_0012: stfld ""long System.ValueTuple<long, int>.Item1"" IL_0017: ldloca.s V_2 IL_0019: ldc.i4.5 IL_001a: stfld ""byte System.ValueTuple<byte, int>.Item1"" IL_001f: ldloc.2 IL_0020: ldfld ""byte System.ValueTuple<byte, int>.Item1"" IL_0025: call ""void System.Console.WriteLine(int)"" IL_002a: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_002f: stloc.s V_4 IL_0031: ldloca.s V_4 IL_0033: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0038: stloc.3 IL_0039: ldloca.s V_3 IL_003b: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int C.<Test>d__1.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.3 IL_004d: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long> C.<Test>d__1.<>t__builder"" IL_0058: ldloca.s V_3 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<Test>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<Test>d__1)"" IL_0060: leave.s IL_00c0 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1.<>u__1"" IL_0068: stloc.3 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<Test>d__1.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int C.<Test>d__1.<>1__state"" IL_007e: ldloca.s V_3 IL_0080: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0085: ldarg.0 IL_0086: ldflda ""System.ValueTuple<long, int> C.<Test>d__1.<v1>5__2"" IL_008b: ldfld ""long System.ValueTuple<long, int>.Item1"" IL_0090: stloc.1 IL_0091: leave.s IL_00ac } catch System.Exception { IL_0093: stloc.s V_5 IL_0095: ldarg.0 IL_0096: ldc.i4.s -2 IL_0098: stfld ""int C.<Test>d__1.<>1__state"" IL_009d: ldarg.0 IL_009e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long> C.<Test>d__1.<>t__builder"" IL_00a3: ldloc.s V_5 IL_00a5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long>.SetException(System.Exception)"" IL_00aa: leave.s IL_00c0 } IL_00ac: ldarg.0 IL_00ad: ldc.i4.s -2 IL_00af: stfld ""int C.<Test>d__1.<>1__state"" IL_00b4: ldarg.0 IL_00b5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long> C.<Test>d__1.<>t__builder"" IL_00ba: ldloc.1 IL_00bb: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<long>.SetResult(long)"" IL_00c0: ret } "); } [Fact] public void StructInStruct() { var source = @" public struct S { public (S, S) field; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,19): error CS0523: Struct member 'S.field' of type '(S, S)' causes a cycle in the struct layout // public (S, S) field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("S.field", "(S, S)").WithLocation(4, 19) ); } [Fact] public void RetargetTupleErrorType() { var lib_cs = @" public class A { public static (int, int) M() { return (1, 2); } } "; var source = @" public class B { void M2() { return A.M(); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: s_valueTupleRefs); lib.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, references: new[] { lib.ToMetadataReference() }); comp.VerifyDiagnostics( // (4,24): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. // void M2() { return A.M(); } Diagnostic(ErrorCode.ERR_NoTypeDef, "A.M").WithArguments("(, )", "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").WithLocation(4, 24) ); var methodM = comp.GetMember<MethodSymbol>("A.M"); Assert.IsType<RetargetingMethodSymbol>(methodM); Assert.Equal("(System.Int32, System.Int32)[missing]", methodM.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.IsType<ConstructedErrorTypeSymbol>(methodM.ReturnType); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>(methodM.ReturnType.OriginalDefinition); Assert.True(methodM.ReturnType.IsTupleType); Assert.True(methodM.ReturnType.IsErrorType()); foreach (var item in methodM.ReturnType.TupleElements) { Assert.IsType<TupleErrorFieldSymbol>(item); Assert.False(item.IsExplicitlyNamedTupleElement); } } [Fact] public void RetargetTupleErrorType_WithNames() { var lib_cs = @" public class A { public static (int Item1, int Bob) M() { return (1, 2); } } "; var source = @" public class B { void M2() { return A.M(); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: s_valueTupleRefs); lib.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, references: new[] { lib.ToMetadataReference() }); comp.VerifyDiagnostics( // (4,24): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. // void M2() { return A.M(); } Diagnostic(ErrorCode.ERR_NoTypeDef, "A.M").WithArguments("(, )", "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").WithLocation(4, 24) ); var methodM = comp.GetMember<MethodSymbol>("A.M"); Assert.IsType<RetargetingMethodSymbol>(methodM); Assert.Equal("(System.Int32 Item1, System.Int32 Bob)[missing]", methodM.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.IsType<ConstructedErrorTypeSymbol>(methodM.ReturnType); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>(methodM.ReturnType.OriginalDefinition); Assert.True(methodM.ReturnType.IsTupleType); Assert.True(methodM.ReturnType.IsErrorType()); foreach (var item in methodM.ReturnType.TupleElements) { Assert.IsType<TupleErrorFieldSymbol>(item); Assert.True(item.IsExplicitlyNamedTupleElement); } } [Fact, WorkItem(13088, "https://github.com/dotnet/roslyn/issues/13088")] public void AssignNullWithMissingValueTuple() { var source = @" public class S { (int, int) t = null; } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (4,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) t = null; Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(4, 5) ); } [Fact, WorkItem(11302, "https://github.com/dotnet/roslyn/issues/11302")] public void CrashInVisitCallReceiverOnBadTupleSyntax() { var source1 = @" public static class C1 { public void M1(this int x, (int, int))) { System.Console.WriteLine(""M1""); } } " + trivial2uple + tupleattributes_cs; var source2 = @" public static class C2 { public void M1(this int x, (int, int))) { System.Console.WriteLine(""M1""); } } " + trivial2uple + tupleattributes_cs; var comp1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "comp1", parseOptions: TestOptions.Regular.WithTuplesFeature()); var comp2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "comp2", parseOptions: TestOptions.Regular.WithTuplesFeature()); var source = @" class C3 { public static void Main() { int x = 0; x.M1((1, 1)); } } "; var comp = CreateCompilationWithMscorlib40(source, references: new[] { comp1.ToMetadataReference(), comp2.ToMetadataReference() }, parseOptions: TestOptions.Regular.WithTuplesFeature(), options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,14): error CS8356: Predefined type 'System.ValueTuple`2' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // x.M1((1, 1)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, "(1, 1)").WithArguments("System.ValueTuple`2", "comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 14) ); } [Fact, WorkItem(12952, "https://github.com/dotnet/roslyn/issues/12952")] public void DropTupleNamesFromArray() { var source = @" public class C { public (int c, int d)[] M() { return new[] { (d: 1, 2) }; } public (int c, int d)[] M2() { return new[] { (d: 1, 2), (d: 1, e: 3), TupleDE() }; } public (int d, int e) TupleDE() { return (1, 3); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(int d, int)'. // return new[] { (d: 1, 2), (d: 1, e: 3), TupleDE() }; Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 3").WithArguments("e", "(int d, int)").WithLocation(10, 42) ); } [Fact, WorkItem(10951, "https://github.com/dotnet/roslyn/issues/10951")] public void ObsoleteValueTuple() { var lib_cs = @" namespace System { [Obsolete] public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) { } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { } } [Obsolete] public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { } public TRest Rest; } } public class D { public static void M2((int, int) x) { } public static void M3((int, string) x) { } } "; var source = @" public class C { void M() { (int, int) x1 = (1, 2); var x2 = (1, 2); var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); var x10 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); D.M2((1, 2)); D.M3((1, null)); System.Console.Write($""{x1} {x2} {x9} {x10}""); } } "; var compLib = CreateCompilationWithMscorlib40(lib_cs, options: TestOptions.ReleaseDll); var comp = CreateCompilationWithMscorlib40(source, references: new[] { compLib.ToMetadataReference() }); comp.VerifyDiagnostics( // (6,9): warning CS0612: '(T1, T2)' is obsolete // (int, int) x1 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(T1, T2)").WithLocation(6, 9), // (6,9): warning CS0612: '(int, int)' is obsolete // (int, int) x1 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(int, int)").WithArguments("(int, int)").WithLocation(6, 9), // (6,25): warning CS0612: '(T1, T2)' is obsolete // (int, int) x1 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2)").WithArguments("(T1, T2)").WithLocation(6, 25), // (7,18): warning CS0612: '(T1, T2)' is obsolete // var x2 = (1, 2); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2)").WithArguments("(T1, T2)").WithLocation(7, 18), // (8,18): warning CS0612: '(T1, T2)' is obsolete // var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("(T1, T2)").WithLocation(8, 18), // (8,18): warning CS0612: 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' is obsolete // var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>").WithLocation(8, 18), // (9,19): warning CS0612: 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>' is obsolete // var x10 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>").WithLocation(9, 19), // (10,14): warning CS0612: '(T1, T2)' is obsolete // D.M2((1, 2)); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2)").WithArguments("(T1, T2)").WithLocation(10, 14), // (11,14): warning CS0612: '(T1, T2)' is obsolete // D.M3((1, null)); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, null)").WithArguments("(T1, T2)").WithLocation(11, 14) ); } [Fact, WorkItem(10951, "https://github.com/dotnet/roslyn/issues/10951")] public void ObsoleteValueTuple2() { var source = @" public class C { void M() { var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); System.Console.Write(x9); } } namespace System { [Obsolete] public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Rest = rest; } public TRest Rest; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): warning CS0612: '(T1, T2)' is obsolete // var x9 = (1, 2, 3, 4, 5, 6, 7, 8, 9); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "(1, 2, 3, 4, 5, 6, 7, 8, 9)").WithArguments("(T1, T2)").WithLocation(6, 18) ); } [Fact, WorkItem(13365, "https://github.com/dotnet/roslyn/issues/13365")] public void Bug13365() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } namespace System.Runtime.CompilerServices { public class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } public class C { public (int, int) GetCoordinates() => (0, 0); public (int x, int y) GetCoordinates2() => (0, 0); public void PrintCoordinates() { (int x1, int y1) = GetCoordinates(); (int x2, int y2) = GetCoordinates2(); } } "; var comp = CreateCompilation(source, assemblyName: "comp"); comp.VerifyEmitDiagnostics( // (25,28): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x1, int y1) = GetCoordinates(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates()").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(25, 28), // (25,28): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x1, int y1) = GetCoordinates(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates()").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(25, 28), // (26,28): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x2, int y2) = GetCoordinates2(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates2()").WithArguments("Item1", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(26, 28), // (26,28): error CS8128: Member 'Item2' was not found on type '(T1, T2)' from assembly 'comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // (int x2, int y2) = GetCoordinates2(); Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "GetCoordinates2()").WithArguments("Item2", "(T1, T2)", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(26, 28) ); } [Fact, WorkItem(13494, "https://github.com/dotnet/roslyn/issues/13494")] public static void Bug13494() { var source1 = @" class Program { static void Main(string[] args) { var(a, ) } } "; var text = SourceText.From(source1); var startTree = SyntaxFactory.ParseSyntaxTree(text); var finalString = startTree.GetCompilationUnitRoot().ToFullString(); var pos = source1.IndexOf("var(a, )") + 8; var newText = text.WithChanges(new TextChange(new TextSpan(pos, 0), " ")); // add space before closing-paren var newTree = startTree.WithChangedText(newText); var finalText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(newText.ToString(), finalText); // no crash } [Fact] [WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")] public void BadOverloadWithTupleLiteralWithNaturalType() { var source = @" class Program { static void M(int i) { } static void M(string i) { } static void Main() { M((1, 2)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from '(int, int)' to 'int' // M((1, 2)); Diagnostic(ErrorCode.ERR_BadArgType, "(1, 2)").WithArguments("1", "(int, int)", "int").WithLocation(9, 11)); } [Fact] [WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")] public void BadOverloadWithTupleLiteralWithNoNaturalType() { var source = @" class Program { static void M(int i) { } static void M(string i) { } static void Main() { M((1, null)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from '(int, <null>)' to 'int' // M((1, null)); Diagnostic(ErrorCode.ERR_BadArgType, "(1, null)").WithArguments("1", "(int, <null>)", "int").WithLocation(9, 11)); } [Fact] [WorkItem(261049, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/261049")] public void DevDiv261049RegressionTest() { var source = @" class Program { static void Main(string[] args) { var (a,b) = Get(out int x, out int y); Console.WriteLine($""({a.first}, {a.second})""); } static (string first,string second) Get(out int a, out int b) { a = 0; b = 1; return (""a"",""b""); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1061: 'string' does not contain a definition for 'first' and no extension method 'first' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // Console.WriteLine($"({a.first}, {a.second})"); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "first").WithArguments("string", "first").WithLocation(7, 37), // (7,48): error CS1061: 'string' does not contain a definition for 'second' and no extension method 'second' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // Console.WriteLine($"({a.first}, {a.second})"); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "second").WithArguments("string", "second").WithLocation(7, 48), // (7,13): error CS0103: The name 'Console' does not exist in the current context // Console.WriteLine($"({a.first}, {a.second})"); Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console").WithLocation(7, 13) ); } [Fact, WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")] public static void TupleCoVariance() { var source = @" public interface I<out T> { System.ValueTuple<bool, T> M(); } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T>.M()'. 'T' is covariant. // System.ValueTuple<bool, T> M(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "System.ValueTuple<bool, T>").WithArguments("I<T>.M()", "T", "covariant", "invariantly").WithLocation(4, 5) ); } [Fact, WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")] public static void TupleCoVariance2() { var source = @" public interface I<out T> { (bool, T)[] M(); } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T>.M()'. 'T' is covariant. // (bool, T)[] M(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "(bool, T)[]").WithArguments("I<T>.M()", "T", "covariant", "invariantly").WithLocation(4, 5) ); } [Fact, WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")] public static void TupleContraVariance() { var source = @" public interface I<in T> { void M((bool, T)[] x); } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (4,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T>.M((bool, T)[])'. 'T' is contravariant. // void M((bool, T)[] x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "(bool, T)[]").WithArguments("I<T>.M((bool, T)[])", "T", "contravariant", "invariantly").WithLocation(4, 12) ); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(13767, "https://github.com/dotnet/roslyn/issues/13767")] public void TupleInConstant() { var source = @" class C<T> { } class C { static void Main() { const C<(int, int)> c = null; System.Console.Write(c); } }"; var comp = CreateCompilation(source, assemblyName: "comp", options: TestOptions.DebugExe); // emit without pdb using (ModuleMetadata block = ModuleMetadata.CreateFromStream(comp.EmitToStream())) { var reader = block.MetadataReader; AssertEx.SetEqual(new[] { "mscorlib 4.0", "System.ValueTuple 4.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ValueTuple`2, System, AssemblyReference:System.ValueTuple", reader.DumpTypeReferences()); } // emit with pdb comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "", validator: (assembly) => { var reader = assembly.GetMetadataReader(); AssertEx.SetEqual(new[] { "mscorlib 4.0", "System.ValueTuple 4.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ValueTuple`2, System, AssemblyReference:System.ValueTuple", reader.DumpTypeReferences()); }); // no assertion in MetadataWriter } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(13767, "https://github.com/dotnet/roslyn/issues/13767")] public void ConstantTypeFromReferencedAssembly() { var libSource = @" public class ReferencedType { } "; var source = @" class C { static void Main() { const ReferencedType c = null; System.Console.Write(c); } }"; var libComp = CreateCompilationWithMscorlib40(libSource, assemblyName: "lib"); libComp.VerifyDiagnostics(); var comp = CreateCompilationWithMscorlib40(source, assemblyName: "comp", references: new[] { libComp.EmitToImageReference() }, options: TestOptions.DebugExe); // emit without pdb using (ModuleMetadata block = ModuleMetadata.CreateFromStream(comp.EmitToStream())) { var reader = block.MetadataReader; AssertEx.SetEqual(new[] { "mscorlib 4.0", "lib 0.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ReferencedType, , AssemblyReference:lib", reader.DumpTypeReferences()); } // emit with pdb comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "", validator: (assembly) => { var reader = assembly.GetMetadataReader(); AssertEx.SetEqual(new[] { "mscorlib 4.0", "lib 0.0" }, reader.DumpAssemblyReferences()); Assert.Contains("ReferencedType, , AssemblyReference:lib", reader.DumpTypeReferences()); }); // no assertion in MetadataWriter } [Fact] [WorkItem(13661, "https://github.com/dotnet/roslyn/issues/13661")] public void LongTupleWithPartialNames_Bug13661() { var source = @" using System; class C { static void Main() { var o = (A: 1, 2, C: 3, D: 4, E: 5, F: 6, G: 7, 8, I: 9); Console.Write(o.I); } } "; CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"9", sourceSymbolValidator: (module) => { var sourceModule = (SourceModuleSymbol)module; var compilation = sourceModule.DeclaringCompilation; var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var x = nodes.OfType<VariableDeclaratorSyntax>().First(); var xSymbol = ((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; AssertEx.SetEqual(xSymbol.GetMembers().OfType<IFieldSymbol>().Select(f => f.Name), "A", "C", "D", "E", "F", "G", "I", "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Rest"); }); // no assert hit } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct0() { var source = @" class C { static void Main() { (int a, int b) x; x.Item1 = 1; x.b = 2; // by the language rules tuple x is definitely assigned // since all its elements are definitely assigned System.Console.WriteLine(x); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,9): error CS0165: Use of unassigned local variable 'x' // x.Item1 = 1; Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(7, 9), // (23,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(23, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct1() { var source = @" class C { static void Main() { var x = (1,2,3,4,5,6,7,8,9); System.Console.WriteLine(x); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } public class ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override string ToString() { return base.ToString(); } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (6,13): error CS8182: Predefined type 'ValueTuple`8' must be a struct. // var x = (1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "x = (1,2,3,4,5,6,7,8,9)").WithArguments("ValueTuple`8").WithLocation(6, 13), // (6,13): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // var x = (1,2,3,4,5,6,7,8,9); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "x = (1,2,3,4,5,6,7,8,9)").WithArguments("ValueTuple`2").WithLocation(6, 13), // (19,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, @"public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(19, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct2() { var source = @" class C { static void Main() { } static void Test2((int a, int b) arg) { } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (20,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(20, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct2i() { var source = @" class C { static void Main() { } static void Test2((int a, int b) arg) { } } namespace System { public interface ValueTuple<T1, T2> { } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1), // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct3() { var source = @" class C { static void Main() { } static void Test1() { (int, int)[] x = null; System.Console.WriteLine(x); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (10,22): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // (int, int)[] x = null; Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "x = null").WithArguments("ValueTuple`2").WithLocation(10, 22), // (23,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(23, 9) ); } [Fact] [WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")] public void ValueTupleNotStruct4() { var source = @" class C { static void Main() { } static (int a, int b) Test2() { return (1, 1); } } namespace System { public class ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } " + tupleattributes_cs; var comp = CreateCompilation(source, assemblyName: "ValueTupleNotStruct", options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (8,35): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // static (int a, int b) Test2() { return (1, 1); } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "{ return (1, 1); }").WithArguments("ValueTuple`2").WithLocation(8, 35), // (8,44): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // static (int a, int b) Test2() { return (1, 1); } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "(1, 1)").WithArguments("ValueTuple`2").WithLocation(8, 44), // (18,9): error CS8182: Predefined type 'ValueTuple`2' must be a struct. // public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, "public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; }").WithArguments("ValueTuple`2").WithLocation(18, 9) ); } [Fact] public void ValueTupleBaseError_NoSystemRuntime() { var source = @"interface I { ((int, int), (int, int)) F(); }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef }); comp.VerifyEmitDiagnostics( // (3,6): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // ((int, int), (int, int)) F(); Diagnostic(ErrorCode.ERR_NoTypeDef, "(int, int)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(3, 6), // (3,18): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // ((int, int), (int, int)) F(); Diagnostic(ErrorCode.ERR_NoTypeDef, "(int, int)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(3, 18), // (3,5): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // ((int, int), (int, int)) F(); Diagnostic(ErrorCode.ERR_NoTypeDef, "((int, int), (int, int))").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(3, 5)); } [WorkItem(16879, "https://github.com/dotnet/roslyn/issues/16879")] [Fact] public void ValueTupleBaseError_MissingReference() { var source0 = @"public class A { } public class B { }"; var comp0 = CreateCompilationWithMscorlib40(source0, assemblyName: "92872377-08d1-4723-8906-a43b03e56ed3"); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"public class C<T> { } namespace System { public class ValueTuple<T1, T2> : A { public ValueTuple(T1 _1, T2 _2) { } } public class ValueTuple<T1, T2, T3> : C<B> { public ValueTuple(T1 _1, T2 _2, T3 _3) { } } }"; var comp1 = CreateCompilationWithMscorlib40(source1, references: new[] { ref0 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"interface I { (int, (int, int), (int, int)) F(); }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ref1 }); comp.VerifyEmitDiagnostics( // error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("B", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("B", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("A", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1), // error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("A", "92872377-08d1-4723-8906-a43b03e56ed3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); } [Fact] public void ValueTupleBase_AssemblyUnification() { var source0v1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { }"; var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile); var comp0v1 = CreateCompilationWithMscorlib40(source0v1, assemblyName: "A", options: signedDllOptions); comp0v1.VerifyDiagnostics(); var ref0v1 = comp0v1.EmitToImageReference(); var source0v2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A { }"; var comp0v2 = CreateCompilationWithMscorlib40(source0v2, assemblyName: "A", options: signedDllOptions); comp0v2.VerifyDiagnostics(); var ref0v2 = comp0v2.EmitToImageReference(); var source1 = @"public class B : A { }"; var comp1 = CreateCompilationWithMscorlib40(source1, references: new[] { ref0v1 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source2 = @"namespace System { public class ValueTuple<T1, T2> : B { public ValueTuple(T1 _1, T2 _2) { } } }"; var comp2 = CreateCompilationWithMscorlib40(source2, references: new[] { ref1, ref0v1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); var source = @"interface I { (int, int) F(); }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ref0v2, ref1, ref2 }); comp.VerifyEmitDiagnostics( // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1), // error CS8182: Predefined type 'ValueTuple`2' must be a struct. Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct).WithArguments("ValueTuple`2").WithLocation(1, 1)); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(13472, "https://github.com/dotnet/roslyn/issues/13472")] public void InvalidCastRef() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 _1, T2 _2) { Item1 = _1; Item2 = _2; } } } namespace System.Runtime.CompilerServices { public class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] names) { } } } class C { static void Main() { (int A, int B) x = (1, 2); ref (int, int) y = ref x; } }"; var comp = CompileAndVerify(source); comp.EmitAndVerify(); } [Fact] [WorkItem(14166, "https://github.com/dotnet/roslyn/issues/14166")] public void RefTuple001() { var source = @" class Program { static (int Alice, int Bob)[] arr = new(int Alice, int Bob)[1]; static void Main(string[] args) { RefParam(ref arr[0]); System.Console.WriteLine(arr[0]); RefReturn().Item2 = 42; System.Console.WriteLine(arr[0]); ref (int, int) x = ref arr[0]; x.Item1 = 33; System.Console.WriteLine(arr[0]); } static void RefParam(ref (int, int) p) { p.Item1 = 42; } static ref (int, int) RefReturn() { return ref arr[0]; } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(42, 0) (42, 42) (33, 42)"); comp.VerifyIL("Program.Main", @" { // Code size 110 (0x6e) .maxstack 2 IL_0000: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0005: ldc.i4.0 IL_0006: ldelema ""System.ValueTuple<int, int>"" IL_000b: call ""void Program.RefParam(ref System.ValueTuple<int, int>)"" IL_0010: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0015: ldc.i4.0 IL_0016: ldelem ""System.ValueTuple<int, int>"" IL_001b: box ""System.ValueTuple<int, int>"" IL_0020: call ""void System.Console.WriteLine(object)"" IL_0025: call ""ref System.ValueTuple<int, int> Program.RefReturn()"" IL_002a: ldc.i4.s 42 IL_002c: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0031: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0036: ldc.i4.0 IL_0037: ldelem ""System.ValueTuple<int, int>"" IL_003c: box ""System.ValueTuple<int, int>"" IL_0041: call ""void System.Console.WriteLine(object)"" IL_0046: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_004b: ldc.i4.0 IL_004c: ldelema ""System.ValueTuple<int, int>"" IL_0051: ldc.i4.s 33 IL_0053: stfld ""int System.ValueTuple<int, int>.Item1"" IL_0058: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_005d: ldc.i4.0 IL_005e: ldelem ""System.ValueTuple<int, int>"" IL_0063: box ""System.ValueTuple<int, int>"" IL_0068: call ""void System.Console.WriteLine(object)"" IL_006d: ret } "); comp.VerifyIL("Program.RefReturn", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: ldsfld ""System.ValueTuple<int, int>[] Program.arr"" IL_0005: ldc.i4.0 IL_0006: ldelema ""System.ValueTuple<int, int>"" IL_000b: ret } "); } [Fact] public static void OperatorOverloadingWithDifferentTupleNames() { var source = @" public class B1 { public static bool operator >=((B1 a, B1 b) x1, B1 x2) { return true; } public static bool operator <=((B1 notA, B1 notB) x1, B1 x2) { return true; } } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics(); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [ConditionalFact(typeof(DesktopOnly))] public void RefTupleDynamicDecode001() { string lib = @" namespace ClassLibrary1 { public class C1 { public virtual ref (int, dynamic) Goo(int arg) { return ref new (int, dynamic)[]{(1, arg)}[0]; } } } "; var libComp = CreateCompilationWithMscorlib45AndCSharp(lib, references: s_valueTupleRefs, options: TestOptions.DebugDll); libComp.VerifyDiagnostics(); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo(42); System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, object) Goo(int arg) { return ref base.Goo(arg); } } } "; var comp = CompileAndVerify(source, expectedOutput: "42qq", references: new[] { libComp.ToMetadataReference() }, options: TestOptions.DebugExe, verify: Verification.Fails); var m = (MethodSymbol)(((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo(System.Int32 arg)", m.ToTestDisplayString()); var b = m.OverriddenMethod; Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo(System.Int32 arg)", b.ToTestDisplayString()); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [Fact] public void RefTupleDynamicDecode002() { string lib = @" namespace ClassLibrary1 { public class C1 { public virtual ref (int, dynamic) Goo(int arg) { return ref new (int, dynamic)[]{(1, arg)}[0]; } } } "; var libComp = CreateCompilationWithMscorlib45AndCSharp(lib, options: TestOptions.DebugDll, references: s_valueTupleRefs); libComp.VerifyDiagnostics(); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo(42); System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, object) Goo(int arg) { return ref base.Goo(arg); } } } "; var libCompRef = AssemblyMetadata.CreateFromImage(libComp.EmitToArray()).GetReference(); var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "42qq", references: s_valueTupleRefs.Concat(new[] { libCompRef }).ToArray(), options: TestOptions.DebugExe, verify: Verification.Fails); var m = (IMethodSymbol)(comp.Compilation.GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo(System.Int32 arg)", m.ToTestDisplayString()); var b = m.OverriddenMethod; Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo(System.Int32 arg)", b.ToTestDisplayString()); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_01() { var source = @" partial class C { public static void Main() { Test((X1:1, Y1:2)); var t1 = (X1:3, Y1:4); Test(t1); Test((5, 6)); var t2 = (7, 8); Test(t2); } public static void Test(AA val) { } } class AA { public static implicit operator AA ((int X1, int Y1) x) { System.Console.WriteLine(x); return new AA(); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2) (3, 4) (5, 6) (7, 8)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_02() { var source = @" partial class C { public static void Main() { Test((X1:1, Y1:2)); var t1 = (X1:3, Y1:4); Test(t1); Test((5, 6)); var t2 = (7, 8); Test(t2); } public static void Test(AA? val) { } } struct AA { public static implicit operator AA ((int X1, int Y1) x) { System.Console.WriteLine(x); return new AA(); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2) (3, 4) (5, 6) (7, 8)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_03() { var source = @" partial class C { public static void Main() { (int X1, int Y1)? t1 = (X1:3, Y1:4); Test(t1); (int, int)? t2 = (7, 8); Test(t2); System.Console.WriteLine(""--""); t1 = null; Test(t1); t2 = null; Test(t2); System.Console.WriteLine(""--""); } public static void Test(AA? val) { } } struct AA { public static implicit operator AA ((int X1, int Y1) x) { System.Console.WriteLine(x); return new AA(); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(3, 4) (7, 8) -- --"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_04() { var source = @" partial class C { public static void Main() { Test(new AA()); } public static void Test((int X1, int Y1) val) { System.Console.WriteLine(val); } } class AA { public static implicit operator (int, int) (AA x) { return (1, 2); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_05() { var source = @" partial class C { public static void Main() { Test(new AA()); } public static void Test((int X1, int Y1) val) { System.Console.WriteLine(val); } } class AA { public static implicit operator (int X1, int Y1) (AA x) { return (1, 2); } }"; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2)"); } [Fact] [WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")] public void UserDefinedConversionsAndNameMismatch_06() { var source = @" partial class C { public static void Main() { BB<(int X1, int Y1)>? t1 = new BB<(int X1, int Y1)>(); Test(t1); BB<(int, int)>? t2 = new BB<(int, int)>(); Test(t2); System.Console.WriteLine(""--""); t1 = null; Test(t1); t2 = null; Test(t2); System.Console.WriteLine(""--""); } public static void Test(AA? val) { } } struct AA { public static implicit operator AA (BB<(int X1, int Y1)> x) { System.Console.WriteLine(""implicit operator AA""); return new AA(); } } struct BB<T> { } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"implicit operator AA implicit operator AA -- --"); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [Fact] public void RefTupleDynamicDecode003() { string lib = @" // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System.Core { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) // .{...-.Q .ver 4:0:1:0 } // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit ClassLibrary1.C1 extends [mscorlib]System.Object { .method public hidebysig newslot virtual instance valuetype [System.ValueTuple]System.ValueTuple`2<int32,object>& Goo(int32 arg) cil managed { .param [0] // the dynamic flags array is too short - decoder expects a flag matching ""ref"", but it is missing here. .custom instance void [System.Core]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 00 01 00 00 ) // Code size 37 (0x25) .maxstack 5 .locals init (valuetype [System.ValueTuple]System.ValueTuple`2<int32,object>& V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr valuetype [System.ValueTuple]System.ValueTuple`2<int32,object> IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: ldarg.1 IL_000b: box [mscorlib]System.Int32 IL_0010: newobj instance void valuetype [System.ValueTuple]System.ValueTuple`2<int32,object>::.ctor(!0, !1) IL_0015: stelem valuetype [System.ValueTuple]System.ValueTuple`2<int32,object> IL_001a: ldc.i4.0 IL_001b: ldelema valuetype [System.ValueTuple]System.ValueTuple`2<int32,object> IL_0020: stloc.0 IL_0021: br.s IL_0023 IL_0023: ldloc.0 IL_0024: ret } // end of method C1::Goo .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 } // end of class ClassLibrary1.C1 "; var libCompRef = CompileIL(lib); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo(42); System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, dynamic) Goo(int arg) { return ref base.Goo(arg); } } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: (new[] { libCompRef }).Concat(s_valueTupleRefs).ToArray(), options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "42qq", verify: Verification.Fails); var m = (MethodSymbol)(comp.GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, dynamic) ConsoleApplication5.C2.Goo(System.Int32 arg)", m.ToTestDisplayString()); var b = m.OverriddenMethod; // not (int, dynamic), // since dynamic flags were not aligned, we have ignored the flags Assert.Equal("ref (System.Int32, System.Object) ClassLibrary1.C1.Goo(System.Int32 arg)", b.ToTestDisplayString()); } [WorkItem(14708, "https://github.com/dotnet/roslyn/issues/14708")] [WorkItem(14709, "https://github.com/dotnet/roslyn/issues/14709")] [ConditionalFact(typeof(DesktopOnly))] public void RefTupleDynamicDecode004() { string lib = @" namespace ClassLibrary1 { public class C1 { public virtual ref (int, dynamic) Goo => ref new (int, dynamic)[]{(1, 42)}[0]; } } "; var libComp = CreateCompilationWithMscorlib45AndCSharp(lib, references: s_valueTupleRefs, options: TestOptions.DebugDll); libComp.VerifyDiagnostics(); var source = @" namespace ConsoleApplication5 { class Program { static void Main(string[] args) { ref var x = ref new C2().Goo; System.Console.Write(x.Item2); x.Item2 = ""qq""; System.Console.WriteLine(x.Item2); } } class C2: ClassLibrary1.C1 { public override ref (int, object) Goo => ref base.Goo; } } "; var libCompRef = AssemblyMetadata.CreateFromImage(libComp.EmitToArray()).GetReference(); var comp = CompileAndVerify(source, expectedOutput: "42qq", references: new[] { libCompRef }, options: TestOptions.DebugExe, verify: Verification.Passes); var m = (PropertySymbol)(((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("ConsoleApplication5.C2").GetMembers("Goo").First()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo { get; }", m.ToTestDisplayString()); Assert.Equal("ref (System.Int32, System.Object) ConsoleApplication5.C2.Goo.get", m.GetMethod.ToTestDisplayString()); var b = m.OverriddenProperty; Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo { get; }", b.ToTestDisplayString()); Assert.Equal("ref (System.Int32, dynamic) ClassLibrary1.C1.Goo.get", b.GetMethod.ToTestDisplayString()); } [Fact] [WorkItem(14267, "https://github.com/dotnet/roslyn/issues/14267")] public void NoSystemRuntimeFacade() { var source = @" class C { static void M() { var o = (1, 2); } } "; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef }); Assert.Equal(TypeKind.Class, compilation.GetWellKnownType(WellKnownType.System_ValueTuple_T2).TypeKind); compilation.VerifyDiagnostics( // (6,17): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // var o = (1, 2); Diagnostic(ErrorCode.ERR_NoTypeDef, "(1, 2)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(6, 17) ); } [Fact] [WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")] public void Iterator_01() { var source = @" using System; using System.Collections.Generic; public class C { static void Main(string[] args) { foreach (var x in entries()) { Console.WriteLine(x); } } static public IEnumerable<(int, int)> entries() { yield return (1, 2); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"(1, 2)"); } [Fact] [WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")] public void Iterator_02() { var source = @" using System; using System.Collections.Generic; public class C { public IEnumerable<(int, int)> entries() { yield return (1, 2); } } "; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef }); compilation.VerifyEmitDiagnostics( // (7,24): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // public IEnumerable<(int, int)> entries() Diagnostic(ErrorCode.ERR_NoTypeDef, "(int, int)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(7, 24), // (9,22): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. // yield return (1, 2); Diagnostic(ErrorCode.ERR_NoTypeDef, "(1, 2)").WithArguments("System.ValueType", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").WithLocation(9, 22) ); } [Fact] [WorkItem(14649, "https://github.com/dotnet/roslyn/issues/14649")] public void ParseLongLambda() { string filler = string.Join("\r\n", Enumerable.Range(1, 1000).Select(i => $"int y{i};")); string parameters = string.Join(", ", Enumerable.Range(1, 2000).Select(i => $"int x{i}")); string text = @" class C { " + filler + @" public void M() { N((" + parameters + @") => 1); } } "; // This is designed to trigger a shift of the array of lexed tokens (see AddLexedTokenSlot) while // parsing lambda parameters var tree = SyntaxFactory.ParseSyntaxTree(text, CSharpParseOptions.Default); // no assertion } [Fact] public void UnusedTuple() { string source = @" public class C { void M(int x) { // Warnings int[] array = new int[] { 42 }; unsafe { fixed (int* p = &array[0]) { (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type (string, int*) t2 = (null, p); // implicit tuple literal conversion on a converted tuple literal with a pointer type (string, (int*, int*)) t3 = (null, (p, p)); } } (int, int) t4 = default((int, int)); (int, int) t5 = (1, 2); (string, string) t6 = (null, null); (string, string) t7 = (""hello"", ""world""); (S, (S, S)) t8 = (new S(), (new S(), new S())); (int, int) t9 = ((C, int))(new C(), 2); // implicit tuple conversion with a user conversion on an element (int, int) t10 = (new C(), 2); // implicit tuple literal conversion with a user conversion on an element (int, int) t11 = ((int, int))(((C, int))(new C(), 2)); // explicit tuple conversion with a user conversion on an element (C, C) t12 = (new C(), new C()); (C, (C, C)) t13 = (new C(), (new C(), new C())); (S, (S, S)) t14 = (new S(), (new S() { /* object initializer */ }, new S())); // No warnings (C, int) tuple = (new C(), 2); (int, int) t20 = ((C, int))tuple; (int, int) t21 = tuple; (int, int) t22 = ((int, int))tuple; C c1 = (1, 2); (int, int) intTuple = (1, 2); C c2 = intTuple; int i1 = 1; int i2 = i1; } public static implicit operator int(C c) { return 0; } public static implicit operator C((int, int) t) { return new C(); } } public struct S { } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, references: s_valueTupleRefs, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (13,18): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(13, 18), // (13,24): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(13, 24), // (13,36): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(13, 36), // (13,39): error CS0306: The type 'int*' may not be used as a type argument // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(13, 39), // (14,26): error CS0306: The type 'int*' may not be used as a type argument // (string, int*) t2 = (null, p); // implicit tuple literal conversion on a converted tuple literal with a pointer type Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(14, 26), // (15,27): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(15, 27), // (15,33): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(15, 33), // (15,53): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(15, 53), // (15,56): error CS0306: The type 'int*' may not be used as a type argument // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p").WithArguments("int*").WithLocation(15, 56), // (13,30): warning CS0219: The variable 't1' is assigned but its value is never used // (int*, int*) t1 = (p, p); // converted tuple literal with a pointer type Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t1").WithArguments("t1").WithLocation(13, 30), // (14,32): warning CS0219: The variable 't2' is assigned but its value is never used // (string, int*) t2 = (null, p); // implicit tuple literal conversion on a converted tuple literal with a pointer type Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2").WithLocation(14, 32), // (15,40): warning CS0219: The variable 't3' is assigned but its value is never used // (string, (int*, int*)) t3 = (null, (p, p)); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t3").WithArguments("t3").WithLocation(15, 40), // (19,20): warning CS0219: The variable 't4' is assigned but its value is never used // (int, int) t4 = default((int, int)); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t4").WithArguments("t4").WithLocation(19, 20), // (20,20): warning CS0219: The variable 't5' is assigned but its value is never used // (int, int) t5 = (1, 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t5").WithArguments("t5").WithLocation(20, 20), // (22,26): warning CS0219: The variable 't6' is assigned but its value is never used // (string, string) t6 = (null, null); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t6").WithArguments("t6").WithLocation(22, 26), // (23,26): warning CS0219: The variable 't7' is assigned but its value is never used // (string, string) t7 = ("hello", "world"); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t7").WithArguments("t7").WithLocation(23, 26), // (24,21): warning CS0219: The variable 't8' is assigned but its value is never used // (S, (S, S)) t8 = (new S(), (new S(), new S())); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t8").WithArguments("t8").WithLocation(24, 21), // (26,20): warning CS0219: The variable 't9' is assigned but its value is never used // (int, int) t9 = ((C, int))(new C(), 2); // implicit tuple conversion with a user conversion on an element Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t9").WithArguments("t9").WithLocation(26, 20), // (27,20): warning CS0219: The variable 't10' is assigned but its value is never used // (int, int) t10 = (new C(), 2); // implicit tuple literal conversion with a user conversion on an element Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t10").WithArguments("t10").WithLocation(27, 20), // (28,20): warning CS0219: The variable 't11' is assigned but its value is never used // (int, int) t11 = ((int, int))(((C, int))(new C(), 2)); // explicit tuple conversion with a user conversion on an element Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t11").WithArguments("t11").WithLocation(28, 20), // (30,16): warning CS0219: The variable 't12' is assigned but its value is never used // (C, C) t12 = (new C(), new C()); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t12").WithArguments("t12").WithLocation(30, 16), // (31,21): warning CS0219: The variable 't13' is assigned but its value is never used // (C, (C, C)) t13 = (new C(), (new C(), new C())); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t13").WithArguments("t13").WithLocation(31, 21), // (32,21): warning CS0219: The variable 't14' is assigned but its value is never used // (S, (S, S)) t14 = (new S(), (new S() { /* object initializer */ }, new S())); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t14").WithArguments("t14").WithLocation(32, 21) ); } [Fact] [WorkItem(14881, "https://github.com/dotnet/roslyn/issues/14881")] [WorkItem(15476, "https://github.com/dotnet/roslyn/issues/15476")] public void TupleElementVsLocal() { var source = @" using System; static class Program { static void Main() { (int elem1, int elem2) tuple; int elem2; tuple = (5, 6); tuple.elem2 = 23; elem2 = 10; Console.WriteLine(tuple.elem2); Console.WriteLine(elem2); } } "; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "elem2").ToArray(); Assert.Equal(4, nodes.Length); Assert.Equal("tuple.elem2 = 23", nodes[0].Parent.Parent.ToString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetSymbolInfo(nodes[0]).Symbol.ToTestDisplayString()); Assert.Equal("elem2 = 10", nodes[1].Parent.ToString()); Assert.Equal("System.Int32 elem2", model.GetSymbolInfo(nodes[1]).Symbol.ToTestDisplayString()); Assert.Equal("(tuple.elem2)", nodes[2].Parent.Parent.Parent.ToString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetSymbolInfo(nodes[2]).Symbol.ToTestDisplayString()); Assert.Equal("(elem2)", nodes[3].Parent.Parent.ToString()); Assert.Equal("System.Int32 elem2", model.GetSymbolInfo(nodes[3]).Symbol.ToTestDisplayString()); var type = tree.GetRoot().DescendantNodes().OfType<TupleTypeSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(type); Assert.Equal("(System.Int32 elem1, System.Int32 elem2)", symbolInfo.Symbol.ToTestDisplayString()); var typeInfo = model.GetTypeInfo(type); Assert.Equal("(System.Int32 elem1, System.Int32 elem2)", typeInfo.Type.ToTestDisplayString()); Assert.Equal(symbolInfo.Symbol, typeInfo.Type); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem1", model.GetDeclaredSymbol(type.Elements.First()).ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetDeclaredSymbol(type.Elements.Last()).ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem1", model.GetDeclaredSymbol((SyntaxNode)type.Elements.First()).ToTestDisplayString()); Assert.Equal("System.Int32 (System.Int32 elem1, System.Int32 elem2).elem2", model.GetDeclaredSymbol((SyntaxNode)type.Elements.Last()).ToTestDisplayString()); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ImplicitIEnumerableImplementationWithDifferentTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { public IEnumerator<(int a, int b)> GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived : Base, IEnumerable<(int notA, int notB)> { public new IEnumerator<(int notA, int notB)> GetEnumerator() { return new DerivedEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<(int notA, int notB)> { bool done = false; public (int notA, int notB) Current { get { return (2, 2); } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { foreach (var x in new Derived()) { Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.Int32 notA, System.Int32 notB)>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var xSymbol = model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single()); Assert.Equal("(System.Int32 notA, System.Int32 notB)", xSymbol.Type.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitIEnumerableImplementationWithDifferentTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { IEnumerator<(int a, int b)> IEnumerable<(int a, int b)>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived : Base, IEnumerable<(int notA, int notB)> { IEnumerator<(int notA, int notB)> IEnumerable<(int notA, int notB)>.GetEnumerator() { return new DerivedEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<(int notA, int notB)> { bool done = false; public (int notA, int notB) Current { get { return (2, 2); } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { foreach (var x in new Derived()) { System.Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.Int32 notA, System.Int32 notB)>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var xSymbol = model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single()); Assert.Equal("(System.Int32 notA, System.Int32 notB)", xSymbol.Type.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericImplicitIEnumerableImplementationUsedWithDifferentTypesAndTupleNames() { var source = @" using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int, int)> { public IEnumerator<(int, int)> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class Derived<T> : Base, IEnumerable<T> { public T state; public new IEnumerator<T> GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { return null; } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { return null; } } } } class C { static void Main() { var collection = new Derived<(string a, string b)>() { state = (""hello"", ""world"") }; foreach (var x in collection) { System.Console.WriteLine(x.a); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32, System.Int32)>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<(System.String a, System.String b)>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32, System.Int32)>", "System.Collections.Generic.IEnumerable<(System.String a, System.String b)>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); CompileAndVerify(comp, expectedOutput: "hello"); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericExplicitIEnumerableImplementationUsedWithDifferentTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { IEnumerator<(int a, int b)> IEnumerable<(int a, int b)>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived<T> : Base, IEnumerable<T> { public T state; IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { var collection = new Derived<(int notA, int notB)>() { state = (42, 43) }; foreach (var x in collection) { System.Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived) as INamedTypeSymbol; Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<(System.Int32 notA, System.Int32 notB)>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.Int32 notA, System.Int32 notB)>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); Assert.Empty(derivedSymbol.GetSymbol().AsUnboundGenericType().AllInterfaces()); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericExplicitIEnumerableImplementationUsedWithoutTuples() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived<T> : Base, IEnumerable<T> { public T state; IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { var collection = new Derived<int>() { state = 42 }; foreach (var x in collection) { System.Console.WriteLine(x); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<System.Int32>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void GenericExplicitIEnumerableImplementationUsedWithDifferentTypesAndTupleNames() { var source = @" using System; using System.Collections; using System.Collections.Generic; class Base : IEnumerable<(int a, int b)> { IEnumerator<(int a, int b)> IEnumerable<(int a, int b)>.GetEnumerator() { throw new Exception(); } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } } class Derived<T> : Base, IEnumerable<T> { public T state; IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new DerivedEnumerator() { state = state }; } IEnumerator IEnumerable.GetEnumerator() { throw new Exception(); } public class DerivedEnumerator : IEnumerator<T> { public T state; bool done = false; public T Current { get { return state; } } public bool MoveNext() { if (done) { return false; } else { done = true; return true; } } public void Reset() { } public void Dispose() { } object IEnumerator.Current { get { throw new Exception(); } } } } class C { static void Main() { var collection = new Derived<(string notA, string notB)>() { state = (""hello"", ""world"") }; foreach (var x in collection) { System.Console.WriteLine(x.notA); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (35,27): error CS1640: foreach statement cannot operate on variables of type 'Derived<(string notA, string notB)>' because it implements multiple instantiations of 'IEnumerable<T>'; try casting to a specific interface instantiation // foreach (var x in collection) Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "collection").WithArguments("Derived<(string notA, string notB)>", "System.Collections.Generic.IEnumerable<T>").WithLocation(35, 27) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var derived = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ElementAt(1); var derivedSymbol = model.GetDeclaredSymbol(derived); Assert.Equal("Derived<T>", derivedSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<T>", "System.Collections.IEnumerable" }, derivedSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); var collection = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(3); var collectionSymbol = (model.GetDeclaredSymbol(collection) as ILocalSymbol)?.Type; Assert.Equal("Derived<(System.String notA, System.String notB)>", collectionSymbol.ToTestDisplayString()); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable<(System.Int32 a, System.Int32 b)>", "System.Collections.Generic.IEnumerable<(System.String notA, System.String notB)>", "System.Collections.IEnumerable" }, collectionSymbol.AllInterfaces.Select(i => i.ToTestDisplayString())); } [Fact] [WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")] public void TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion() { var source = @" interface I1<T> {} class Base<U> where U : I1<(int a, int b)> {} class Derived : Base<I1<(int notA, int notB)>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")] public void TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion2() { var source = @" interface I1<T> {} interface I2<T> : I1<T> {} class Base<U> where U : I1<(int a, int b)> {} class Derived : Base<I2<(int notA, int notB)>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void CanReImplementInterfaceWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } // explicit implementation } class Derived : Base, I<(int notA, int notB)> { public (int notA, int notB) M() { return (3, 4); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void CannotOverrideWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public virtual (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { public override (int notA, int notB) M() { return (3, 4); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,42): error CS8139: 'Derived.M()': cannot change tuple element names when overriding inherited member 'Base.M()' // public override (int notA, int notB) M() { return (3, 4); } Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M").WithArguments("Derived.M()", "Base.M()").WithLocation(12, 42) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void CanShadowWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { public new (int notA, int notB) M() { return (3, 4); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_01() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } // explicit implementation } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(10, 24) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_02() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } // explicit implementation public (int notA, int notB) M() { return (1, 2); } } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(11, 24) ); } [Fact] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_03() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS0535: 'Base' does not implement interface member 'I<(int a, int b)>.M()' // class Base : I<(int a, int b)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int a, int b)>").WithArguments("Base", "I<(int a, int b)>.M()").WithLocation(6, 14), // (9,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(9, 24) ); } [Fact] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_04() { var source1 = @" public interface I<T> { T M(); } public class Base : I<(int a, int b)> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (6,21): error CS0535: 'Base' does not implement interface member 'I<(int a, int b)>.M()' // public class Base : I<(int a, int b)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int a, int b)>").WithArguments("Base", "I<(int a, int b)>.M()").WithLocation(6, 21) ); var source2 = @" class Derived1 : Base, I<(int notA, int notB)> { } class Derived2 : Base, I<(int a, int b)> { } "; var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }); comp2.VerifyDiagnostics( // (2,24): error CS0535: 'Derived1' does not implement interface member 'I<(int notA, int notB)>.M()' // class Derived1 : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<(int notA, int notB)>").WithArguments("Derived1", "I<(int notA, int notB)>.M()").WithLocation(2, 24) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_05() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived1 : Base, I<(int notA, int notB)> { // error } class Derived2 : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int notA, int notB)>.M()' (including on the return type). // class Derived1 : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int notA, int notB)>").WithArguments("Base.M()", "I<(int notA, int notB)>.M()").WithLocation(10, 24) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ImplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { // error } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,23): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int notA, int notB)>.M()' (including on the return type). // class Derived : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int notA, int notB)>").WithArguments("Base.M()", "I<(int notA, int notB)>.M()").WithLocation(10, 23) ); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ImplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames2() { var source = @" interface I<T> { T M(); } class Base { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { // error } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,23): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int notA, int notB)>.M()' (including on the return type). // class Derived : Base, I<(int notA, int notB)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int notA, int notB)>").WithArguments("Base.M()", "I<(int notA, int notB)>.M()").WithLocation(10, 23) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ImplicitBaseImplementationNotConsideredImplementationForInterfaceWithNoNames() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { public (int a, int b) M() { return (1, 2); } } class Derived : Base, I<(int, int)> { // error } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,23): error CS8141: The tuple element names in the signature of method 'Base.M()' must match the tuple element names of interface method 'I<(int, int)>.M()' (including on the return type). // class Derived : Base, I<(int, int)> Diagnostic(ErrorCode.ERR_ImplBadTupleNames, "I<(int, int)>").WithArguments("Base.M()", "I<(int, int)>.M()").WithLocation(10, 23) ); } [Fact] [WorkItem(20528, "https://github.com/dotnet/roslyn/issues/20528")] public void ImplicitBaseImplementationWithNoNamesConsideredImplementationForInterface() { var source = @" interface I<T> { T M(); } class Base : I<(int, int)> { public (int, int) M() { return (1, 2); } } class Derived : Base, I<(int a, int b)> { // ok } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")] public void ReImplementationAndInference() { var source = @" interface I<T> { T M(); } class Base : I<(int a, int b)> { (int a, int b) I<(int a, int b)>.M() { return (1, 2); } } class Derived : Base, I<(int notA, int notB)> { public (int notA, int notB) M() { return (3, 4); } } class C { static void Main() { Base b = new Derived(); var x = Test(b); // tuple names from Base, implementation from Derived System.Console.Write(x.a); } static T Test<T>(I<T> t) { return t.M(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "3"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); Assert.Equal("x", x.Identifier.ToString()); var xSymbol = ((ILocalSymbol)model.GetDeclaredSymbol(x)).Type; Assert.Equal("(System.Int32 a, System.Int32 b)", xSymbol.ToTestDisplayString()); } [Fact] [WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")] public void TupleTypeWithTooFewElements() { var source = @" class C { void M(int x, () y, (int a) z) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,20): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 20), // (4,31): error CS8124: Tuple must contain at least two elements. // void M(int x, () y, (int a) z) { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 31) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var y = tree.GetRoot().DescendantNodes().OfType<TupleTypeSyntax>().ElementAt(0); Assert.Equal("()", y.ToString()); var yType = model.GetTypeInfo(y); Assert.Equal("(?, ?)", yType.Type.ToTestDisplayString()); var z = tree.GetRoot().DescendantNodes().OfType<TupleTypeSyntax>().ElementAt(1); Assert.Equal("(int a)", z.ToString()); var zType = model.GetTypeInfo(z); Assert.Equal("(System.Int32 a, ?)", zType.Type.ToTestDisplayString()); } [Fact] [WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")] public void TupleExpressionWithTooFewElements() { var source = @" class C { object x = (Alice: 1); } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8124: Tuple must contain at least two elements. // object x = (Alice: 1); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(4, 25) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(Alice: 1)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int32 Alice, ?)", tupleType.Type.ToTestDisplayString()); } [Fact] [WorkItem(16159, "https://github.com/dotnet/roslyn/issues/16159")] public void ExtensionMethodOnConvertedTuple001() { var source = @" using System; using System.Linq; using System.Collections.Generic; static class C { static IEnumerable<(T, U)> Zip<T, U>(this(IEnumerable<T> xs, IEnumerable<U> ys) source) => source.xs.Zip(source.ys, (x, y) => (x, y)); static void Main() { foreach (var t in Zip((new int[] { 1, 2 }, new byte[] { 3, 4 }))) { System.Console.WriteLine(t); } foreach (var t in (new int[] { 1, 2 }, new byte[] { 3, 4 }).Zip()) { System.Console.WriteLine(t); } var notALiteral = (new int[] { 1, 2 }, new byte[] { 3, 4 }); foreach (var (x, y) in notALiteral.Zip()) { System.Console.WriteLine((x, y)); } } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (1, 3) (2, 4) (1, 3) (2, 4) (1, 3) (2, 4) "); } [Fact] public void ExtensionMethodOnConvertedTuple002() { var source = @" using System; using System.Collections; static class C { static string M(this(object x, (ValueType, IStructuralComparable) y) self) => self.ToString(); static string M1(this (dynamic x, System.Exception y) self) => self.ToString(); static void Main() { System.Console.WriteLine((""qq"", (Alice: 1, (2, 3))).M()); (dynamic Alice, NullReferenceException Bob) arg = (123, null); System.Console.WriteLine(arg.M1()); } } "; var comp = CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @" (qq, (1, (2, 3))) (123, ) "); } [Fact] public void ExtensionMethodOnConvertedTuple002Err() { var source = @" using System; using System.Collections; static class C { static string M(this(object x, (ValueType, IStructuralComparable) y) self) => self.ToString(); static string GetAwaiter(this (object x, Func<int> y) self) => self.ToString(); static void Main() { System.Console.WriteLine((""qq"", (Alice: 1, (null, 3))).M()); System.Console.WriteLine((""qq"", ()=>1 ).GetAwaiter()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,64): error CS0117: '(string, (int, (<null>, int)))' does not contain a definition for 'M' // System.Console.WriteLine(("qq", (Alice: 1, (null, 3))).M()); Diagnostic(ErrorCode.ERR_NoSuchMember, "M").WithArguments("(string, (int, (<null>, int)))", "M").WithLocation(13, 64), // (15,49): error CS0117: '(string, lambda expression)' does not contain a definition for 'GetAwaiter' // System.Console.WriteLine(("qq", ()=>1 ).GetAwaiter()); Diagnostic(ErrorCode.ERR_NoSuchMember, "GetAwaiter").WithArguments("(string, lambda expression)", "GetAwaiter").WithLocation(15, 49) ); } [Fact] public void ExtensionMethodOnConvertedTuple003() { var source = @" static class C { static string M(this (int x, long y) self) => self.ToString(); static string M1(this (int x, long? y) self) => self.ToString(); static void Main() { // implicit constant conversion System.Console.WriteLine((1, 2).M()); // identity conversion (this one is OK) System.Console.WriteLine((1, 2L).M()); // implicit nullable conversion System.Console.WriteLine((First: 1, Second: 2L).M1()); // null literal conversion System.Console.WriteLine((1, null).M1()); // implicit numeric conversion var notAliteral = (A: 1, B: 2); System.Console.WriteLine(notAliteral.M()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,34): error CS1929: '(int, int)' does not contain a definition for 'M' and the best extension method overload 'C.M((int x, long y))' requires a receiver of type '(int x, long y)' // System.Console.WriteLine((1, 2).M()); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(1, 2)").WithArguments("(int, int)", "M", "C.M((int x, long y))", "(int x, long y)").WithLocation(10, 34), // (16,34): error CS1929: '(int, long)' does not contain a definition for 'M1' and the best extension method overload 'C.M1((int x, long? y))' requires a receiver of type '(int x, long? y)' // System.Console.WriteLine((First: 1, Second: 2L).M1()); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "(First: 1, Second: 2L)").WithArguments("(int, long)", "M1", "C.M1((int x, long? y))", "(int x, long? y)").WithLocation(16, 34), // (19,44): error CS0117: '(int, <null>)' does not contain a definition for 'M1' // System.Console.WriteLine((1, null).M1()); Diagnostic(ErrorCode.ERR_NoSuchMember, "M1").WithArguments("(int, <null>)", "M1"), // (23,34): error CS1929: '(int A, int B)' does not contain a definition for 'M' and the best extension method overload 'C.M((int x, long y))' requires a receiver of type '(int x, long y)' // System.Console.WriteLine(notAliteral.M()); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "notAliteral").WithArguments("(int A, int B)", "M", "C.M((int x, long y))", "(int x, long y)").WithLocation(23, 34) ); } [ConditionalFact(typeof(DesktopOnly))] public void Serialization() { var source = @" using System; class C { public static void Main() { VerifySerialization(new ValueTuple()); VerifySerialization(ValueTuple.Create(1)); VerifySerialization((1, 2, 3, 4, 5, 6, 7, 8)); Console.WriteLine(""DONE""); } public static void VerifySerialization<T>(T tuple) { var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); var writer = new System.IO.StringWriter(); serializer.Serialize(writer, tuple); string xml = writer.ToString(); object output = serializer.Deserialize(new System.IO.StringReader(xml)); if (!tuple.Equals(output)) { throw new Exception(""Deserialization output didn't match""); } } }"; var comp = CreateCompilationWithMscorlib40(new[] { source, tuplelib_cs }, references: new[] { SystemXmlRef }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "DONE"); } [Fact] public void GetWellKnownTypeWithAmbiguities() { var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]"; var corlib_cs = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class ValueType { } public struct Void { } public class Attribute { } } namespace System.Reflection { public class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(String version) { } } }"; string valuetuple_cs = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2); } }"; var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib"); corlibWithoutVT.VerifyDiagnostics(); var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference(); var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib"); corlibWithVT.VerifyDiagnostics(); var corlibWithVTRef = corlibWithVT.EmitToImageReference(); var libWithVT = CreateEmptyCompilation(valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll); libWithVT.VerifyDiagnostics(); var libWithVTRef = libWithVT.EmitToImageReference(); var comp = CSharpCompilation.Create("test", references: new[] { libWithVTRef, corlibWithVTRef }); var found = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.False(found.IsErrorType()); Assert.Equal("corlib", found.ContainingAssembly.Name); var comp2 = comp.WithOptions(comp.Options.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); var tuple2 = comp2.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.False(tuple2.IsErrorType()); Assert.Equal(libWithVTRef.Display, tuple2.ContainingAssembly.MetadataName.ToString()); var comp3 = CSharpCompilation.Create("test", references: new[] { corlibWithVTRef, libWithVTRef }) // order reversed .WithOptions(comp.Options.WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)); var tuple3 = comp3.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.False(tuple3.IsErrorType()); Assert.Equal(libWithVTRef.Display, tuple3.ContainingAssembly.MetadataName.ToString()); var libWithVTRef2 = CreateEmptyCompilation(valuetuple_cs, references: new[] { corlibWithoutVTRef }).EmitToImageReference(); var comp4 = CreateEmptyCompilation("", references: new[] { libWithVTRef, libWithVTRef2, corlibWithoutVTRef }); var tuple4 = comp4.GetWellKnownType(WellKnownType.System_ValueTuple_T2); Assert.True(tuple4.IsErrorType()); } [Fact] [WorkItem(17962, "https://github.com/dotnet/roslyn/issues/17962")] public void TupleWithAsOperator() { var source = @" class C { void M<T>() { var x = (0, null) as (int, T)?; System.Console.WriteLine(x == null); } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,17): error CS8304: The first operand of an 'as' operator may not be a tuple literal without a natural type. // var x = (0, null) as (int, T)?; Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(0, null) as (int, T)?").WithLocation(6, 17) ); } [Fact] public void CheckedConstantConversions() { var source = @"#pragma warning disable 219 class C { static void Main() { unchecked { var u = ((byte, byte))(0, -1); var (a, b) = ((byte, byte))(0, -2); } checked { var c = ((byte, byte))(0, -1); var (a, b) = ((byte, byte))(0, -2); } } }"; var comp = CreateCompilationWithMscorlib40( source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (13,39): error CS0221: Constant value '-1' cannot be converted to a 'byte' (use 'unchecked' syntax to override) // var c = ((byte, byte))(0, -1); Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "-1").WithArguments("-1", "byte").WithLocation(13, 39), // (14,44): error CS0221: Constant value '-2' cannot be converted to a 'byte' (use 'unchecked' syntax to override) // var (a, b) = ((byte, byte))(0, -2); Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "-2").WithArguments("-2", "byte").WithLocation(14, 44)); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInAsOperator() { var source = @" using System; class P { static void Main() { var x1 = (1, 1) as (int, int a)?; var x2 = (1, 1) as (int, int)?; var x3 = (1, new object()) as (int, dynamic)?; Console.Write($""{x1} {x2} {x3}""); } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(1, 1) (1, 1) (1, System.Object)"); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInAsOperator2() { var source = @" class P { static void M() { var x = (a: 1, b: 1) as (int c, int d)?; var y = (1, 1) as (int, long)?; } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,17): warning CS0458: The result of the expression is always 'null' of type '(int, long)?' // var y = (1, 1) as (int, long)?; Diagnostic(ErrorCode.WRN_AlwaysNull, "(1, 1) as (int, long)?").WithArguments("(int, long)?").WithLocation(7, 17) ); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInIsOperator() { var source = @" class P { static void M() { var x1 = (1, 1) is (int, int a)?; } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,29): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "int").WithArguments("type pattern", "9.0").WithLocation(6, 29), // (6,41): error CS1525: Invalid expression term ';' // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 41), // (6,41): error CS1003: Syntax error, ':' expected // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(6, 41), // (6,41): error CS1525: Invalid expression term ';' // var x1 = (1, 1) is (int, int a)?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 41) ); } [Fact] [WorkItem(17963, "https://github.com/dotnet/roslyn/issues/17963")] public void NullableTupleInIsOperator2() { var source = @" class P { static void M() { var x1 = (1, 1) is System.Nullable<(int, int a)>; } }"; var comp = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,18): warning CS0183: The given expression is always of the provided ('(int, int a)?') type // var x1 = (1, 1) is System.Nullable<(int, int a)>; Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "(1, 1) is System.Nullable<(int, int a)>").WithArguments("(int, int a)?").WithLocation(6, 18) ); } [Fact] [WorkItem(18459, "https://github.com/dotnet/roslyn/issues/18459")] public void CheckedConversions() { var source = @"using System; class C { static (long, byte) Default((int, int) t) { return ((long, byte))t; } static (long, byte) Unchecked((int, int) t) { unchecked { return ((long, byte))t; } } static (long, byte) Checked((int, int) t) { checked { return ((long, byte))t; } } static void Main() { var d = Default((-1, -1)); Console.Write(d); var u = Unchecked((-1, -1)); Console.Write(u); try { var c = Checked((-1, -1)); Console.Write(c); } catch (OverflowException) { Console.Write(""overflow""); } } }"; var comp = CreateCompilationWithMscorlib40( source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"(-1, 255)(-1, 255)overflow"); verifier.VerifyIL("C.Default", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_000f: conv.u1 IL_0010: newobj ""System.ValueTuple<long, byte>..ctor(long, byte)"" IL_0015: ret }"); verifier.VerifyIL("C.Unchecked", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_000f: conv.u1 IL_0010: newobj ""System.ValueTuple<long, byte>..ctor(long, byte)"" IL_0015: ret }"); verifier.VerifyIL("C.Checked", @"{ // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_000f: conv.ovf.u1 IL_0010: newobj ""System.ValueTuple<long, byte>..ctor(long, byte)"" IL_0015: ret }"); } [Fact] [WorkItem(19434, "https://github.com/dotnet/roslyn/issues/19434")] public void ExplicitTupleLiteralConversionWithNullable01() { var source = @" class C { static void Main() { int x = 1; var y = ((byte, byte)?)(x, x); System.Console.WriteLine(y.Value); } } "; var comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"(1, 1)"); comp.VerifyIL("C.Main()", @" { // Code size 38 (0x26) .maxstack 3 .locals init (int V_0, //x System.ValueTuple<byte, byte>? V_1) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldloc.0 IL_0006: conv.u1 IL_0007: ldloc.0 IL_0008: conv.u1 IL_0009: newobj ""System.ValueTuple<byte, byte>..ctor(byte, byte)"" IL_000e: call ""System.ValueTuple<byte, byte>?..ctor(System.ValueTuple<byte, byte>)"" IL_0013: ldloca.s V_1 IL_0015: call ""System.ValueTuple<byte, byte> System.ValueTuple<byte, byte>?.Value.get"" IL_001a: box ""System.ValueTuple<byte, byte>"" IL_001f: call ""void System.Console.WriteLine(object)"" IL_0024: nop IL_0025: ret } "); comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"(1, 1)"); comp.VerifyIL("C.Main()", @" { // Code size 36 (0x24) .maxstack 3 .locals init (int V_0, //x System.ValueTuple<byte, byte>? V_1) //y IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldloc.0 IL_0005: conv.u1 IL_0006: ldloc.0 IL_0007: conv.u1 IL_0008: newobj ""System.ValueTuple<byte, byte>..ctor(byte, byte)"" IL_000d: call ""System.ValueTuple<byte, byte>?..ctor(System.ValueTuple<byte, byte>)"" IL_0012: ldloca.s V_1 IL_0014: call ""System.ValueTuple<byte, byte> System.ValueTuple<byte, byte>?.Value.get"" IL_0019: box ""System.ValueTuple<byte, byte>"" IL_001e: call ""void System.Console.WriteLine(object)"" IL_0023: ret } "); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion_01() { var source = @" class C { void M() { int? e = 5; (int, string) y = (e, null); // the only conversion we find is an explicit conversion System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,28): error CS0029: Cannot implicitly convert type 'int?' to 'int' // (int, string) y = (e, null); Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("int?", "int").WithLocation(7, 28) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion(comp); } private static void VerifySemanticModelTypelessTupleWithNoImplicitConversion(CSharpCompilation comp) { var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(tuple).Kind); var first = tuple.Arguments[0].Expression; Assert.Equal("System.Int32?", model.GetTypeInfo(first).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(first).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(first).Kind); var second = tuple.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(second).Type); Assert.Equal("System.String", model.GetTypeInfo(second).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(second).Kind); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion_02() { var source = @" class C { (int, string) M() { int? e = 5; return (e, null); // the only conversion we find is an explicit conversion } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,17): error CS0029: Cannot implicitly convert type 'int?' to 'int' // return (e, null); // the only conversion we find is an explicit conversion Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("int?", "int").WithLocation(7, 17) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion(comp); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion2_01() { var source = @" class C { void M() { int? e = 5; (int, string)? y = (e, null); // the only conversion we find is an explicit conversion System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,28): error CS8135: Tuple with 2 elements cannot be converted to type '(int, string)?'. // (int, string)? y = (e, null); // the only conversion we find is an explicit conversion Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(e, null)").WithArguments("2", "(int, string)?").WithLocation(7, 28) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion2(comp); } private static void VerifySemanticModelTypelessTupleWithNoImplicitConversion2(CSharpCompilation comp) { var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Equal("(System.Int32, System.String)?", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(tuple).Kind); var first = tuple.Arguments[0].Expression; Assert.Equal("System.Int32?", model.GetTypeInfo(first).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(first).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitNullable, model.GetConversion(first).Kind); var second = tuple.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(second).Type); Assert.Equal("System.String", model.GetTypeInfo(second).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(second).Kind); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion2_02() { var source = @" class C { (int, string)? M() { int? e = 5; return (e, null); // the only conversion we find is an explicit conversion } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,16): error CS8135: Tuple with 2 elements cannot be converted to type '(int, string)?'. // return (e, null); // the only conversion we find is an explicit conversion Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(e, null)").WithArguments("2", "(int, string)?").WithLocation(7, 16) ); VerifySemanticModelTypelessTupleWithNoImplicitConversion2(comp); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypelessTupleWithNoImplicitConversion3() { var source = @" class C { void M() { int? e = 5; (int, string, int) y = (e, null); // no conversion found System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,32): error CS8135: Tuple with 2 elements cannot be converted to type '(int, string, int)'. // (int, string, int) y = (e, null); // no conversion found Diagnostic(ErrorCode.ERR_ConversionNotTupleCompatible, "(e, null)").WithArguments("2", "(int, string, int)").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Null(model.GetTypeInfo(tuple).Type); Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, model.GetConversion(tuple).Kind); var first = tuple.Arguments[0].Expression; Assert.Equal("System.Int32?", model.GetTypeInfo(first).Type.ToTestDisplayString()); Assert.Equal("System.Int32?", model.GetTypeInfo(first).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(first).Kind); var second = tuple.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(second).Type); Assert.Null(model.GetTypeInfo(second).ConvertedType); Assert.Equal(ConversionKind.Identity, model.GetConversion(second).Kind); } [Fact] [WorkItem(20208, "https://github.com/dotnet/roslyn/issues/20208")] public void UnusedTupleAssignedToVar() { var source = @" class C { public static void Main () { (int, int) t1 = (1, 2); var t2 = (3, 4); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (6,20): warning CS0219: The variable 't1' is assigned but its value is never used // (int, int) t1 = (1, 2); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t1").WithArguments("t1").WithLocation(6, 20), // (7,13): warning CS0219: The variable 't2' is assigned but its value is never used // var t2 = (3, 4); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2").WithLocation(7, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(tuple).Kind); } [Fact] [WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")] public void TypedTupleWithNoConversion() { var source = @" class C { void M() { int? e = 5; (int, string, int) y = (e, """"); // no conversion found System.Console.Write(y); } } "; var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1), references: new[] { MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef }); comp.VerifyDiagnostics( // (7,32): error CS0029: Cannot implicitly convert type '(int? e, string)' to '(int, string, int)' // (int, string, int) y = (e, ""); // no conversion found Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(e, """")").WithArguments("(int? e, string)", "(int, string, int)").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32? e, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(tuple).ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, model.GetConversion(tuple).Kind); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_01() { var source = @"using System; public class C { public static void Main() { A<A<int>> a = null; M1(a); // ok, selects M1<T>(A<A<T>> a) var b = default(ValueTuple<ValueTuple<int, int>, int>); M2(b); // ok, should select M2<T>(ValueTuple<ValueTuple<T, int>, int> a) } public static void M1<T>(A<T> a) { Console.Write(1); } public static void M1<T>(A<A<T>> a) { Console.Write(2); } public static void M2<T>(ValueTuple<T, int> a) { Console.Write(3); } public static void M2<T>(ValueTuple<ValueTuple<T, int>, int> a) { Console.Write(4); } } public class A<T> {}"; var comp = CompileAndVerify(source, expectedOutput: "24"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_01b() { var source = @"using System; public class C { public static void Main() { var b = ((0, 0), 0); M2(b); // ok, should select M2<T>(((T, int), int) a) } public static void M2<T>((T, int) a) { Console.Write(3); } public static void M2<T>(((T, int), int) a) { Console.Write(4); } }"; var comp = CompileAndVerify(source, expectedOutput: "4"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a1() { var source = @"using System; public class C { public static void Main() { // var b = (1, 2, 3, 4, 5, 6, 7, 8); var b = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple<int>(8)); M1(b); M2(b); // ok, should select M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a2() { var source = @"using System; public class C { public static void Main() { // var b = (1, 2, 3, 4, 5, 6, 7, 8); var b = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple<int>(8)); M1(ref b); M2(ref b); // ok, should select M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ref ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ref ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ref ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a3() { var source = @"using System; public class C { public static void Main() { I<ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>> b = null; M1(b); M2(b); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(3); } } public interface I<in T>{} "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a4() { var source = @"using System; public class C { public static void Main() { I<ValueTuple<int, int, int, int, int, int, int, ValueTuple<int>>> b = null; M1(b); M2(b); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(I<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> a) where TRest : struct { Console.Write(3); } } public interface I<out T>{} "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a5() { var source = @"using System; public class C { public static void Main() { M1((1, 2, 3, 4, 5, 6, 7, 8)); M2((1, 2, 3, 4, 5, 6, 7, 8)); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a6() { var source = @"using System; public class C { public static void Main() { M2((()=>1, ()=>2, ()=>3, ()=>4, ()=>5, ()=>6, ()=>7, ()=>8)); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, ValueTuple<Func<T8>>> a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"2"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02a7() { var source = @"using System; public class C { public static void Main() { M1((()=>1, ()=>2, ()=>3, ()=>4, ()=>5, ()=>6, ()=>7, ()=>8)); } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, TRest> a) where TRest : struct { Console.Write(1); } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'C.M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<Func<T1>, Func<T2>, Func<T3>, Func<T4>, Func<T5>, Func<T6>, Func<T7>, TRest>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1((()=>1, ()=>2, ()=>3, ()=>4, ()=>5, ()=>6, ()=>7, ()=>8)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("C.M1<T1, T2, T3, T4, T5, T6, T7, TRest>(System.ValueTuple<System.Func<T1>, System.Func<T2>, System.Func<T3>, System.Func<T4>, System.Func<T5>, System.Func<T6>, System.Func<T7>, TRest>)").WithLocation(6, 9) ); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] [WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")] public void MoreGenericTieBreaker_02b() { var source = @"using System; public class C { public static void Main() { var b = (1, 2, 3, 4, 5, 6, 7, 8); M1(b); M2(b); // ok, should select M2<T1, T2, T3, T4, T5, T6, T7, T8>((T1, T2, T3, T4, T5, T6, T7, T8) a) } public static void M1<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(1); } public static void M2<T1, T2, T3, T4, T5, T6, T7, T8>((T1, T2, T3, T4, T5, T6, T7, T8) a) { Console.Write(2); } public static void M2<T1, T2, T3, T4, T5, T6, T7, TRest>(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> a) where TRest : struct { Console.Write(3); } } "; var comp = CompileAndVerify(source, expectedOutput: @"12"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_03() { var source = @"using System; public class C { public static void Main() { var b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, (10, 10), (11, 11)); M1(b); // ok, should select M2<T, U, V>(((T, int), int, int, int, int, int, int, int, int, (U, int), V) a) } public static void M1<T, U, V>(((T, int), int, int, int, int, int, int, int, int, (U, int), V) a) { Console.Write(3); } public static void M1<T, U, V>((T, int, int, int, int, int, int, int, int, U, (V, int)) a) { Console.Write(4); } }"; var comp = CompileAndVerify(source, expectedOutput: "3"); } [Fact] [WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")] public void MoreGenericTieBreaker_04() { var source = @"using System; public class C { public static void Main() { var b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, (20, 20)); M1(b); // error: ambiguous } public static void M1<T, U>((T, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, (U, int)) a) { Console.Write(3); } public static void M1<T, U>(((T, int), int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, U) a) { Console.Write(4); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1<T, U>((T, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, (U, int)))' and 'C.M1<T, U>(((T, int), int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, U))' // M1(b); // error: ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1<T, U>((T, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, (U, int)))", "C.M1<T, U>(((T, int), int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, U))").WithLocation(7, 9) ); } [Fact] [WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")] void TypelessTupleInArrayInitializer() { string source = @" class C { static (int A, object B)[] mTupleArray = { (A: 0, B: null) }; private static void Main() { System.Console.Write(mTupleArray[0].B == null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes(); var node = nodes.OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(A: 0, B: null)", node.ToString()); var tupleSymbol = model.GetTypeInfo(node); Assert.Null(tupleSymbol.Type); Assert.Equal("(System.Int32 A, System.Object B)", tupleSymbol.ConvertedType.ToTestDisplayString()); } [Fact] public void SettingMembersOfReadOnlyTuple() { var text = @" public class C { public static void Main() { var tuple = (1, 2); tuple.Item1 = 3; } } namespace System { public readonly struct ValueTuple<T1, T2> { public readonly T1 Item1; public readonly T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // tuple.Item1 = 3; Diagnostic(ErrorCode.ERR_AssgReadonly, "tuple.Item1").WithLocation(8, 9)); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithTuple_AddingNames() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<(int, int)> impl) { var case3 = impl.Do(((int x, int y) a) => a.x * a.y); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do(((int x, int y) a) => a.x * a.y)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithTuple_DifferentNames() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<(int a, int b)> impl) { var case3 = impl.Do(((int x, int y) a) => a.x * a.y); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do(((int x, int y) a) => a.x * a.y)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithTuple_DroppingNames() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<(int a, int b)> impl) { var case3 = impl.Do(((int, int) a) => a.Item1 * a.Item2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do(((int, int) a) => a.Item1 * a.Item2)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Fact, WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")] public void InferenceWithDynamic() { string source = @" using System; public interface IDo<T> { IResult<TReturn> Do<TReturn>(Func<T, TReturn> fn); } public interface IResult<TReturn> { } public class Class1 { public void Test1(IDo<object> impl) { var case3 = impl.Do((dynamic a) => 1); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var doSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("impl.Do((dynamic a) => 1)", doSyntax.ToString()); var doSymbol = (IMethodSymbol)model.GetSymbolInfo(doSyntax).Symbol; Assert.Equal("IResult<System.Int32>", doSymbol.ReturnType.ToTestDisplayString()); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase_ValueTuple(bool useImageReference) { var lib_cs = @" public class C2<T1, T2> { } public class SelfReferencing : C2<SelfReferencing, (string A, int B)> { public SelfReferencing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: s_valueTupleRefs); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class Program { public static void M() { _ = new SelfReferencing(); } } "; var comp = CreateCompilationWithMscorlib40(source_cs, references: new[] { libRef }); comp.VerifyEmitDiagnostics(); var executable_cs = @" public class C { public static void Main() { Program.M(); } }"; var executeComp = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase_ValueTupleInContainer(bool useImageReference, bool missingValueTuple) { var missingContainer_cs = @" public class MissingContainer<T> { } "; var missingContainer = CreateCompilationWithMscorlib40(missingContainer_cs, references: s_valueTupleRefs); missingContainer.VerifyDiagnostics(); var missingContainerRef = useImageReference ? missingContainer.EmitToImageReference() : missingContainer.ToMetadataReference(); var lib_cs = @" public class C2<T1, T2> { } public class SelfReferencing : C2<SelfReferencing, MissingContainer<(string A, int B)>> { public SelfReferencing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: new[] { missingContainerRef, SystemRuntimeFacadeRef, ValueTupleRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class Program { public static void M() { _ = new SelfReferencing(); } } "; // Compile without System.ValueTuple and/or MissingContainer var references = missingValueTuple ? new[] { libRef } : new[] { libRef, SystemRuntimeFacadeRef, ValueTupleRef }; var comp = CreateCompilationWithMscorlib40(source_cs, references: references); comp.VerifyEmitDiagnostics(); // Execute with all the references present var executable_cs = @" public class C { public static void Main() { Program.M(); } }"; var executeComp = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, SystemRuntimeFacadeRef, ValueTupleRef, missingContainerRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase_ValueTupleAndContainer(bool useImageReference) { var missingContainer_cs = @" public class MissingContainer<T> { } "; var missingContainer = CreateCompilationWithMscorlib40(missingContainer_cs, references: s_valueTupleRefs); missingContainer.VerifyDiagnostics(); var missingContainerRef = useImageReference ? missingContainer.EmitToImageReference() : missingContainer.ToMetadataReference(); var lib_cs = @" public class C : MissingContainer<(string A, int B)> { public C() { System.Console.Write(""ran""); } } "; var lib = CreateCompilationWithMscorlib40(lib_cs, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef, missingContainerRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class C2 { public static void M() { _ = new C(); } } "; var executable_cs = @" public class C3 { public static void Main() { C2.M(); } }"; var comp = CreateCompilationWithMscorlib40(source_cs, references: new[] { libRef }); // missing System.ValueTuple and MissingContainer comp.VerifyEmitDiagnostics(); var executeComp = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, missingContainerRef, SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); var comp2 = CreateCompilationWithMscorlib40(source_cs, references: new[] { libRef, missingContainerRef }); // missing System.ValueTuple comp2.VerifyEmitDiagnostics(); var executeComp2 = CreateCompilationWithMscorlib40(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, missingContainerRef, SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp2, expectedOutput: "ran"); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void MissingTypeArgumentInBase(bool useImageReference) { var missing_cs = @"public class Missing { }"; var missing = CreateCompilation(missing_cs); missing.VerifyDiagnostics(); var missingRef = useImageReference ? missing.EmitToImageReference() : missing.ToMetadataReference(); var lib_cs = @" public class C2<T1, T2> { } public class SelfReferencingClassWithMissing : C2<SelfReferencingClassWithMissing, Missing> { public SelfReferencingClassWithMissing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilation(lib_cs, references: new[] { missingRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class C { public static void M() { _ = new SelfReferencingClassWithMissing(); } } "; var comp = CreateCompilation(source_cs, references: new[] { libRef }); comp.VerifyEmitDiagnostics(); var executable_cs = @" public class C2 { public static void Main() { C.M(); } }"; var executeComp = CreateCompilation(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, missingRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Fact] [WorkItem(41699, "https://github.com/dotnet/roslyn/issues/41699")] public void MissingBaseType_TupleTypeArgumentWithNames() { var sourceA = @"public class A<T> { }"; var comp = CreateCompilation(sourceA, assemblyName: "A"); var refA = comp.EmitToImageReference(); var sourceB = @"public class B : A<(object X, B Y)> { }"; comp = CreateCompilation(sourceB, references: new[] { refA }); var refB = comp.EmitToImageReference(); var sourceC = @"class Program { static void Main() { var b = new B(); b.ToString(); } }"; comp = CreateCompilation(sourceC, references: new[] { refB }); comp.VerifyDiagnostics( // (6,11): error CS0012: The type 'A<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // b.ToString(); Diagnostic(ErrorCode.ERR_NoTypeDef, "ToString").WithArguments("A<>", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 11)); } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfTupleNamesWhenMissingValueTupleType() { var vtLib = CreateEmptyCompilation(trivial2uple + tupleattributes_cs, references: new[] { MscorlibRef }, assemblyName: "vt"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<(int alice, int bob)> { public void Add(int alice, int bob) => throw null; public IEnumerator<(int alice, int bob)> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs, references: new[] { MscorlibRef, vtLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client_cs = @" public class ClassB { public ClassB() { new ClassA { { 42, 10 } }; } }"; var comp = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to vt comp.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(comp, decodingSuccessful: false); var compWithMetadataReference = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.ToMetadataReference() }); // missing reference to vt compWithMetadataReference.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithMetadataReference, decodingSuccessful: true); var fakeVtLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "vt"); var compWithFakeVt = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeVtLib.EmitToImageReference() }); // reference to fake vt compWithFakeVt.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithFakeVt, decodingSuccessful: false); var client2_cs = @" public class ClassB { public ClassB() { var collectionA = new ClassA { { 42, 10 } }; foreach (var i in collectionA) { } } }"; var comp2 = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to vt comp2.VerifyDiagnostics( // (7,27): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("(, )", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27), // (7,27): error CS0012: The type '(, )' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("(, )", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(comp2, decodingSuccessful: false); var comp2WithFakeVt = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeVtLib.EmitToImageReference() }); // reference to fake vt comp2WithFakeVt.VerifyDiagnostics( // (7,27): error CS7069: Reference to type '(, )' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("(, )", "vt").WithLocation(7, 27), // (7,27): error CS7069: Reference to type '(, )' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("(, )", "vt").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(comp2WithFakeVt, decodingSuccessful: false); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation, bool decodingSuccessful) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; if (decodingSuccessful) { Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32 alice, System.Int32 bob)[missing]>", iEnumerable.ToTestDisplayString()); } else { Assert.Equal("System.Collections.Generic.IEnumerable<(System.Int32, System.Int32)[missing]>", iEnumerable.ToTestDisplayString()); } var tuple = iEnumerable.TypeArguments()[0]; if (decodingSuccessful) { Assert.Equal("(System.Int32 alice, System.Int32 bob)[missing]", tuple.ToTestDisplayString()); Assert.True(tuple.IsTupleType); Assert.True(tuple.IsErrorType()); } else { Assert.Equal("(System.Int32, System.Int32)[missing]", tuple.ToTestDisplayString()); Assert.True(tuple.IsTupleType); Assert.True(tuple.IsErrorType()); } } } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfLongTupleNamesWhenMissingValueTupleType() { var vtLib = CreateEmptyCompilation(tuplelib_cs + tupleattributes_cs, references: new[] { MscorlibRef }, assemblyName: "vt"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8)> { public void Add(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8) => throw null; public IEnumerator<(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8)> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs, references: new[] { MscorlibRef, vtLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client2_cs = @" public class ClassB { public ClassB() { var collectionA = new ClassA { { 1, 2, 3, 4, 5, 6, 7, 8 } }; foreach (var i in collectionA) { } } }"; var fakeVtLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "vt"); var comp = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to vt comp.VerifyDiagnostics( // (7,27): error CS0012: The type 'ValueTuple<,,,,,,,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27), // (7,27): error CS0012: The type 'ValueTuple<,,,,,,,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_NoTypeDef, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(comp); var compWithFakeVt = CreateEmptyCompilation(client2_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeVtLib.EmitToImageReference() }); // reference to fake vt compWithFakeVt.VerifyDiagnostics( // (7,27): error CS7069: Reference to type 'ValueTuple<,,,,,,,>' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt").WithLocation(7, 27), // (7,27): error CS7069: Reference to type 'ValueTuple<,,,,,,,>' claims it is defined in 'vt', but it could not be found // foreach (var i in collectionA) Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "collectionA").WithArguments("System.ValueTuple<,,,,,,,>", "vt").WithLocation(7, 27) ); verifyTupleTypeWithErrorUnderlyingType(compWithFakeVt); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; var tuple = iEnumerable.TypeArguments()[0]; AssertEx.Equal("System.ValueTuple<System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.ValueTuple<System.Int32>[missing]>[missing]", tuple.ToTestDisplayString()); Assert.True(tuple.IsErrorType()); Assert.True(tuple.IsTupleType); } } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfTupleNamesWhenMissingNonTupleType() { var containerLib = CreateEmptyCompilation("public class Container<T> { }", references: new[] { MscorlibRef }, assemblyName: "container"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<Container<(int alice, int bob)>> { public void Add(int alice, int bob) => throw null; public IEnumerator<Container<(int alice, int bob)>> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs + tuplelib_cs + tupleattributes_cs, references: new[] { MscorlibRef, containerLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client_cs = @" public class ClassB { public ClassB() { new ClassA { { 42, 10 } }; } }"; var comp = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to container comp.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(comp, decodingSuccessful: false); var compWithMetadataReference = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.ToMetadataReference() }); // missing reference to container compWithMetadataReference.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithMetadataReference, decodingSuccessful: true); var fakeContainerLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "container"); var compWithFakeContainer = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeContainerLib.EmitToImageReference() }); // reference to fake container compWithFakeContainer.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithFakeContainer, decodingSuccessful: false); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation, bool decodingSuccessful) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; if (decodingSuccessful) { AssertEx.Equal("System.Collections.Generic.IEnumerable<Container<(System.Int32 alice, System.Int32 bob)>[missing]>", iEnumerable.ToTestDisplayString()); } else { Assert.Equal("System.Collections.Generic.IEnumerable<Container<(System.Int32, System.Int32)>[missing]>", iEnumerable.ToTestDisplayString()); } var container = (NamedTypeSymbol)iEnumerable.TypeArguments()[0]; Assert.True(container.IsErrorType()); var tuple = (NamedTypeSymbol)container.TypeArguments()[0]; if (decodingSuccessful) { Assert.Equal("(System.Int32 alice, System.Int32 bob)", tuple.ToTestDisplayString()); } else { Assert.Equal("(System.Int32, System.Int32)", tuple.ToTestDisplayString()); } Assert.True(tuple.IsTupleType); Assert.False(tuple.TupleUnderlyingType.IsErrorType()); Assert.False(tuple.IsErrorType()); } } [Fact] [WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")] public void FailedDecodingOfTupleNamesWhenMissingContainerType() { var containerLib = CreateEmptyCompilation("public class Container<T> { public class Contained<U> { } }", references: new[] { MscorlibRef }, assemblyName: "container"); var lib_cs = @" using System.Collections; using System.Collections.Generic; public class ClassA : IEnumerable<Container<(int alice, int bob)>.Contained<(int charlie, int dylan)>> { public void Add(int alice, int bob) => throw null; public IEnumerator<Container<(int alice, int bob)>.Contained<(int charlie, int dylan)>> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }"; var lib = CreateEmptyCompilation(lib_cs + tuplelib_cs + tupleattributes_cs, references: new[] { MscorlibRef, containerLib.EmitToImageReference() }); lib.VerifyDiagnostics(); var client_cs = @" public class ClassB { public ClassB() { new ClassA { { 42, 10 } }; } }"; var comp = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference() }); // missing reference to container comp.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(comp, decodingSuccessful: false); var compWithMetadataReference = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.ToMetadataReference() }); // missing reference to container compWithMetadataReference.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithMetadataReference, decodingSuccessful: true); var fakeContainerLib = CreateEmptyCompilation("", references: new[] { MscorlibRef }, assemblyName: "container"); var compWithFakeContainer = CreateEmptyCompilation(client_cs, references: new[] { MscorlibRef, lib.EmitToImageReference(), fakeContainerLib.EmitToImageReference() }); // reference to fake container compWithFakeContainer.VerifyDiagnostics(); verifyTupleTypeWithErrorUnderlyingType(compWithFakeContainer, decodingSuccessful: false); void verifyTupleTypeWithErrorUnderlyingType(CSharpCompilation compilation, bool decodingSuccessful) { var classA = (NamedTypeSymbol)compilation.GetMember("ClassA"); var iEnumerable = (ConstructedNamedTypeSymbol)classA.Interfaces()[0]; AssertEx.Equal(decodingSuccessful ? "System.Collections.Generic.IEnumerable<Container<(System.Int32 alice, System.Int32 bob)>[missing].Contained<(System.Int32 charlie, System.Int32 dylan)>[missing]>" : "System.Collections.Generic.IEnumerable<Container<(System.Int32, System.Int32)>[missing].Contained<(System.Int32, System.Int32)>[missing]>", iEnumerable.ToTestDisplayString()); var contained = (NamedTypeSymbol)iEnumerable.TypeArguments()[0]; Assert.Equal(decodingSuccessful ? "Container<(System.Int32 alice, System.Int32 bob)>[missing].Contained<(System.Int32 charlie, System.Int32 dylan)>[missing]" : "Container<(System.Int32, System.Int32)>[missing].Contained<(System.Int32, System.Int32)>[missing]", contained.ToTestDisplayString()); Assert.True(contained.IsErrorType()); var tuple1 = (NamedTypeSymbol)contained.TypeArguments()[0]; Assert.Equal(decodingSuccessful ? "(System.Int32 charlie, System.Int32 dylan)" : "(System.Int32, System.Int32)", tuple1.ToTestDisplayString()); Assert.True(tuple1.IsTupleType); Assert.False(tuple1.TupleUnderlyingType.IsErrorType()); Assert.False(tuple1.IsErrorType()); var container = contained.ContainingType; Assert.Equal(decodingSuccessful ? "Container<(System.Int32 alice, System.Int32 bob)>[missing]" : "Container<(System.Int32, System.Int32)>[missing]", container.ToTestDisplayString()); Assert.True(container.IsErrorType()); var tuple2 = (NamedTypeSymbol)container.TypeArguments()[0]; Assert.Equal(decodingSuccessful ? "(System.Int32 alice, System.Int32 bob)" : "(System.Int32, System.Int32)", tuple2.ToTestDisplayString()); Assert.True(tuple2.IsTupleType); Assert.False(tuple2.TupleUnderlyingType.IsErrorType()); Assert.False(tuple2.IsErrorType()); } } [Fact] [WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")] [WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_01() { var source0 = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public static int F1 = 123; public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return F1.ToString(); } } } "; var source1 = @" class Program { public static void Main() { System.Console.WriteLine((1,2).ToString()); } } "; var source2 = @" class Program { public static void Main() { System.Console.WriteLine(System.ValueTuple<int, int>.F1); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "123"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "123"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "123"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "123"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "123"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Where(f => f.Name == "F1").Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")] [WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_02() { var source0 = @" namespace System { // struct with two values public struct ValueTuple<T1, T2> { public int F1; public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; F1 = 123; } public override string ToString() { return F1.ToString(); } } } "; var source1 = @" class Program { public static void Main() { System.Console.WriteLine((1,2).ToString()); } } "; var source2 = @" class Program { public static void Main() { System.Console.WriteLine((1,2).F1); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "123"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "123"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "123"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "123"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "123"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Where(f => f.Name == "F1").Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")] [WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_03() { var source0 = @" namespace System { public struct ValueTuple { public static readonly int F1 = 4; public static int CombineHashCodes(int h1, int h2) { return F1 + h1 + h2; } } } "; var source1 = @" class Program { static void Main() { System.Console.WriteLine(System.ValueTuple.CombineHashCodes(2, 3)); } } "; var source2 = @" class Program { public static void Main() { System.Console.WriteLine(System.ValueTuple.F1 + 2 + 3); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "9"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "9"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "9"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "9"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "9"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")] [WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void CustomFields_04() { var source0 = @" namespace System { public struct ValueTuple { public int F1; public int CombineHashCodes(int h1, int h2) { return F1 + h1 + h2; } } } "; var source1 = @" class Program { static void Main() { System.ValueTuple tuple = default; tuple.F1 = 4; System.Console.WriteLine(tuple.CombineHashCodes(2, 3)); } } "; var source2 = @" class Program { public static void Main() { System.ValueTuple tuple = default; tuple.F1 = 4; System.Console.WriteLine(tuple.F1 + 2 + 3); } } "; var comp1 = CreateCompilation(source0 + source1, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp1, expectedOutput: "9"); verifyField(comp1); var comp1Ref = new[] { comp1.ToMetadataReference() }; var comp1ImageRef = new[] { comp1.EmitToImageReference() }; var comp4 = CreateCompilation(source0 + source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe); CompileAndVerify(comp4, expectedOutput: "9"); var comp5 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp5, expectedOutput: "9"); verifyField(comp5); var comp6 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.DebugExe, references: comp1ImageRef); CompileAndVerify(comp6, expectedOutput: "9"); verifyField(comp6); var comp7 = CreateCompilation(source2, targetFramework: TargetFramework.Mscorlib46, options: TestOptions.DebugExe, references: comp1Ref); CompileAndVerify(comp7, expectedOutput: "9"); verifyField(comp7); static void verifyField(CSharpCompilation comp) { var field = comp.GetMember<FieldSymbol>("System.ValueTuple.F1"); Assert.NotNull(field.TupleUnderlyingField); Assert.Same(field, field.TupleUnderlyingField); var toEmit = field.ContainingType.GetFieldsToEmit().Single(); Assert.Same(toEmit, toEmit.TupleUnderlyingField); Assert.Same(field.TupleUnderlyingField, toEmit); } } [Fact] [WorkItem(43621, "https://github.com/dotnet/roslyn/issues/43621")] public void CustomFields_05() { var source0 = @" using System; namespace System { public class C { public unsafe static void Main() { var s = new ValueTuple(); int* p = s.MessageType; s.MessageType[0] = 12; p[1] = p[0]; Console.WriteLine(s.MessageType[1]); } } public unsafe struct ValueTuple { public fixed int MessageType[50]; } } "; var comp1 = CreateCompilation(source0, options: TestOptions.DebugExe.WithAllowUnsafe(true)); var verifier = CompileAndVerify(comp1, verify: Verification.Skipped); // unsafe code // There is a problem with caller, so execution currently yields the wrong result // Tracked by https://github.com/dotnet/roslyn/issues/43621 //var verifier = CompileAndVerify(comp1, expectedOutput: 12, verify: Verification.Skipped); // unsafe code if (ExecutionConditionUtil.IsCoreClr) { verifier.VerifyTypeIL("ValueTuple", @" .class public sequential ansi sealed beforefieldinit System.ValueTuple extends [netstandard]System.ValueType { // Nested Types .class nested public sequential ansi sealed beforefieldinit '<MessageType>e__FixedBuffer' extends [netstandard]System.ValueType { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [netstandard]System.Runtime.CompilerServices.UnsafeValueTypeAttribute::.ctor() = ( 01 00 00 00 ) .pack 0 .size 200 // Fields .field public int32 FixedElementField } // end of class <MessageType>e__FixedBuffer // Fields .field public valuetype System.ValueTuple/'<MessageType>e__FixedBuffer' MessageType .custom instance void [netstandard]System.Runtime.CompilerServices.FixedBufferAttribute::.ctor(class [netstandard]System.Type, int32) = ( 01 00 5c 53 79 73 74 65 6d 2e 49 6e 74 33 32 2c 20 6e 65 74 73 74 61 6e 64 61 72 64 2c 20 56 65 72 73 69 6f 6e 3d 32 2e 30 2e 30 2e 30 2c 20 43 75 6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50 75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 63 63 37 62 31 33 66 66 63 64 32 64 64 64 35 31 32 00 00 00 00 00 ) } // end of class System.ValueTuple "); } } [Fact] [WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")] public void TupleUnderlyingType_FromCSharp() { var source = @"#pragma warning disable 169 class Program { static System.ValueTuple F0; static (int, int) F1; static (int A, int B) F2; static (object, object, object, object, object, object, object, object) F3; static (object, object B, object, object D, object, object F, object, object H) F4; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single(); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F0").Single()).Type, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, "System.ValueTuple", "()"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F1").Single()).Type, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F2").Single()).Type, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F3").Single()).Type, TupleUnderlyingTypeValue.Same, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Null, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)"); VerifyTypeFromCSharp((NamedTypeSymbol)((FieldSymbol)containingType.GetMembers("F4").Single()).Type, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Distinct, TupleUnderlyingTypeValue.Null, TupleUnderlyingTypeValue.Null, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)"); } [Fact] [WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")] public void TupleUnderlyingType_FromVisualBasic() { var source = @"Class Program Private F0 As System.ValueTuple Private F1 As (Integer, Integer) Private F2 As (A As Integer, B As Integer) Private F3 As (Object, Object, Object, Object, Object, Object, Object, Object) Private F4 As (Object, B As Object, Object, D As Object, Object, F As Object, Object, H As Object) End Class"; var comp = CreateVisualBasicCompilation(source, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); comp.VerifyDiagnostics(); var containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single(); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F0").Single()).Type, TupleUnderlyingTypeValue.Null, "System.ValueTuple", "System.ValueTuple"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F1").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F2").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F3").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)"); VerifyTypeFromVisualBasic((INamedTypeSymbol)((IFieldSymbol)containingType.GetMembers("F4").Single()).Type, TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)"); } private enum TupleUnderlyingTypeValue { Null, Distinct, Same } private static void VerifyTypeFromCSharp( NamedTypeSymbol type, TupleUnderlyingTypeValue expectedInternalValue, TupleUnderlyingTypeValue expectedPublicValue, TupleUnderlyingTypeValue definitionInternalValue, TupleUnderlyingTypeValue definitionPublicValue, string expectedCSharp, string expectedVisualBasic) { VerifyDisplay(type.GetPublicSymbol(), expectedCSharp, expectedVisualBasic); VerifyInternalType(type, expectedInternalValue); VerifyPublicType(type.GetPublicSymbol(), expectedPublicValue); type = type.OriginalDefinition; VerifyInternalType(type, definitionInternalValue); VerifyPublicType(type.GetPublicSymbol(), definitionPublicValue); } private static void VerifyTypeFromVisualBasic( INamedTypeSymbol type, TupleUnderlyingTypeValue expectedValue, string expectedCSharp, string expectedVisualBasic) { VerifyDisplay(type, expectedCSharp, expectedVisualBasic); VerifyPublicType(type, expectedValue); VerifyPublicType(type.OriginalDefinition, expectedValue); } private static void VerifyDisplay(INamedTypeSymbol type, string expectedCSharp, string expectedVisualBasic) { Assert.Equal(expectedCSharp, CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)); Assert.Equal(expectedVisualBasic, VisualBasic.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)); } private static void VerifyInternalType(NamedTypeSymbol type, TupleUnderlyingTypeValue expectedValue) { var underlyingType = type.TupleUnderlyingType; switch (expectedValue) { case TupleUnderlyingTypeValue.Null: Assert.Null(underlyingType); break; case TupleUnderlyingTypeValue.Distinct: Assert.NotEqual(type, underlyingType); Assert.True(type.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)); Assert.False(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)); VerifyInternalType(underlyingType, TupleUnderlyingTypeValue.Same); break; case TupleUnderlyingTypeValue.Same: Assert.Equal(type, underlyingType); Assert.True(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)); break; default: throw ExceptionUtilities.UnexpectedValue(expectedValue); } } private static void VerifyPublicType(INamedTypeSymbol type, TupleUnderlyingTypeValue expectedValue) { var underlyingType = type.TupleUnderlyingType; switch (expectedValue) { case TupleUnderlyingTypeValue.Null: Assert.Null(underlyingType); break; case TupleUnderlyingTypeValue.Distinct: Assert.NotEqual(type, underlyingType); Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.Default)); Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.ConsiderEverything)); VerifyPublicType(underlyingType, TupleUnderlyingTypeValue.Null); break; default: throw ExceptionUtilities.UnexpectedValue(expectedValue); } } [Fact] [WorkItem(40981, "https://github.com/dotnet/roslyn/issues/40981")] public void TupleFromMetadata_TypeInference() { var source0 = @" using System; public interface IInterface { (Type, Type)[] GetTypeTuples(); } "; var source1 = @" using System; using System.Linq; public class Class { private void Method(IInterface inter, Func<(Type, Type), string> keySelector) { var tuples = inter.GetTypeTuples(); IOrderedEnumerable<(Type, Type)> ordered = tuples.OrderBy(keySelector); } } "; var comp0 = CreateCompilation(new[] { source0, source1 }, options: TestOptions.DebugDll); CompileAndVerify(comp0); var comp1 = CreateCompilation(source0, options: TestOptions.DebugDll); CompileAndVerify(comp1); var comp2 = CreateCompilation(source1, references: new[] { comp1.EmitToImageReference() }, options: TestOptions.DebugDll); CompileAndVerify(comp2); } [Fact] [WorkItem(1090920, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/1090920")] public void GetSymbolInfoOnInitializerOfValueTupleField() { var source = @" namespace System { public struct ValueTuple<T1> { public T1 Item1 = default; public ValueTuple(T1 item1) { } } } "; var comp = CreateCompilation(new[] { source }, options: TestOptions.DebugDll); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var literal = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.True(model.GetSymbolInfo(literal).IsEmpty); } [Fact, WorkItem(1090920, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/1090920")] public void NameofFixedBuffer() { var source = @" namespace System { public class C { public static void Main() { ValueTuple<int> myStruct = default; Console.Write(myStruct.ToString()); char[] o; myStruct.DoSomething(out o); Console.Write(Other.GetFromExternal()); } } public unsafe struct ValueTuple<T1> { public fixed char MessageType[50]; public override string ToString() { return nameof(MessageType); } public void DoSomething(out char[] x) { x = new char[] { }; Action a = () => { System.Console.Write($"" {nameof(x)} ""); }; a(); } } class Other { public static string GetFromExternal() { ValueTuple<int> myStruct = default; return nameof(myStruct.MessageType); } } } "; var compilation = CreateCompilationWithMscorlib45(source, null, TestOptions.UnsafeDebugExe); CompileAndVerify(compilation, expectedOutput: "MessageType x MessageType").VerifyDiagnostics(); } [Fact] [WorkItem(27322, "https://github.com/dotnet/roslyn/issues/27322")] public void ExpressionTreeWithTuple() { var source = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { static void Main() { var tupleA = (1, 3); var tupleB = (1, ""123"".Length); Expression<Func<int>> ok1 = () => tupleA.Item1; Expression<Func<int>> ok2 = () => tupleA.GetHashCode(); Expression<Func<Tuple<int, int>>> ok3 = () => tupleA.ToTuple(); Expression<Func<bool>> ok4 = () => Equals(tupleA, tupleB); Expression<Func<int>> ok5 = () => Comparer<(int, int)>.Default.Compare(tupleA, tupleB); ok1.Compile()(); ok2.Compile()(); ok3.Compile()(); ok4.Compile()(); ok5.Compile()(); Expression<Func<bool>> issue1 = () => tupleA.Equals(tupleB); Expression<Func<int>> issue2 = () => tupleA.CompareTo(tupleB); Console.WriteLine(""Done.""); } }"; var comp = CreateCompilation( source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"Done."); verifier.VerifyIL("C.Main", @" { // Code size 799 (0x31f) .maxstack 7 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Linq.Expressions.Expression<System.Func<int>> V_1, //ok1 System.Linq.Expressions.Expression<System.Func<int>> V_2, //ok2 System.Linq.Expressions.Expression<System.Func<System.Tuple<int, int>>> V_3, //ok3 System.Linq.Expressions.Expression<System.Func<bool>> V_4) //ok4 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: ldc.i4.3 IL_0009: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000e: stfld ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_0013: ldloc.0 IL_0014: ldc.i4.1 IL_0015: ldstr ""123"" IL_001a: call ""int string.Length.get"" IL_001f: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0024: stfld ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_0029: ldloc.0 IL_002a: ldtoken ""C.<>c__DisplayClass0_0"" IL_002f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0034: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0039: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_003e: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0043: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0048: ldtoken ""int System.ValueTuple<int, int>.Item1"" IL_004d: ldtoken ""System.ValueTuple<int, int>"" IL_0052: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle, System.RuntimeTypeHandle)"" IL_0057: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_005c: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0061: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0066: stloc.1 IL_0067: ldloc.0 IL_0068: ldtoken ""C.<>c__DisplayClass0_0"" IL_006d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0072: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0077: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_007c: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0081: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0086: ldtoken ""int object.GetHashCode()"" IL_008b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0090: castclass ""System.Reflection.MethodInfo"" IL_0095: call ""System.Linq.Expressions.Expression[] System.Array.Empty<System.Linq.Expressions.Expression>()"" IL_009a: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_009f: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_00a4: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a9: stloc.2 IL_00aa: ldnull IL_00ab: ldtoken ""System.Tuple<int, int> System.TupleExtensions.ToTuple<int, int>(System.ValueTuple<int, int>)"" IL_00b0: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_00b5: castclass ""System.Reflection.MethodInfo"" IL_00ba: ldc.i4.1 IL_00bb: newarr ""System.Linq.Expressions.Expression"" IL_00c0: dup IL_00c1: ldc.i4.0 IL_00c2: ldloc.0 IL_00c3: ldtoken ""C.<>c__DisplayClass0_0"" IL_00c8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00cd: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_00d2: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_00d7: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_00dc: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_00e1: stelem.ref IL_00e2: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_00e7: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_00ec: call ""System.Linq.Expressions.Expression<System.Func<System.Tuple<int, int>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Tuple<int, int>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00f1: stloc.3 IL_00f2: ldnull IL_00f3: ldtoken ""bool object.Equals(object, object)"" IL_00f8: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_00fd: castclass ""System.Reflection.MethodInfo"" IL_0102: ldc.i4.2 IL_0103: newarr ""System.Linq.Expressions.Expression"" IL_0108: dup IL_0109: ldc.i4.0 IL_010a: ldloc.0 IL_010b: ldtoken ""C.<>c__DisplayClass0_0"" IL_0110: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0115: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_011a: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_011f: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0124: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0129: ldtoken ""object"" IL_012e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0133: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0138: stelem.ref IL_0139: dup IL_013a: ldc.i4.1 IL_013b: ldloc.0 IL_013c: ldtoken ""C.<>c__DisplayClass0_0"" IL_0141: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0146: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_014b: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_0150: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0155: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_015a: ldtoken ""object"" IL_015f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0164: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0169: stelem.ref IL_016a: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_016f: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0174: call ""System.Linq.Expressions.Expression<System.Func<bool>> System.Linq.Expressions.Expression.Lambda<System.Func<bool>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0179: stloc.s V_4 IL_017b: ldnull IL_017c: ldtoken ""System.Collections.Generic.Comparer<System.ValueTuple<int, int>> System.Collections.Generic.Comparer<System.ValueTuple<int, int>>.Default.get"" IL_0181: ldtoken ""System.Collections.Generic.Comparer<System.ValueTuple<int, int>>"" IL_0186: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_018b: castclass ""System.Reflection.MethodInfo"" IL_0190: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0195: ldtoken ""int System.Collections.Generic.Comparer<System.ValueTuple<int, int>>.Compare(System.ValueTuple<int, int>, System.ValueTuple<int, int>)"" IL_019a: ldtoken ""System.Collections.Generic.Comparer<System.ValueTuple<int, int>>"" IL_019f: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_01a4: castclass ""System.Reflection.MethodInfo"" IL_01a9: ldc.i4.2 IL_01aa: newarr ""System.Linq.Expressions.Expression"" IL_01af: dup IL_01b0: ldc.i4.0 IL_01b1: ldloc.0 IL_01b2: ldtoken ""C.<>c__DisplayClass0_0"" IL_01b7: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01bc: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_01c1: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_01c6: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_01cb: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_01d0: stelem.ref IL_01d1: dup IL_01d2: ldc.i4.1 IL_01d3: ldloc.0 IL_01d4: ldtoken ""C.<>c__DisplayClass0_0"" IL_01d9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01de: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_01e3: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_01e8: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_01ed: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_01f2: stelem.ref IL_01f3: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_01f8: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_01fd: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0202: ldloc.1 IL_0203: callvirt ""System.Func<int> System.Linq.Expressions.Expression<System.Func<int>>.Compile()"" IL_0208: callvirt ""int System.Func<int>.Invoke()"" IL_020d: pop IL_020e: ldloc.2 IL_020f: callvirt ""System.Func<int> System.Linq.Expressions.Expression<System.Func<int>>.Compile()"" IL_0214: callvirt ""int System.Func<int>.Invoke()"" IL_0219: pop IL_021a: ldloc.3 IL_021b: callvirt ""System.Func<System.Tuple<int, int>> System.Linq.Expressions.Expression<System.Func<System.Tuple<int, int>>>.Compile()"" IL_0220: callvirt ""System.Tuple<int, int> System.Func<System.Tuple<int, int>>.Invoke()"" IL_0225: pop IL_0226: ldloc.s V_4 IL_0228: callvirt ""System.Func<bool> System.Linq.Expressions.Expression<System.Func<bool>>.Compile()"" IL_022d: callvirt ""bool System.Func<bool>.Invoke()"" IL_0232: pop IL_0233: callvirt ""System.Func<int> System.Linq.Expressions.Expression<System.Func<int>>.Compile()"" IL_0238: callvirt ""int System.Func<int>.Invoke()"" IL_023d: pop IL_023e: ldloc.0 IL_023f: ldtoken ""C.<>c__DisplayClass0_0"" IL_0244: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0249: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_024e: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_0253: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0258: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_025d: ldtoken ""bool System.ValueTuple<int, int>.Equals(System.ValueTuple<int, int>)"" IL_0262: ldtoken ""System.ValueTuple<int, int>"" IL_0267: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_026c: castclass ""System.Reflection.MethodInfo"" IL_0271: ldc.i4.1 IL_0272: newarr ""System.Linq.Expressions.Expression"" IL_0277: dup IL_0278: ldc.i4.0 IL_0279: ldloc.0 IL_027a: ldtoken ""C.<>c__DisplayClass0_0"" IL_027f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0284: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0289: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_028e: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0293: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0298: stelem.ref IL_0299: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_029e: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_02a3: call ""System.Linq.Expressions.Expression<System.Func<bool>> System.Linq.Expressions.Expression.Lambda<System.Func<bool>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_02a8: pop IL_02a9: ldloc.0 IL_02aa: ldtoken ""C.<>c__DisplayClass0_0"" IL_02af: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02b4: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_02b9: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleA"" IL_02be: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_02c3: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_02c8: ldtoken ""int System.ValueTuple<int, int>.CompareTo(System.ValueTuple<int, int>)"" IL_02cd: ldtoken ""System.ValueTuple<int, int>"" IL_02d2: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle, System.RuntimeTypeHandle)"" IL_02d7: castclass ""System.Reflection.MethodInfo"" IL_02dc: ldc.i4.1 IL_02dd: newarr ""System.Linq.Expressions.Expression"" IL_02e2: dup IL_02e3: ldc.i4.0 IL_02e4: ldloc.0 IL_02e5: ldtoken ""C.<>c__DisplayClass0_0"" IL_02ea: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02ef: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_02f4: ldtoken ""System.ValueTuple<int, int> C.<>c__DisplayClass0_0.tupleB"" IL_02f9: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_02fe: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_0303: stelem.ref IL_0304: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0309: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_030e: call ""System.Linq.Expressions.Expression<System.Func<int>> System.Linq.Expressions.Expression.Lambda<System.Func<int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0313: pop IL_0314: ldstr ""Done."" IL_0319: call ""void System.Console.WriteLine(string)"" IL_031e: ret } "); } [Fact] [WorkItem(24517, "https://github.com/dotnet/roslyn/issues/24517")] public void Issue24517() { var source = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { static void Main() { Expression<Func<ValueTuple<int, int>>> e1 = () => new ValueTuple<int, int>(1, 2); Expression<Func<KeyValuePair<int, int>>> e2 = () => new KeyValuePair<int, int>(1, 2); e1.Compile()(); e2.Compile()(); Console.WriteLine(""Done.""); } }"; var comp = CreateCompilation( source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"Done."); } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); var type = (SourceNamedTypeSymbol)comp.GetMember("System.ValueTuple"); var field = (SourceMemberFieldSymbolFromDeclarator)type.GetMember("Item1"); var underlyingField = field.TupleUnderlyingField; Assert.True(field.RequiresCompletion); Assert.True(underlyingField.RequiresCompletion); Assert.False(field.HasComplete(CompletionPart.All)); Assert.False(underlyingField.HasComplete(CompletionPart.All)); field.ForceComplete(null, default); Assert.True(field.RequiresCompletion); Assert.True(underlyingField.RequiresCompletion); Assert.True(field.HasComplete(CompletionPart.All)); Assert.True(underlyingField.HasComplete(CompletionPart.All)); } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void EmptyValueTuple() { var source = @" namespace System { public struct ValueTuple<T1, T2> { } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "emptyValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); verifier.VerifyTypeIL("ValueTuple`2", @" .class public sequential ansi sealed beforefieldinit System.ValueTuple`2<T1, T2> extends [mscorlib]System.ValueType { .pack 0 .size 1 } // end of class System.ValueTuple`2 "); var client = @" class C { int M((int, int) t) { return t.Item1; } } "; var comp2 = CreateCompilation(client, references: new[] { comp.EmitToImageReference() }, targetFramework: TargetFramework.Mscorlib40); comp2.VerifyDiagnostics( // (6,18): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // return t.Item1; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 18) ); var comp3 = CreateCompilation("", references: new[] { comp.ToMetadataReference() }, targetFramework: TargetFramework.Mscorlib46); var retargetingValueTupleType = (NamedTypeSymbol)comp3.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.IsType<RetargetingNamedTypeSymbol>(retargetingValueTupleType); Assert.Empty(retargetingValueTupleType.GetFieldsToEmit()); verify(retargetingValueTupleType.GetMember<FieldSymbol>("Item1"), retargeting: true, index: 0); verify(retargetingValueTupleType.GetMember<FieldSymbol>("Item2"), retargeting: true, index: 1); AssertEx.SetEqual(new string[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "(T1, T2)..ctor()" }, retargetingValueTupleType.GetMembers().ToTestDisplayStrings()); AssertEx.SetEqual(new string[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "(T1, T2)..ctor()" }, retargetingValueTupleType.GetMembersUnordered().OrderBy(m => m.Name).ToTestDisplayStrings()); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.Empty(type.GetFieldsToEmit()); var item1 = type.GetMember<FieldSymbol>("Item1"); verify(item1, retargeting: false, index: 0); var item2 = type.GetMember<FieldSymbol>("Item2"); verify(item2, retargeting: false, index: 1); } static void verify(FieldSymbol field, bool retargeting, int index) { Assert.True(field.IsDefinition); Assert.True(field.HasUseSiteError); Assert.True(field.IsTupleElement()); Assert.True(field.IsDefaultTupleElement); Assert.Equal(index, field.TupleElementIndex); Assert.Null(field.TupleUnderlyingField); Assert.Same(field, field.CorrespondingTupleField); Assert.False(field.IsExplicitlyNamedTupleElement); } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void EmptyValueTuple_WithCtor() { var source = @" namespace System { public struct ValueTuple<T1, T2> { ValueTuple(T1 item1, T2 item2) => throw null; } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "emptyValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); verifier.VerifyTypeIL("ValueTuple`2", @" .class public sequential ansi sealed beforefieldinit System.ValueTuple`2<T1, T2> extends [mscorlib]System.ValueType { .pack 0 .size 1 // Methods .method private hidebysig specialname rtspecialname instance void .ctor ( !T1 item1, !T2 item2 ) cil managed { // Method begins at RVA 0x2050 // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method ValueTuple`2::.ctor } // end of class System.ValueTuple`2 "); var client = @" class C { int M((int, int) t) { return t.Item1; } } "; var comp2 = CreateCompilation(client, references: new[] { comp.EmitToImageReference() }, targetFramework: TargetFramework.Mscorlib40); comp2.VerifyDiagnostics( // (6,18): error CS8128: Member 'Item1' was not found on type '(T1, T2)' from assembly 'emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // return t.Item1; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "Item1").WithArguments("Item1", "(T1, T2)", "emptyValueTuple, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 18) ); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.Equal("(T1, T2)", type.ToTestDisplayString()); var fields = type.GetMembers().OfType<FieldSymbol>(); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, fields.ToTestDisplayStrings()); Assert.All(fields, f => Assert.True(f.HasUseSiteError)); Assert.Equal(module is SourceModuleSymbol ? "SourceNamedTypeSymbol" : "PENamedTypeSymbolGeneric", type.GetType().Name); Assert.Empty(type.GetFieldsToEmit()); } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void EmptyValueTuple_WithTupleSyntaxInside() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public (T1, T2) M() => throw null; public (T1 Item1, T2 Item2) M2() => throw null; public (T1, T2 Item2) M3() => throw null; } }"; var comp = CreateCompilation(source + tupleattributes_cs, targetFramework: TargetFramework.Mscorlib40); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M").ReturnType; if (isSourceSymbol) Assert.Equal("SourceNamedTypeSymbol: (T1, T2)", print(tuple1)); else Assert.Equal("PENamedTypeSymbolGeneric: (T1, T2)", print(tuple1)); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1 Item1, T2 Item2)", print(tuple2)); if (isSourceSymbol) { AssertTestDisplayString(tuple2.GetMembers(), "T1 (T1 Item1, T2 Item2).Item1", "T2 (T1 Item1, T2 Item2).Item2", "(T1, T2) (T1 Item1, T2 Item2).M()", "(T1 Item1, T2 Item2) (T1 Item1, T2 Item2).M2()", "(T1, T2 Item2) (T1 Item1, T2 Item2).M3()", "(T1 Item1, T2 Item2)..ctor()"); } else { AssertTestDisplayString(tuple2.GetMembers(), "T1 (T1 Item1, T2 Item2).Item1", "T2 (T1 Item1, T2 Item2).Item2", "(T1 Item1, T2 Item2)..ctor()", "(T1, T2) (T1 Item1, T2 Item2).M()", "(T1 Item1, T2 Item2) (T1 Item1, T2 Item2).M2()", "(T1, T2 Item2) (T1 Item1, T2 Item2).M3()"); } var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1, T2 Item2)", print(tuple3)); } static string print(NamedTypeSymbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void ValueTuple_WithTupleSyntaxInside() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public (T1, T2) M() => throw null; public (T1 Item1, T2 Item2) M2() => throw null; public (T1, T2 Item2) M3() => throw null; } }"; var comp = CreateCompilation(source + tupleattributes_cs, targetFramework: TargetFramework.Mscorlib40); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M").ReturnType; if (isSourceSymbol) Assert.Equal("SourceNamedTypeSymbol: (T1, T2)", print(tuple1)); else Assert.Equal("PENamedTypeSymbolGeneric: (T1, T2)", print(tuple1)); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1 Item1, T2 Item2)", print(tuple2)); var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("System.ValueTuple.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (T1, T2 Item2)", print(tuple3)); } static string print(NamedTypeSymbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Fact, WorkItem(43597, "https://github.com/dotnet/roslyn/issues/43597")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void TestValueTuplesDefinition() { var comp = CreateCompilation(trivial2uple + trivial3uple + trivialRemainingTuples, targetFramework: TargetFramework.Mscorlib40); CompileAndVerify(comp, sourceSymbolValidator: verifyModule, symbolValidator: verifyModule); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var retargetingValueTupleTypes = comp2.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple"); verifyTupleTypes(retargetingValueTupleTypes, retargeting: true); static void verifyModule(ModuleSymbol module) { var valueTupleTypes = module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple"); verifyTupleTypes(valueTupleTypes, retargeting: false); } static void verifyTupleTypes(ImmutableArray<Symbol> valueTupleTypes, bool retargeting) { AssertEx.SetEqual(new[] { "(T1, T2)", "(T1, T2, T3)", "System.ValueTuple<T1>", "(T1, T2, T3, T4)", "(T1, T2, T3, T4, T5)", "(T1, T2, T3, T4, T5, T6)", "(T1, T2, T3, T4, T5, T6, T7)", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>" }, valueTupleTypes.ToTestDisplayStrings()); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2" }, ((NamedTypeSymbol)valueTupleTypes[0]).GetFieldsToEmit().ToTestDisplayStrings()); verify(valueTupleTypes[0], name: "Item1", display: "T1 (T1, T2).Item1", index: 0); verify(valueTupleTypes[0], "Item2", "T2 (T1, T2).Item2", 1); verify(valueTupleTypes[1], "Item1", "T1 (T1, T2, T3).Item1", 0); verify(valueTupleTypes[1], "Item2", "T2 (T1, T2, T3).Item2", 1); verify(valueTupleTypes[1], "Item3", "T3 (T1, T2, T3).Item3", 2); verify(valueTupleTypes[2], "Item1", "T1 System.ValueTuple<T1>.Item1", 0); verify(valueTupleTypes[3], "Item1", "T1 (T1, T2, T3, T4).Item1", 0); verify(valueTupleTypes[3], "Item2", "T2 (T1, T2, T3, T4).Item2", 1); verify(valueTupleTypes[3], "Item3", "T3 (T1, T2, T3, T4).Item3", 2); verify(valueTupleTypes[3], "Item4", "T4 (T1, T2, T3, T4).Item4", 3); verify(valueTupleTypes[4], "Item1", "T1 (T1, T2, T3, T4, T5).Item1", 0); verify(valueTupleTypes[4], "Item2", "T2 (T1, T2, T3, T4, T5).Item2", 1); verify(valueTupleTypes[4], "Item3", "T3 (T1, T2, T3, T4, T5).Item3", 2); verify(valueTupleTypes[4], "Item4", "T4 (T1, T2, T3, T4, T5).Item4", 3); verify(valueTupleTypes[4], "Item5", "T5 (T1, T2, T3, T4, T5).Item5", 4); verify(valueTupleTypes[5], "Item1", "T1 (T1, T2, T3, T4, T5, T6).Item1", 0); verify(valueTupleTypes[5], "Item2", "T2 (T1, T2, T3, T4, T5, T6).Item2", 1); verify(valueTupleTypes[5], "Item3", "T3 (T1, T2, T3, T4, T5, T6).Item3", 2); verify(valueTupleTypes[5], "Item4", "T4 (T1, T2, T3, T4, T5, T6).Item4", 3); verify(valueTupleTypes[5], "Item5", "T5 (T1, T2, T3, T4, T5, T6).Item5", 4); verify(valueTupleTypes[5], "Item6", "T6 (T1, T2, T3, T4, T5, T6).Item6", 5); verify(valueTupleTypes[6], "Item1", "T1 (T1, T2, T3, T4, T5, T6, T7).Item1", 0); verify(valueTupleTypes[6], "Item2", "T2 (T1, T2, T3, T4, T5, T6, T7).Item2", 1); verify(valueTupleTypes[6], "Item3", "T3 (T1, T2, T3, T4, T5, T6, T7).Item3", 2); verify(valueTupleTypes[6], "Item4", "T4 (T1, T2, T3, T4, T5, T6, T7).Item4", 3); verify(valueTupleTypes[6], "Item5", "T5 (T1, T2, T3, T4, T5, T6, T7).Item5", 4); verify(valueTupleTypes[6], "Item6", "T6 (T1, T2, T3, T4, T5, T6, T7).Item6", 5); verify(valueTupleTypes[6], "Item7", "T7 (T1, T2, T3, T4, T5, T6, T7).Item7", 6); void verify(Symbol tuple, string name, string display, int index) { var isSourceSymbol = tuple.ContainingModule is SourceModuleSymbol; var namedType = (NamedTypeSymbol)tuple; Assert.True(namedType.IsTupleType); Assert.Equal(isSourceSymbol ? "SourceNamedTypeSymbol" : (retargeting ? "RetargetingNamedTypeSymbol" : "PENamedTypeSymbolGeneric"), namedType.GetType().Name); var item = namedType.GetMember<FieldSymbol>(name); if (retargeting) { Assert.IsType<RetargetingFieldSymbol>(item); } else if (isSourceSymbol) { Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(item); } else { Assert.IsType<PEFieldSymbol>(item); } Assert.True(item.IsDefaultTupleElement); Assert.True(item.IsDefinition); Assert.False(item.IsImplicitlyDeclared); Assert.False(item.IsVirtualTupleField); Assert.Equal(display, item.ToTestDisplayString()); Assert.Equal(index, item.TupleElementIndex); Assert.Equal(name, item.Name); Assert.Equal(1, item.Locations.Length); if (retargeting || isSourceSymbol) { Assert.Equal(name, item.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } else { Assert.Empty(item.DeclaringSyntaxReferences); } Assert.Same(item, item.TupleUnderlyingField); Assert.Same(item, item.CorrespondingTupleField); Assert.False(item.IsExplicitlyNamedTupleElement); Assert.Null(item.AssociatedSymbol); } } } [Fact, WorkItem(43597, "https://github.com/dotnet/roslyn/issues/43597")] [WorkItem(43549, "https://github.com/dotnet/roslyn/issues/43549")] public void TestValueTuple8Definition() { var comp = CreateCompilation(trivialRemainingTuples, targetFramework: TargetFramework.Mscorlib40); CompileAndVerify(comp, sourceSymbolValidator: verifyModule, symbolValidator: verifyModule); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var retargetingValueTupleTypes = comp2.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple"); verifyTuple8Type(retargetingValueTupleTypes[5], retargeting: true); static void verifyModule(ModuleSymbol module) { var valueTupleTypes = module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").As<NamedTypeSymbol>(); AssertEx.SetEqual(new[] { "System.ValueTuple<T1>", "(T1, T2, T3, T4)", "(T1, T2, T3, T4, T5)", "(T1, T2, T3, T4, T5, T6)", "(T1, T2, T3, T4, T5, T6, T7)", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>" }, valueTupleTypes.ToTestDisplayStrings()); } static void verifyTuple8Type(Symbol tuple, bool retargeting) { verify("Item1", "T1 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item1"); verify("Item2", "T2 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item2"); verify("Item3", "T3 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item3"); verify("Item4", "T4 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item4"); verify("Item5", "T5 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item5"); verify("Item6", "T6 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item6"); verify("Item7", "T7 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item7"); verify("Rest", "TRest System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Rest"); void verify(string name, string display) { var isSourceSymbol = tuple.ContainingModule is SourceModuleSymbol; var namedType = (NamedTypeSymbol)tuple; Assert.False(namedType.IsTupleType); var item = namedType.GetMember<FieldSymbol>(name); Assert.Equal(-1, item.TupleElementIndex); if (retargeting) { Assert.IsType<RetargetingFieldSymbol>(item); } else if (isSourceSymbol) { Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(item); } else { Assert.IsType<PEFieldSymbol>(item); } Assert.False(item.IsDefaultTupleElement); Assert.True(item.IsDefinition); Assert.False(item.IsImplicitlyDeclared); Assert.False(item.IsVirtualTupleField); Assert.Equal(display, item.ToTestDisplayString()); Assert.Equal(-1, item.TupleElementIndex); Assert.Equal(name, item.Name); Assert.Equal(1, item.Locations.Length); if (retargeting || isSourceSymbol) { Assert.Equal(name, item.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } else { Assert.Empty(item.DeclaringSyntaxReferences); } Assert.Null(item.TupleUnderlyingField); Assert.Null(item.CorrespondingTupleField); Assert.False(item.IsExplicitlyNamedTupleElement); Assert.Null(item.AssociatedSymbol); } } } [Fact, WorkItem(43595, "https://github.com/dotnet/roslyn/issues/43595")] public void TestValueTuple2Definition_WithExtraField() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public string field; } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "customValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); var comp3 = CreateCompilation("", references: new[] { comp.ToMetadataReference() }, targetFramework: TargetFramework.Mscorlib46); var retargetingValueTupleType = (NamedTypeSymbol)comp3.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); Assert.IsType<RetargetingNamedTypeSymbol>(retargetingValueTupleType); verifyTupleType(retargetingValueTupleType, retargeting: true); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); verifyTupleType(type, retargeting: false); } static void verifyTupleType(NamedTypeSymbol namedType, bool retargeting) { Assert.Equal("(T1, T2)", namedType.ToTestDisplayString()); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "System.String (T1, T2).field" }, namedType.GetFieldsToEmit().ToTestDisplayStrings()); var fields = namedType.GetMembers().OfType<FieldSymbol>(); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "System.String (T1, T2).field" }, fields.ToTestDisplayStrings()); Assert.All(fields, f => Assert.False(f.HasUseSiteError)); verify("Item1", "T1 (T1, T2).Item1", isTupleElement: true); verify("Item2", "T2 (T1, T2).Item2", true); verify("field", "System.String (T1, T2).field", false); void verify(string name, string display, bool isTupleElement) { var isSourceSymbol = namedType.ContainingModule is SourceModuleSymbol; Assert.True(namedType.IsTupleType); var item = namedType.GetMember<FieldSymbol>(name); if (retargeting) { Assert.IsType<RetargetingFieldSymbol>(item); } else if (isSourceSymbol) { Assert.IsType<SourceMemberFieldSymbolFromDeclarator>(item); } else { Assert.IsType<PEFieldSymbol>(item); } Assert.Equal(isTupleElement, item.IsDefaultTupleElement); Assert.True(item.IsDefinition); Assert.False(item.IsImplicitlyDeclared); Assert.False(item.IsVirtualTupleField); Assert.Equal(display, item.ToTestDisplayString()); Assert.Equal(name, item.Name); Assert.Equal(1, item.Locations.Length); if (retargeting || isSourceSymbol) { Assert.Equal(name, item.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } else { Assert.Empty(item.DeclaringSyntaxReferences); } if (isTupleElement) { Assert.Same(item, item.CorrespondingTupleField); } else { Assert.Equal(-1, item.TupleElementIndex); Assert.Null(item.CorrespondingTupleField); } Assert.False(item.IsExplicitlyNamedTupleElement); Assert.Same(item, item.TupleUnderlyingField); Assert.Null(item.AssociatedSymbol); } } } [Fact] public void TestValueTuple2Definition_WithExtraAutoProperty() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public string Property { get; set; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40, assemblyName: "customValueTuple"); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var namedType = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); var isSourceSymbol = namedType.ContainingModule is SourceModuleSymbol; Assert.Equal("(T1, T2)", namedType.ToTestDisplayString()); var fields = namedType.GetMembers().OfType<FieldSymbol>(); AssertEx.SetEqual(new[] { "T1 (T1, T2).Item1", "T2 (T1, T2).Item2", "System.String (T1, T2).<Property>k__BackingField" }, fields.ToTestDisplayStrings()); var backingField = namedType.GetField("<Property>k__BackingField"); if (isSourceSymbol) { Assert.IsType<SynthesizedBackingFieldSymbol>(backingField); Assert.Equal("System.String (T1, T2).Property { get; set; }", backingField.AssociatedSymbol.ToTestDisplayString()); } else { Assert.IsType<PEFieldSymbol>(backingField); Assert.Null(backingField.AssociatedSymbol); } } } [Fact] public void SwitchWithNamedTuple() { var source = @" class C { static int M() { var isColInit = true; var errorCode = (message: """", isColInit) switch { (message: null, isColInit: true) => 42, (message: null, isColInit: false) => 43, (message: { }, isColInit: true) => 44, (message: { }, isColInit: false) => 45, }; return errorCode; } } " + trivial2uple + tupleattributes_cs; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_Item2() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item2; public T1 Item13; public T1 Rest; } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); var item2 = type.GetMember<FieldSymbol>("Item2"); verify(item2); var item13 = type.GetMember<FieldSymbol>("Item13"); verify(item13); var rest = type.GetMember<FieldSymbol>("Rest"); verify(rest); } static void verify(FieldSymbol field) { Assert.False(field.IsTupleElement()); Assert.False(field.IsDefaultTupleElement); Assert.Equal(-1, field.TupleElementIndex); Assert.Same(field, field.TupleUnderlyingField); Assert.Null(field.CorrespondingTupleField); } } [Fact] public void TupleWithElementNamedWithDefaultName() { // Instrumenting test as part of investigating flakiness: https://github.com/dotnet/roslyn/issues/52658 for (int i = 0; i < 1000; i++) { string source = @" class C { (int Item1, int Item2) M() => throw null; } "; var comp = CreateCompilation(source); var m = (MethodSymbol)comp.GetMember("C.M"); var tuple = m.ReturnType; Assert.Equal("(System.Int32 Item1, System.Int32 Item2)", tuple.ToTestDisplayString()); Assert.IsType<ConstructedNamedTypeSymbol>(tuple); var item1 = tuple.GetMember<TupleElementFieldSymbol>("Item1"); // Instrumenting test as part of investigating flakiness: https://github.com/dotnet/roslyn/issues/52658 RoslynDebug.AssertOrFailFast(0 == item1.TupleElementIndex); var item1Underlying = item1.TupleUnderlyingField; Assert.IsType<SubstitutedFieldSymbol>(item1Underlying); Assert.Equal("System.Int32 (System.Int32 Item1, System.Int32 Item2).Item1", item1Underlying.ToTestDisplayString()); // Instrumenting test as part of investigating flakiness: https://github.com/dotnet/roslyn/issues/52658 RoslynDebug.AssertOrFailFast(0 == item1Underlying.TupleElementIndex); Assert.Same(item1Underlying, item1Underlying.TupleUnderlyingField); var item2 = tuple.GetMember<TupleElementFieldSymbol>("Item2"); Assert.Equal(1, item2.TupleElementIndex); var item2Underlying = item2.TupleUnderlyingField; Assert.IsType<SubstitutedFieldSymbol>(item2Underlying); Assert.Equal(1, item2Underlying.TupleElementIndex); Assert.Same(item2Underlying, item2Underlying.TupleUnderlyingField); } } [Fact] public void IndexOfUnderlyingFieldsInTuple9() { string source = @" class C { (int, int, int, int, int, int, int, int, int) M() => throw null; } "; var comp = CreateCompilation(source); var m = (MethodSymbol)comp.GetMember("C.M"); var tuple = m.ReturnType; Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", tuple.ToTestDisplayString()); Assert.IsType<ConstructedNamedTypeSymbol>(tuple); var item8 = tuple.GetMember<TupleElementFieldSymbol>("Item8"); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8", item8.ToTestDisplayString()); Assert.Equal(7, item8.TupleElementIndex); var item8Underlying = item8.TupleUnderlyingField; Assert.Equal("Item1", item8Underlying.Name); Assert.IsType<SubstitutedFieldSymbol>(item8Underlying); Assert.Equal(0, item8Underlying.TupleElementIndex); Assert.Same(item8Underlying, item8Underlying.TupleUnderlyingField); var item9 = tuple.GetMember<TupleElementFieldSymbol>("Item9"); Assert.Equal("System.Int32 (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9", item9.ToTestDisplayString()); Assert.Equal(8, item9.TupleElementIndex); var item9Underlying = item9.TupleUnderlyingField; Assert.Equal("Item2", item9Underlying.Name); Assert.IsType<SubstitutedFieldSymbol>(item9Underlying); Assert.Equal(1, item9Underlying.TupleElementIndex); Assert.Same(item9Underlying, item9Underlying.TupleUnderlyingField); } [Fact] public void RealFieldsAreNotWrapped() { string source = @" public class C { public (int, int) M() => throw null; public (int Item1, int Item2) M2() => throw null; public (int a, int b) M3() => throw null; } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public int field; public ValueTuple(T1 item1, T2 item2) => throw null; } } "; var comp = CreateCompilation(source); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMembers("ValueTuple").Single(); assertValueTupleUnderlyingFields(type, isSourceSymbol); if (isSourceSymbol) { Assert.Equal("SourceNamedTypeSymbol: (T1, T2)", print(type)); AssertEx.SetEqual(new[] { "SourceMemberFieldSymbolFromDeclarator: field", "SourceMemberFieldSymbolFromDeclarator: Item1", "SourceMemberFieldSymbolFromDeclarator: Item2" }, printFields(type)); } else { Assert.Equal("PENamedTypeSymbolGeneric: (T1, T2)", print(type)); AssertEx.SetEqual(new[] { "PEFieldSymbol: field", "PEFieldSymbol: Item1", "PEFieldSymbol: Item2" }, printFields(type)); } var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32)", print(tuple1)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2" }, printFields(tuple1)); assertTupleUnderlyingFields(tuple1); var tuple1Item1 = tuple1.GetMember<FieldSymbol>("Item1"); Assert.False(tuple1Item1.IsDefinition); Assert.Equal("T1 (T1, T2).Item1", tuple1Item1.OriginalDefinition.ToTestDisplayString()); Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", tuple1Item1.OriginalDefinition.GetType().Name); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 Item1, System.Int32 Item2)", print(tuple2)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2" }, printFields(tuple2)); assertTupleUnderlyingFields(tuple2); var tuple2Item1 = tuple2.GetMember<FieldSymbol>("Item1"); Assert.False(tuple2Item1.IsDefinition); Assert.Equal("T1 (T1, T2).Item1", tuple2Item1.OriginalDefinition.ToTestDisplayString()); Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", tuple2Item1.OriginalDefinition.GetType().Name); var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 a, System.Int32 b)", print(tuple3)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleVirtualElementFieldSymbol: a", "TupleElementFieldSymbol: Item2", "TupleVirtualElementFieldSymbol: b", }, printFields(tuple3)); assertTupleUnderlyingFields(tuple3); var tuple3Item1 = tuple3.GetMember<FieldSymbol>("Item1"); Assert.False(tuple3Item1.IsDefinition); Assert.Equal("T1 (T1, T2).Item1", tuple3Item1.OriginalDefinition.ToTestDisplayString()); Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", tuple3Item1.OriginalDefinition.GetType().Name); Assert.True(tuple3.GetMember<FieldSymbol>("a").IsDefinition); Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32)", print(tuple3.TupleUnderlyingType)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: field", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2" }, printFields(tuple3.TupleUnderlyingType)); } static void assertValueTupleUnderlyingFields(NamedTypeSymbol type, bool isSourceSymbol) { var fields = type.GetMembers().OfType<FieldSymbol>(); foreach (var field in fields) { var underlying = field.TupleUnderlyingField; Assert.Equal(isSourceSymbol ? "SourceMemberFieldSymbolFromDeclarator" : "PEFieldSymbol", underlying.GetType().Name); Assert.Equal(isSourceSymbol ? "SourceNamedTypeSymbol" : "PENamedTypeSymbolGeneric", underlying.ContainingType.GetType().Name); } } static void assertTupleUnderlyingFields(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); foreach (var field in fields) { var underlying = field.TupleUnderlyingField; Assert.Equal("SubstitutedFieldSymbol", underlying.GetType().Name); Assert.Equal("ConstructedNamedTypeSymbol", underlying.ContainingType.GetType().Name); } } static IEnumerable<string> printFields(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); return fields.Select(s => s.GetType().Name + ": " + s.Name); } static string print(Symbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Fact] public void RealFieldsAreNotWrapped_LongTuples() { string source = @" public class C { public (int, int, int, int, int, int, int, int) M() => throw null; public (int Item1, int Item2, int Item3, int Item4, int Item5, int Item6, int Item7, int Item8) M2() => throw null; public (int a, int b, int c, int d, int e, int f, int g, int h) M3() => throw null; public System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> M4() => throw null; } "; var comp = CreateCompilation(source + trivialRemainingTuples); CompileAndVerify(comp, symbolValidator: verifyModule, sourceSymbolValidator: verifyModule); static void verifyModule(ModuleSymbol module) { var tuple1 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", print(tuple1)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple1)); assertUnderlying(tuple1); Assert.True(tuple1.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple1.GetMember<FieldSymbol>("Item8").IsDefinition); var tuple2 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M2").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 Item1, System.Int32 Item2, System.Int32 Item3, System.Int32 Item4, System.Int32 Item5, System.Int32 Item6, System.Int32 Item7, System.Int32 Item8)", print(tuple2)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple2)); assertUnderlying(tuple2); Assert.True(tuple2.TupleUnderlyingType.Equals(tuple1, TypeCompareKind.ConsiderEverything)); Assert.True(tuple2.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple2.GetMember<FieldSymbol>("Item8").IsDefinition); var tuple3 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M3").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32 a, System.Int32 b, System.Int32 c, System.Int32 d, System.Int32 e, System.Int32 f, System.Int32 g, System.Int32 h)", print(tuple3)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8", "TupleVirtualElementFieldSymbol: a", "TupleVirtualElementFieldSymbol: b", "TupleVirtualElementFieldSymbol: c", "TupleVirtualElementFieldSymbol: d", "TupleVirtualElementFieldSymbol: e", "TupleVirtualElementFieldSymbol: f", "TupleVirtualElementFieldSymbol: g", "TupleVirtualElementFieldSymbol: h", }, printFields(tuple3)); assertUnderlying(tuple3); Assert.True(tuple3.TupleUnderlyingType.Equals(tuple1, TypeCompareKind.ConsiderEverything)); Assert.True(tuple3.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("Item8").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("a").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("b").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("c").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("d").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("e").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("f").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("g").IsDefinition); Assert.True(tuple3.GetMember<FieldSymbol>("h").IsDefinition); Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", print(tuple3.TupleUnderlyingType)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple3.TupleUnderlyingType)); var tuple4 = (NamedTypeSymbol)module.GlobalNamespace.GetMember<MethodSymbol>("C.M4").ReturnType; Assert.Equal("ConstructedNamedTypeSymbol: (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", print(tuple4)); AssertEx.SetEqual(new[] { "SubstitutedFieldSymbol: Rest", "TupleElementFieldSymbol: Item1", "TupleElementFieldSymbol: Item2", "TupleElementFieldSymbol: Item3", "TupleElementFieldSymbol: Item4", "TupleElementFieldSymbol: Item5", "TupleElementFieldSymbol: Item6", "TupleElementFieldSymbol: Item7", "TupleVirtualElementFieldSymbol: Item8" }, printFields(tuple4)); assertUnderlying(tuple4); Assert.True(tuple4.TupleUnderlyingType.Equals(tuple1, TypeCompareKind.ConsiderEverything)); Assert.True(tuple4.GetMember<FieldSymbol>("Item1").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item2").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item3").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item4").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item5").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item6").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item7").IsDefinition); Assert.True(tuple4.GetMember<FieldSymbol>("Item8").IsDefinition); } static void assertUnderlying(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); foreach (var field in fields) { var underlying = field.TupleUnderlyingField; Assert.Equal("SubstitutedFieldSymbol", underlying.GetType().Name); Assert.Equal("ConstructedNamedTypeSymbol", underlying.ContainingType.GetType().Name); } } static IEnumerable<string> printFields(NamedTypeSymbol type) { var fields = type.GetMembers().OfType<FieldSymbol>(); return fields.Select(s => s.GetType().Name + ": " + s.Name); } static string print(NamedTypeSymbol s) { return s.GetType().Name + ": " + s.ToTestDisplayString(); } } [Theory, WorkItem(43857, "https://github.com/dotnet/roslyn/issues/43857")] [InlineData("(Z a, Z b)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")] [InlineData("(Z, Z b)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, ""b""})")] [InlineData("(Z a, Z)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", null})")] [InlineData("(Z, Z)*", null)] [InlineData("((Z a, Z b), Z c)*", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, ""c"", ""a"", ""b""})")] public void PointerTypeDecoding(string type, string expectedAttribute) { var comp = CompileAndVerify($@" unsafe struct Z {{ public {type} F; }} ", options: TestOptions.UnsafeReleaseDll, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("Z"); var field = c.GetField("F"); if (expectedAttribute == null) { Assert.Empty(field.GetAttributes()); } else { Assert.Equal(expectedAttribute, field.GetAttributes().Single().ToString()); } Assert.Equal(type, field.Type.ToTestDisplayString()); } } [Fact] public void TupleAsMemberTests() { // Use minimal framework to force the tuple symbols to be generated as ErrorFields, because they couldn't be matched with the // nonexistent System.ValueTuple's fields. var comp = CreateCompilation("", targetFramework: TargetFramework.Minimal); var @object = comp.GetSpecialType(SpecialType.System_Object); var obliviousObject = TypeWithAnnotations.Create(@object, NullableAnnotation.Oblivious); // (object~ a, object~ b, object~ c, object~ d, object~ e, object~ f, object~ g, object~ h, object~ i) // All positions are errored var obliviousOriginalTuple = NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: ImmutableArray.Create(obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject, obliviousObject), elementLocations: ImmutableArray.Create<Location>(null, null, null, null, null, null, null, null, null), elementNames: ImmutableArray.Create("a", "b", "c", "d", "e", "f", "g", "h", "i"), comp, shouldCheckConstraints: false, includeNullability: false, errorPositions: ImmutableArray.Create(true, true, true, true, true, true, true, true, true)); AssertEx.Equal("System.ValueTuple<System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, (System.Object, System.Object)>", obliviousOriginalTuple.ToTestDisplayString(includeNonNullable: true)); var nullableObject = TypeWithAnnotations.Create(@object, NullableAnnotation.Annotated); var nonNullableObject = TypeWithAnnotations.Create(@object, NullableAnnotation.NotAnnotated); // (object!, object?, object!, object?, object!, object?, object!, object?, object!) // All positions are errored var nullableEnabledTuple = NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: ImmutableArray.Create(nonNullableObject, nullableObject, nonNullableObject, nullableObject, nonNullableObject, nullableObject, nonNullableObject, nullableObject, nonNullableObject), elementLocations: ImmutableArray.Create<Location>(null, null, null, null, null, null, null, null, null), elementNames: default, comp, shouldCheckConstraints: false, includeNullability: false, errorPositions: ImmutableArray.Create(true, true, true, true, true, true, true, true, true)); AssertEx.Equal("System.ValueTuple<System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, (System.Object?, System.Object!)>", nullableEnabledTuple.ToTestDisplayString(includeNonNullable: true)); // Original tuple fields as a member of the nullable-enabled tuple, should carry the names over for (int i = 0; i < obliviousOriginalTuple.TupleElements.Length; i++) { var originalField = (TupleErrorFieldSymbol)obliviousOriginalTuple.TupleElements[i]; verifyIndexAndDefaultElement(originalField, i, isDefaultElement: false); var nullabilityString = (i % 2 == 1) ? "?" : "!"; var name = ((char)('a' + i)).ToString(); var newField = (TupleErrorFieldSymbol)originalField.AsMember(nullableEnabledTuple); AssertEx.Equal($"System.Object{nullabilityString} System.ValueTuple<System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, (System.Object?, System.Object!)>.{name}", newField.ToTestDisplayString(includeNonNullable: true)); verifyIndexAndDefaultElement(newField, i, isDefaultElement: false); verifyDefaultFieldType(newField, i, nullabilityString); var newDefaultField = (TupleErrorFieldSymbol)newField.CorrespondingTupleField; verifyIndexAndDefaultElement(newDefaultField, i, isDefaultElement: true); verifyDefaultFieldType(newDefaultField, i, nullabilityString); var originalDefaultField = (TupleErrorFieldSymbol)originalField.CorrespondingTupleField; verifyIndexAndDefaultElement(originalDefaultField, i, isDefaultElement: true); newDefaultField = (TupleErrorFieldSymbol)originalDefaultField.AsMember(nullableEnabledTuple); verifyIndexAndDefaultElement(newDefaultField, i, isDefaultElement: true); verifyDefaultFieldType(newDefaultField, i, nullabilityString); } static void verifyIndexAndDefaultElement(TupleErrorFieldSymbol tupleField, int i, bool isDefaultElement) { Assert.Equal(i, tupleField.TupleElementIndex); Assert.Equal(isDefaultElement, tupleField.IsDefaultTupleElement); } static void verifyDefaultFieldType(FieldSymbol tupleField, int i, string nullabilityString) { AssertEx.Equal($"System.Object{nullabilityString} System.ValueTuple<System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, System.Object?, System.Object!, (System.Object?, System.Object!)>.Item{i + 1}", tupleField.CorrespondingTupleField.ToTestDisplayString(includeNonNullable: true)); } } } }
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Xaml/Impl/Features/QuickInfo/IXamlQuickInfoService.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; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal interface IXamlQuickInfoService : ILanguageService { Task<XamlQuickInfo> GetQuickInfoAsync(TextDocument document, int position, CancellationToken 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; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal interface IXamlQuickInfoService : ILanguageService { Task<XamlQuickInfo> GetQuickInfoAsync(TextDocument document, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/Core.Wpf/InlineRename/HighlightTags/RenameFixupTagDefinition.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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags { [Export(typeof(EditorFormatDefinition))] [Name(RenameFixupTag.TagId)] [UserVisible(true)] [ExcludeFromCodeCoverage] internal class RenameFixupTagDefinition : MarkerFormatDefinition { public static double StrokeThickness => 1.0; public static double[] StrokeDashArray => new[] { 4.0, 4.0 }; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameFixupTagDefinition() { this.Border = new Pen(Brushes.Green, thickness: StrokeThickness) { DashStyle = new DashStyle(StrokeDashArray, 0) }; this.DisplayName = EditorFeaturesResources.Inline_Rename_Fixup; this.ZOrder = 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags { [Export(typeof(EditorFormatDefinition))] [Name(RenameFixupTag.TagId)] [UserVisible(true)] [ExcludeFromCodeCoverage] internal class RenameFixupTagDefinition : MarkerFormatDefinition { public static double StrokeThickness => 1.0; public static double[] StrokeDashArray => new[] { 4.0, 4.0 }; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameFixupTagDefinition() { this.Border = new Pen(Brushes.Green, thickness: StrokeThickness) { DashStyle = new DashStyle(StrokeDashArray, 0) }; this.DisplayName = EditorFeaturesResources.Inline_Rename_Fixup; this.ZOrder = 1; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/AggregatedFormattingResult.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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class AggregatedFormattingResult : AbstractAggregatedFormattingResult { public AggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) : base(node, results, formattingSpans) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.Node, GetFormattingSpans(), map, cancellationToken); return rewriter.Transform(); } } }
// 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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class AggregatedFormattingResult : AbstractAggregatedFormattingResult { public AggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) : base(node, results, formattingSpans) { } protected override SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken) { var rewriter = new TriviaRewriter(this.Node, GetFormattingSpans(), map, cancellationToken); return rewriter.Transform(); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackId.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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { [DataContract] internal readonly struct RemoteServiceCallbackId : IEquatable<RemoteServiceCallbackId> { [DataMember(Order = 0)] public readonly int Id; public RemoteServiceCallbackId(int id) => Id = id; public override bool Equals(object? obj) => obj is RemoteServiceCallbackId id && Equals(id); public bool Equals(RemoteServiceCallbackId other) => Id == other.Id; public override int GetHashCode() => Id; public static bool operator ==(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => left.Equals(right); public static bool operator !=(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => !(left == right); } }
// 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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { [DataContract] internal readonly struct RemoteServiceCallbackId : IEquatable<RemoteServiceCallbackId> { [DataMember(Order = 0)] public readonly int Id; public RemoteServiceCallbackId(int id) => Id = id; public override bool Equals(object? obj) => obj is RemoteServiceCallbackId id && Equals(id); public bool Equals(RemoteServiceCallbackId other) => Id == other.Id; public override int GetHashCode() => Id; public static bool operator ==(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => left.Equals(right); public static bool operator !=(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => !(left == right); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Test/Core/ModuleInitializer.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.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { internal static class ModuleInitializer { [ModuleInitializer] internal static void Initialize() { Trace.Listeners.Clear(); Trace.Listeners.Add(new ThrowingTraceListener()); } } }
// 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.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { internal static class ModuleInitializer { [ModuleInitializer] internal static void Initialize() { Trace.Listeners.Clear(); Trace.Listeners.Add(new ThrowingTraceListener()); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Tools/ExternalAccess/FSharp/Internal/VisualStudio/FSharpProjectExternalErrorReporterFactory.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; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.Shell; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.VisualStudio { internal static class FSharpProjectExternalErrorReporterFactory { public static IVsLanguageServiceBuildErrorReporter2 Create(ProjectId projectId, string errorCodePrefix, IServiceProvider serviceProvider) { ThreadHelper.ThrowIfNotOnUIThread(); var workspace = (VisualStudioWorkspaceImpl)serviceProvider.GetMefService<VisualStudioWorkspace>(); workspace.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); return new ProjectExternalErrorReporter(projectId, errorCodePrefix, LanguageNames.FSharp, workspace); } } }
// 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; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.Shell; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.VisualStudio { internal static class FSharpProjectExternalErrorReporterFactory { public static IVsLanguageServiceBuildErrorReporter2 Create(ProjectId projectId, string errorCodePrefix, IServiceProvider serviceProvider) { ThreadHelper.ThrowIfNotOnUIThread(); var workspace = (VisualStudioWorkspaceImpl)serviceProvider.GetMefService<VisualStudioWorkspace>(); workspace.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); return new ProjectExternalErrorReporter(projectId, errorCodePrefix, LanguageNames.FSharp, workspace); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/AbstractUseTypeCodeRefactoringProvider.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; 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.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType { internal abstract class AbstractUseTypeCodeRefactoringProvider : CodeRefactoringProvider { protected abstract string Title { get; } protected abstract Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken); protected abstract TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken); protected abstract TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var declaration = await GetDeclarationAsync(context).ConfigureAwait(false); if (declaration == null) { return; } Debug.Assert(declaration.IsKind(SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredType = FindAnalyzableType(declaration, semanticModel, cancellationToken); if (declaredType == null) { return; } var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var typeStyle = AnalyzeTypeName(declaredType, semanticModel, optionSet, cancellationToken); if (typeStyle.IsStylePreferred && typeStyle.Severity != ReportDiagnostic.Suppress) { // the analyzer would handle this. So we do not. return; } if (!typeStyle.CanConvert()) { return; } context.RegisterRefactoring( new MyCodeAction( Title, c => UpdateDocumentAsync(document, declaredType, c)), declaredType.Span); } private static async Task<SyntaxNode> GetDeclarationAsync(CodeRefactoringContext context) { // We want to provide refactoring for changing the Type of newly introduced variables in following cases: // - DeclarationExpressionSyntax: `"42".TryParseInt32(out var number)` // - VariableDeclarationSyntax: General field / variable declaration statement `var number = 42` // - ForEachStatementSyntax: The variable that gets introduced by foreach `foreach(var number in numbers)` // // In addition to providing the refactoring when the whole node (i.e. the node that introduces the new variable) in question is selected // we also want to enable it when only the type node is selected because this refactoring changes the type. We still have to make sure // we're only working on TypeNodes for in above-mentioned situations. // // For foreach we need to guard against selecting just the expression because it is also of type `TypeSyntax`. var declNode = await context.TryGetRelevantNodeAsync<DeclarationExpressionSyntax>().ConfigureAwait(false); if (declNode != null) return declNode; var variableNode = await context.TryGetRelevantNodeAsync<VariableDeclarationSyntax>().ConfigureAwait(false); if (variableNode != null) return variableNode; // `ref var` is a bit of an interesting construct. 'ref' looks like a modifier, but is actually a // type-syntax. Ensure the user can get the feature anywhere on this construct var type = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); if (type?.Parent is RefTypeSyntax) type = (TypeSyntax)type.Parent; if (type?.Parent is VariableDeclarationSyntax) return type.Parent; var foreachStatement = await context.TryGetRelevantNodeAsync<ForEachStatementSyntax>().ConfigureAwait(false); if (foreachStatement != null) return foreachStatement; var syntaxFacts = context.Document.GetLanguageService<ISyntaxFactsService>(); var typeNode = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); var typeNodeParent = typeNode?.Parent; if (typeNodeParent != null && (typeNodeParent.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.VariableDeclaration) || (typeNodeParent.IsKind(SyntaxKind.ForEachStatement) && !syntaxFacts.IsExpressionOfForeach(typeNode)))) { return typeNodeParent; } return null; } private async Task<Document> UpdateDocumentAsync(Document document, TypeSyntax type, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); await HandleDeclarationAsync(document, editor, type, cancellationToken).ConfigureAwait(false); var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// 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; 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.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType { internal abstract class AbstractUseTypeCodeRefactoringProvider : CodeRefactoringProvider { protected abstract string Title { get; } protected abstract Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken); protected abstract TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken); protected abstract TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var declaration = await GetDeclarationAsync(context).ConfigureAwait(false); if (declaration == null) { return; } Debug.Assert(declaration.IsKind(SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredType = FindAnalyzableType(declaration, semanticModel, cancellationToken); if (declaredType == null) { return; } var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var typeStyle = AnalyzeTypeName(declaredType, semanticModel, optionSet, cancellationToken); if (typeStyle.IsStylePreferred && typeStyle.Severity != ReportDiagnostic.Suppress) { // the analyzer would handle this. So we do not. return; } if (!typeStyle.CanConvert()) { return; } context.RegisterRefactoring( new MyCodeAction( Title, c => UpdateDocumentAsync(document, declaredType, c)), declaredType.Span); } private static async Task<SyntaxNode> GetDeclarationAsync(CodeRefactoringContext context) { // We want to provide refactoring for changing the Type of newly introduced variables in following cases: // - DeclarationExpressionSyntax: `"42".TryParseInt32(out var number)` // - VariableDeclarationSyntax: General field / variable declaration statement `var number = 42` // - ForEachStatementSyntax: The variable that gets introduced by foreach `foreach(var number in numbers)` // // In addition to providing the refactoring when the whole node (i.e. the node that introduces the new variable) in question is selected // we also want to enable it when only the type node is selected because this refactoring changes the type. We still have to make sure // we're only working on TypeNodes for in above-mentioned situations. // // For foreach we need to guard against selecting just the expression because it is also of type `TypeSyntax`. var declNode = await context.TryGetRelevantNodeAsync<DeclarationExpressionSyntax>().ConfigureAwait(false); if (declNode != null) return declNode; var variableNode = await context.TryGetRelevantNodeAsync<VariableDeclarationSyntax>().ConfigureAwait(false); if (variableNode != null) return variableNode; // `ref var` is a bit of an interesting construct. 'ref' looks like a modifier, but is actually a // type-syntax. Ensure the user can get the feature anywhere on this construct var type = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); if (type?.Parent is RefTypeSyntax) type = (TypeSyntax)type.Parent; if (type?.Parent is VariableDeclarationSyntax) return type.Parent; var foreachStatement = await context.TryGetRelevantNodeAsync<ForEachStatementSyntax>().ConfigureAwait(false); if (foreachStatement != null) return foreachStatement; var syntaxFacts = context.Document.GetLanguageService<ISyntaxFactsService>(); var typeNode = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); var typeNodeParent = typeNode?.Parent; if (typeNodeParent != null && (typeNodeParent.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.VariableDeclaration) || (typeNodeParent.IsKind(SyntaxKind.ForEachStatement) && !syntaxFacts.IsExpressionOfForeach(typeNode)))) { return typeNodeParent; } return null; } private async Task<Document> UpdateDocumentAsync(Document document, TypeSyntax type, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); await HandleDeclarationAsync(document, editor, type, cancellationToken).ConfigureAwait(false); var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Xaml/Impl/Features/Formatting/XamlFormattingOptions.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; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting { internal class XamlFormattingOptions { public bool InsertSpaces { get; set; } public int TabSize { get; set; } public IDictionary<string, object> OtherOptions { get; set; } } }
// 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; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting { internal class XamlFormattingOptions { public bool InsertSpaces { get; set; } public int TabSize { get; set; } public IDictionary<string, object> OtherOptions { get; set; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Core/Def/EditorConfigSettings/Common/IEnumSettingViewModelFactory.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.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModelFactory { bool IsSupported(OptionKey2 key); IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting); } }
// 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.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal interface IEnumSettingViewModelFactory { bool IsSupported(OptionKey2 key); IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Remote/Core/IRemoteAssetSynchronizationService.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal interface IRemoteAssetSynchronizationService { /// <summary> /// Synchronize data to OOP proactively without anyone asking for it to make most of operation /// faster /// </summary> ValueTask SynchronizePrimaryWorkspaceAsync(PinnedSolutionInfo solutionInfo, Checksum checksum, int workspaceVersion, CancellationToken cancellationToken); ValueTask SynchronizeTextAsync(DocumentId documentId, Checksum baseTextChecksum, IEnumerable<TextChange> textChanges, CancellationToken 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.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal interface IRemoteAssetSynchronizationService { /// <summary> /// Synchronize data to OOP proactively without anyone asking for it to make most of operation /// faster /// </summary> ValueTask SynchronizePrimaryWorkspaceAsync(PinnedSolutionInfo solutionInfo, Checksum checksum, int workspaceVersion, CancellationToken cancellationToken); ValueTask SynchronizeTextAsync(DocumentId documentId, Checksum baseTextChecksum, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/CSharp/Portable/NavigateTo/CSharpNavigateToSearchService.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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.NavigateTo; namespace Microsoft.CodeAnalysis.CSharp.NavigateTo { [ExportLanguageService(typeof(INavigateToSearchService), LanguageNames.CSharp), Shared] internal class CSharpNavigateToSearchService : AbstractNavigateToSearchService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpNavigateToSearchService() { } } }
// 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.NavigateTo; namespace Microsoft.CodeAnalysis.CSharp.NavigateTo { [ExportLanguageService(typeof(INavigateToSearchService), LanguageNames.CSharp), Shared] internal class CSharpNavigateToSearchService : AbstractNavigateToSearchService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpNavigateToSearchService() { } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Core/Portable/Syntax/SyntaxList.WithTwoChildren.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax { internal partial class SyntaxList { internal class WithTwoChildren : SyntaxList { private SyntaxNode? _child0; private SyntaxNode? _child1; internal WithTwoChildren(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) : base(green, parent, position) { } internal override SyntaxNode? GetNodeSlot(int index) { switch (index) { case 0: return this.GetRedElement(ref _child0, 0); case 1: return this.GetRedElementIfNotToken(ref _child1); default: return null; } } internal override SyntaxNode? GetCachedSlot(int index) { switch (index) { case 0: return _child0; case 1: return _child1; default: 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; using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax { internal partial class SyntaxList { internal class WithTwoChildren : SyntaxList { private SyntaxNode? _child0; private SyntaxNode? _child1; internal WithTwoChildren(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) : base(green, parent, position) { } internal override SyntaxNode? GetNodeSlot(int index) { switch (index) { case 0: return this.GetRedElement(ref _child0, 0); case 1: return this.GetRedElementIfNotToken(ref _child1); default: return null; } } internal override SyntaxNode? GetCachedSlot(int index) { switch (index) { case 0: return _child0; case 1: return _child1; default: return null; } } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Compilation/MemberSemanticModel.NodeMapBuilder.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 Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class MemberSemanticModel { protected sealed class NodeMapBuilder : BoundTreeWalkerWithStackGuard { private NodeMapBuilder(OrderPreservingMultiDictionary<SyntaxNode, BoundNode> map, SyntaxTree tree, SyntaxNode thisSyntaxNodeOnly) { _map = map; _tree = tree; _thisSyntaxNodeOnly = thisSyntaxNodeOnly; } private readonly OrderPreservingMultiDictionary<SyntaxNode, BoundNode> _map; private readonly SyntaxTree _tree; private readonly SyntaxNode _thisSyntaxNodeOnly; /// <summary> /// Walks the bound tree and adds all non compiler generated bound nodes whose syntax matches the given one /// to the cache. /// </summary> /// <param name="root">The root of the bound tree.</param> /// <param name="map">The cache.</param> /// <param name="node">The syntax node where to add bound nodes for.</param> public static void AddToMap(BoundNode root, Dictionary<SyntaxNode, ImmutableArray<BoundNode>> map, SyntaxTree tree, SyntaxNode node = null) { Debug.Assert(node == null || root == null || !(root.Syntax is StatementSyntax), "individually added nodes are not supposed to be statements."); if (root == null || map.ContainsKey(root.Syntax)) { // root node is already in the map, children must be in the map too. return; } var additionMap = OrderPreservingMultiDictionary<SyntaxNode, BoundNode>.GetInstance(); var builder = new NodeMapBuilder(additionMap, tree, node); builder.Visit(root); foreach (CSharpSyntaxNode key in additionMap.Keys) { if (map.ContainsKey(key)) { #if DEBUG // It's possible that AddToMap was previously called with a subtree of root. If this is the case, // then we'll see an entry in the map. Since the incremental binder should also have seen the // pre-existing map entry, the entry in addition map should be identical. // Another, more unfortunate, possibility is that we've had to re-bind the syntax and the new bound // nodes are equivalent, but not identical, to the existing ones. In such cases, we prefer the // existing nodes so that the cache will always return the same bound node for a given syntax node. // EXAMPLE: Suppose we have the statement P.M(1); // First, we ask for semantic info about "P". We'll walk up to the statement level and bind that. // We'll end up with map entries for "1", "P", "P.M(1)", and "P.M(1);". // Next, we ask for semantic info about "P.M". That isn't in our map, so we walk up to the statement // level - again - and bind that - again. // Once again, we'll end up with map entries for "1", "P", "P.M(1)", and "P.M(1);". They will // have the same structure as the original map entries, but will not be ReferenceEquals. var existing = map[key]; var added = additionMap[key]; Debug.Assert(existing.Length == added.Length, "existing.Length == added.Length"); for (int i = 0; i < existing.Length; i++) { // TODO: it would be great if we could check !ReferenceEquals(existing[i], added[i]) (DevDiv #11584). // Known impediments include: // 1) Field initializers aren't cached because they're not in statements. // 2) Single local declarations (e.g. "int x = 1;" vs "int x = 1, y = 2;") aren't found in the cache // since nothing is cached for the statement syntax. if (existing[i].Kind != added[i].Kind) { Debug.Assert(!(key is StatementSyntax), "!(key is StatementSyntax)"); // This also seems to be happening when we get equivalent BoundTypeExpression and BoundTypeOrValueExpression nodes. if (existing[i].Kind == BoundKind.TypeExpression && added[i].Kind == BoundKind.TypeOrValueExpression) { Debug.Assert( TypeSymbol.Equals(((BoundTypeExpression)existing[i]).Type, ((BoundTypeOrValueExpression)added[i]).Type, TypeCompareKind.ConsiderEverything2), string.Format( System.Globalization.CultureInfo.InvariantCulture, "((BoundTypeExpression)existing[{0}]).Type == ((BoundTypeOrValueExpression)added[{0}]).Type", i)); } else if (existing[i].Kind == BoundKind.TypeOrValueExpression && added[i].Kind == BoundKind.TypeExpression) { Debug.Assert( TypeSymbol.Equals(((BoundTypeOrValueExpression)existing[i]).Type, ((BoundTypeExpression)added[i]).Type, TypeCompareKind.ConsiderEverything2), string.Format( System.Globalization.CultureInfo.InvariantCulture, "((BoundTypeOrValueExpression)existing[{0}]).Type == ((BoundTypeExpression)added[{0}]).Type", i)); } else { Debug.Assert(false, "New bound node does not match existing bound node"); } } else { Debug.Assert( (object)existing[i] == added[i] || !(key is StatementSyntax), string.Format( System.Globalization.CultureInfo.InvariantCulture, "(object)existing[{0}] == added[{0}] || !(key is StatementSyntax)", i)); } } #endif } else { map[key] = additionMap[key]; } } additionMap.Free(); } public override BoundNode Visit(BoundNode node) { // Do not cache bound nodes associated with a different syntax tree. We can get nodes like that // when semantic model binds complete simple program body. Semantic model is never asked about // information for nodes associated with a different syntax tree, therefore, there is no advantage // in putting the bound nodes in the map. SimpleProgramBodySemanticModelMergedBoundNodeCache facilitates // reuse of bound nodes from other trees. if (node == null || node.SyntaxTree != _tree) { return null; } BoundNode current = node; // It is possible that we will encounter a lambda in the bound tree that was never // turned into a bound lambda. For example, if you have something like: // // object x = (int y)=>M(y); // // then no conversion to a valid delegate type was performed and the "bound" tree // contains an "unbound" lambda with no body. Or, similarly, we could have something // like: // // M(x=>x.Blah()); // // and overload resolution failed to infer a unique type for x; perhaps it // inferred two types and neither return type was better. Or perhaps // there was a semantic error inside the lambda. // // In any of these cases there will be no bound lambda in the bound tree. // // Ultimately what we probably want to do here is ensure that this never happens; // we could run a post-processing pass on the bound tree, look for unbound lambdas, // and replace them with bound lambdas. However at this time that is a fairly complex // change and it is not clear where the most efficient place to put the rewriter is // in the IDE scenario. Until we figure that out, I'm going to detect that situation // here, when building the map. If we encounter an unbound lambda in the tree, // we'll just bind it right now. The unbound lambda will cache the result, and we'll // keep on trucking just as though there had been a bound lambda here all along. if (node.Kind == BoundKind.UnboundLambda) { current = ((UnboundLambda)node).BindForErrorRecovery(); } // It is possible for there to be multiple bound nodes with the same syntax tree, // and that is by design. For example, in // // byte b = 3; // // there is a bound node for the implicit conversion to byte and a bound node for the // literal, an int. Sometimes we want the inner one (to state the type of the expression) // and sometimes we want the "parent's" view of things (for extract method, for instance.) // // We want to add all bound nodes associated with the same syntax node to the cache, so we first add the // bound node, then we dive deeper into the bound tree. if (ShouldAddNode(current)) { _map.Add(current.Syntax, current); } // In machine-generated code we frequently end up with binary operator trees that are deep on the left, // such as a + b + c + d ... // To avoid blowing the call stack, we build an explicit stack to handle the left-hand recursion. var binOp = current as BoundBinaryOperator; if (binOp != null) { var stack = ArrayBuilder<BoundExpression>.GetInstance(); stack.Push(binOp.Right); current = binOp.Left; binOp = current as BoundBinaryOperator; while (binOp != null) { if (ShouldAddNode(binOp)) { _map.Add(binOp.Syntax, binOp); } stack.Push(binOp.Right); current = binOp.Left; binOp = current as BoundBinaryOperator; } Visit(current); while (stack.Count > 0) { Visit(stack.Pop()); } stack.Free(); } else { base.Visit(current); } return null; } /// <summary> /// Decides whether to the add the bound node to the cache or not. /// </summary> /// <param name="currentBoundNode">The bound node.</param> private bool ShouldAddNode(BoundNode currentBoundNode) { // Do not add compiler generated nodes. if (currentBoundNode.WasCompilerGenerated) { return false; } // Do not add if only a specific syntax node should be added. if (_thisSyntaxNodeOnly != null && currentBoundNode.Syntax != _thisSyntaxNodeOnly) { return false; } return true; } public override BoundNode VisitQueryClause(BoundQueryClause node) { this.Visit(node.Value); VisitUnoptimizedForm(node); return null; } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return null; } public override BoundNode VisitAwaitableInfo(BoundAwaitableInfo node) { return null; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { throw ExceptionUtilities.Unreachable; } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { 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.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class MemberSemanticModel { protected sealed class NodeMapBuilder : BoundTreeWalkerWithStackGuard { private NodeMapBuilder(OrderPreservingMultiDictionary<SyntaxNode, BoundNode> map, SyntaxTree tree, SyntaxNode thisSyntaxNodeOnly) { _map = map; _tree = tree; _thisSyntaxNodeOnly = thisSyntaxNodeOnly; } private readonly OrderPreservingMultiDictionary<SyntaxNode, BoundNode> _map; private readonly SyntaxTree _tree; private readonly SyntaxNode _thisSyntaxNodeOnly; /// <summary> /// Walks the bound tree and adds all non compiler generated bound nodes whose syntax matches the given one /// to the cache. /// </summary> /// <param name="root">The root of the bound tree.</param> /// <param name="map">The cache.</param> /// <param name="node">The syntax node where to add bound nodes for.</param> public static void AddToMap(BoundNode root, Dictionary<SyntaxNode, ImmutableArray<BoundNode>> map, SyntaxTree tree, SyntaxNode node = null) { Debug.Assert(node == null || root == null || !(root.Syntax is StatementSyntax), "individually added nodes are not supposed to be statements."); if (root == null || map.ContainsKey(root.Syntax)) { // root node is already in the map, children must be in the map too. return; } var additionMap = OrderPreservingMultiDictionary<SyntaxNode, BoundNode>.GetInstance(); var builder = new NodeMapBuilder(additionMap, tree, node); builder.Visit(root); foreach (CSharpSyntaxNode key in additionMap.Keys) { if (map.ContainsKey(key)) { #if DEBUG // It's possible that AddToMap was previously called with a subtree of root. If this is the case, // then we'll see an entry in the map. Since the incremental binder should also have seen the // pre-existing map entry, the entry in addition map should be identical. // Another, more unfortunate, possibility is that we've had to re-bind the syntax and the new bound // nodes are equivalent, but not identical, to the existing ones. In such cases, we prefer the // existing nodes so that the cache will always return the same bound node for a given syntax node. // EXAMPLE: Suppose we have the statement P.M(1); // First, we ask for semantic info about "P". We'll walk up to the statement level and bind that. // We'll end up with map entries for "1", "P", "P.M(1)", and "P.M(1);". // Next, we ask for semantic info about "P.M". That isn't in our map, so we walk up to the statement // level - again - and bind that - again. // Once again, we'll end up with map entries for "1", "P", "P.M(1)", and "P.M(1);". They will // have the same structure as the original map entries, but will not be ReferenceEquals. var existing = map[key]; var added = additionMap[key]; Debug.Assert(existing.Length == added.Length, "existing.Length == added.Length"); for (int i = 0; i < existing.Length; i++) { // TODO: it would be great if we could check !ReferenceEquals(existing[i], added[i]) (DevDiv #11584). // Known impediments include: // 1) Field initializers aren't cached because they're not in statements. // 2) Single local declarations (e.g. "int x = 1;" vs "int x = 1, y = 2;") aren't found in the cache // since nothing is cached for the statement syntax. if (existing[i].Kind != added[i].Kind) { Debug.Assert(!(key is StatementSyntax), "!(key is StatementSyntax)"); // This also seems to be happening when we get equivalent BoundTypeExpression and BoundTypeOrValueExpression nodes. if (existing[i].Kind == BoundKind.TypeExpression && added[i].Kind == BoundKind.TypeOrValueExpression) { Debug.Assert( TypeSymbol.Equals(((BoundTypeExpression)existing[i]).Type, ((BoundTypeOrValueExpression)added[i]).Type, TypeCompareKind.ConsiderEverything2), string.Format( System.Globalization.CultureInfo.InvariantCulture, "((BoundTypeExpression)existing[{0}]).Type == ((BoundTypeOrValueExpression)added[{0}]).Type", i)); } else if (existing[i].Kind == BoundKind.TypeOrValueExpression && added[i].Kind == BoundKind.TypeExpression) { Debug.Assert( TypeSymbol.Equals(((BoundTypeOrValueExpression)existing[i]).Type, ((BoundTypeExpression)added[i]).Type, TypeCompareKind.ConsiderEverything2), string.Format( System.Globalization.CultureInfo.InvariantCulture, "((BoundTypeOrValueExpression)existing[{0}]).Type == ((BoundTypeExpression)added[{0}]).Type", i)); } else { Debug.Assert(false, "New bound node does not match existing bound node"); } } else { Debug.Assert( (object)existing[i] == added[i] || !(key is StatementSyntax), string.Format( System.Globalization.CultureInfo.InvariantCulture, "(object)existing[{0}] == added[{0}] || !(key is StatementSyntax)", i)); } } #endif } else { map[key] = additionMap[key]; } } additionMap.Free(); } public override BoundNode Visit(BoundNode node) { // Do not cache bound nodes associated with a different syntax tree. We can get nodes like that // when semantic model binds complete simple program body. Semantic model is never asked about // information for nodes associated with a different syntax tree, therefore, there is no advantage // in putting the bound nodes in the map. SimpleProgramBodySemanticModelMergedBoundNodeCache facilitates // reuse of bound nodes from other trees. if (node == null || node.SyntaxTree != _tree) { return null; } BoundNode current = node; // It is possible that we will encounter a lambda in the bound tree that was never // turned into a bound lambda. For example, if you have something like: // // object x = (int y)=>M(y); // // then no conversion to a valid delegate type was performed and the "bound" tree // contains an "unbound" lambda with no body. Or, similarly, we could have something // like: // // M(x=>x.Blah()); // // and overload resolution failed to infer a unique type for x; perhaps it // inferred two types and neither return type was better. Or perhaps // there was a semantic error inside the lambda. // // In any of these cases there will be no bound lambda in the bound tree. // // Ultimately what we probably want to do here is ensure that this never happens; // we could run a post-processing pass on the bound tree, look for unbound lambdas, // and replace them with bound lambdas. However at this time that is a fairly complex // change and it is not clear where the most efficient place to put the rewriter is // in the IDE scenario. Until we figure that out, I'm going to detect that situation // here, when building the map. If we encounter an unbound lambda in the tree, // we'll just bind it right now. The unbound lambda will cache the result, and we'll // keep on trucking just as though there had been a bound lambda here all along. if (node.Kind == BoundKind.UnboundLambda) { current = ((UnboundLambda)node).BindForErrorRecovery(); } // It is possible for there to be multiple bound nodes with the same syntax tree, // and that is by design. For example, in // // byte b = 3; // // there is a bound node for the implicit conversion to byte and a bound node for the // literal, an int. Sometimes we want the inner one (to state the type of the expression) // and sometimes we want the "parent's" view of things (for extract method, for instance.) // // We want to add all bound nodes associated with the same syntax node to the cache, so we first add the // bound node, then we dive deeper into the bound tree. if (ShouldAddNode(current)) { _map.Add(current.Syntax, current); } // In machine-generated code we frequently end up with binary operator trees that are deep on the left, // such as a + b + c + d ... // To avoid blowing the call stack, we build an explicit stack to handle the left-hand recursion. var binOp = current as BoundBinaryOperator; if (binOp != null) { var stack = ArrayBuilder<BoundExpression>.GetInstance(); stack.Push(binOp.Right); current = binOp.Left; binOp = current as BoundBinaryOperator; while (binOp != null) { if (ShouldAddNode(binOp)) { _map.Add(binOp.Syntax, binOp); } stack.Push(binOp.Right); current = binOp.Left; binOp = current as BoundBinaryOperator; } Visit(current); while (stack.Count > 0) { Visit(stack.Pop()); } stack.Free(); } else { base.Visit(current); } return null; } /// <summary> /// Decides whether to the add the bound node to the cache or not. /// </summary> /// <param name="currentBoundNode">The bound node.</param> private bool ShouldAddNode(BoundNode currentBoundNode) { // Do not add compiler generated nodes. if (currentBoundNode.WasCompilerGenerated) { return false; } // Do not add if only a specific syntax node should be added. if (_thisSyntaxNodeOnly != null && currentBoundNode.Syntax != _thisSyntaxNodeOnly) { return false; } return true; } public override BoundNode VisitQueryClause(BoundQueryClause node) { this.Visit(node.Value); VisitUnoptimizedForm(node); return null; } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return null; } public override BoundNode VisitAwaitableInfo(BoundAwaitableInfo node) { return null; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { throw ExceptionUtilities.Unreachable; } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return false; } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/PublicModel/MethodSymbol.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 System.Reflection.Metadata; using System.Threading; using Microsoft.Cci; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class MethodSymbol : Symbol, IMethodSymbol { private readonly Symbols.MethodSymbol _underlying; private ITypeSymbol _lazyReturnType; private ImmutableArray<ITypeSymbol> _lazyTypeArguments; private ITypeSymbol _lazyReceiverType; public MethodSymbol(Symbols.MethodSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; internal Symbols.MethodSymbol UnderlyingMethodSymbol => _underlying; MethodKind IMethodSymbol.MethodKind { get { switch (_underlying.MethodKind) { case MethodKind.AnonymousFunction: return MethodKind.AnonymousFunction; case MethodKind.Constructor: return MethodKind.Constructor; case MethodKind.Conversion: return MethodKind.Conversion; case MethodKind.DelegateInvoke: return MethodKind.DelegateInvoke; case MethodKind.Destructor: return MethodKind.Destructor; case MethodKind.EventAdd: return MethodKind.EventAdd; case MethodKind.EventRemove: return MethodKind.EventRemove; case MethodKind.ExplicitInterfaceImplementation: return MethodKind.ExplicitInterfaceImplementation; case MethodKind.UserDefinedOperator: return MethodKind.UserDefinedOperator; case MethodKind.BuiltinOperator: return MethodKind.BuiltinOperator; case MethodKind.Ordinary: return MethodKind.Ordinary; case MethodKind.PropertyGet: return MethodKind.PropertyGet; case MethodKind.PropertySet: return MethodKind.PropertySet; case MethodKind.ReducedExtension: return MethodKind.ReducedExtension; case MethodKind.StaticConstructor: return MethodKind.StaticConstructor; case MethodKind.LocalFunction: return MethodKind.LocalFunction; case MethodKind.FunctionPointerSignature: return MethodKind.FunctionPointerSignature; default: throw ExceptionUtilities.UnexpectedValue(_underlying.MethodKind); } } } ITypeSymbol IMethodSymbol.ReturnType { get { if (_lazyReturnType is null) { Interlocked.CompareExchange(ref _lazyReturnType, _underlying.ReturnTypeWithAnnotations.GetPublicSymbol(), null); } return _lazyReturnType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReturnNullableAnnotation { get { return _underlying.ReturnTypeWithAnnotations.ToPublicAnnotation(); } } ImmutableArray<ITypeSymbol> IMethodSymbol.TypeArguments { get { if (_lazyTypeArguments.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeArguments, _underlying.TypeArgumentsWithAnnotations.GetPublicSymbols(), default); } return _lazyTypeArguments; } } ImmutableArray<CodeAnalysis.NullableAnnotation> IMethodSymbol.TypeArgumentNullableAnnotations => _underlying.TypeArgumentsWithAnnotations.ToPublicAnnotations(); ImmutableArray<ITypeParameterSymbol> IMethodSymbol.TypeParameters { get { return _underlying.TypeParameters.GetPublicSymbols(); } } ImmutableArray<IParameterSymbol> IMethodSymbol.Parameters { get { return _underlying.Parameters.GetPublicSymbols(); } } IMethodSymbol IMethodSymbol.ConstructedFrom { get { return _underlying.ConstructedFrom.GetPublicSymbol(); } } bool IMethodSymbol.IsReadOnly { get { return _underlying.IsEffectivelyReadOnly; } } bool IMethodSymbol.IsInitOnly { get { return _underlying.IsInitOnly; } } IMethodSymbol IMethodSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.OverriddenMethod { get { return _underlying.OverriddenMethod.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.ReceiverType { get { if (_lazyReceiverType is null) { Interlocked.CompareExchange(ref _lazyReceiverType, _underlying.ReceiverType?.GetITypeSymbol(_underlying.ReceiverNullableAnnotation), null); } return _lazyReceiverType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReceiverNullableAnnotation => _underlying.ReceiverNullableAnnotation; IMethodSymbol IMethodSymbol.ReducedFrom { get { return _underlying.ReducedFrom.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { return _underlying.GetTypeInferredDuringReduction( reducedFromTypeParameter.EnsureCSharpSymbolOrNull(nameof(reducedFromTypeParameter))). GetPublicSymbol(); } IMethodSymbol IMethodSymbol.ReduceExtensionMethod(ITypeSymbol receiverType) { return _underlying.ReduceExtensionMethod( receiverType.EnsureCSharpSymbolOrNull(nameof(receiverType)), compilation: null). GetPublicSymbol(); } ImmutableArray<IMethodSymbol> IMethodSymbol.ExplicitInterfaceImplementations { get { return _underlying.ExplicitInterfaceImplementations.GetPublicSymbols(); } } ISymbol IMethodSymbol.AssociatedSymbol { get { return _underlying.AssociatedSymbol.GetPublicSymbol(); } } bool IMethodSymbol.IsGenericMethod { get { return _underlying.IsGenericMethod; } } bool IMethodSymbol.IsAsync { get { return _underlying.IsAsync; } } bool IMethodSymbol.HidesBaseMethodsByName { get { return _underlying.HidesBaseMethodsByName; } } ImmutableArray<CustomModifier> IMethodSymbol.ReturnTypeCustomModifiers { get { return _underlying.ReturnTypeWithAnnotations.CustomModifiers; } } ImmutableArray<CustomModifier> IMethodSymbol.RefCustomModifiers { get { return _underlying.RefCustomModifiers; } } ImmutableArray<AttributeData> IMethodSymbol.GetReturnTypeAttributes() { return _underlying.GetReturnTypeAttributes().Cast<CSharpAttributeData, AttributeData>(); } SignatureCallingConvention IMethodSymbol.CallingConvention => _underlying.CallingConvention.ToSignatureConvention(); ImmutableArray<INamedTypeSymbol> IMethodSymbol.UnmanagedCallingConventionTypes => _underlying.UnmanagedCallingConventionTypes.SelectAsArray(t => t.GetPublicSymbol()); IMethodSymbol IMethodSymbol.Construct(params ITypeSymbol[] typeArguments) { return _underlying.Construct(ConstructTypeArguments(typeArguments)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations) { return _underlying.Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.PartialImplementationPart { get { return _underlying.PartialImplementationPart.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.PartialDefinitionPart { get { return _underlying.PartialDefinitionPart.GetPublicSymbol(); } } bool IMethodSymbol.IsPartialDefinition => _underlying.IsPartialDefinition(); INamedTypeSymbol IMethodSymbol.AssociatedAnonymousDelegate { get { return null; } } int IMethodSymbol.Arity => _underlying.Arity; bool IMethodSymbol.IsExtensionMethod => _underlying.IsExtensionMethod; System.Reflection.MethodImplAttributes IMethodSymbol.MethodImplementationFlags => _underlying.ImplementationAttributes; bool IMethodSymbol.IsVararg => _underlying.IsVararg; bool IMethodSymbol.IsCheckedBuiltin => _underlying.IsCheckedBuiltin; bool IMethodSymbol.ReturnsVoid => _underlying.ReturnsVoid; bool IMethodSymbol.ReturnsByRef => _underlying.ReturnsByRef; bool IMethodSymbol.ReturnsByRefReadonly => _underlying.ReturnsByRefReadonly; RefKind IMethodSymbol.RefKind => _underlying.RefKind; bool IMethodSymbol.IsConditional => _underlying.IsConditional; DllImportData IMethodSymbol.GetDllImportData() => _underlying.GetDllImportData(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitMethod(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitMethod(this); } #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.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Threading; using Microsoft.Cci; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class MethodSymbol : Symbol, IMethodSymbol { private readonly Symbols.MethodSymbol _underlying; private ITypeSymbol _lazyReturnType; private ImmutableArray<ITypeSymbol> _lazyTypeArguments; private ITypeSymbol _lazyReceiverType; public MethodSymbol(Symbols.MethodSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; internal Symbols.MethodSymbol UnderlyingMethodSymbol => _underlying; MethodKind IMethodSymbol.MethodKind { get { switch (_underlying.MethodKind) { case MethodKind.AnonymousFunction: return MethodKind.AnonymousFunction; case MethodKind.Constructor: return MethodKind.Constructor; case MethodKind.Conversion: return MethodKind.Conversion; case MethodKind.DelegateInvoke: return MethodKind.DelegateInvoke; case MethodKind.Destructor: return MethodKind.Destructor; case MethodKind.EventAdd: return MethodKind.EventAdd; case MethodKind.EventRemove: return MethodKind.EventRemove; case MethodKind.ExplicitInterfaceImplementation: return MethodKind.ExplicitInterfaceImplementation; case MethodKind.UserDefinedOperator: return MethodKind.UserDefinedOperator; case MethodKind.BuiltinOperator: return MethodKind.BuiltinOperator; case MethodKind.Ordinary: return MethodKind.Ordinary; case MethodKind.PropertyGet: return MethodKind.PropertyGet; case MethodKind.PropertySet: return MethodKind.PropertySet; case MethodKind.ReducedExtension: return MethodKind.ReducedExtension; case MethodKind.StaticConstructor: return MethodKind.StaticConstructor; case MethodKind.LocalFunction: return MethodKind.LocalFunction; case MethodKind.FunctionPointerSignature: return MethodKind.FunctionPointerSignature; default: throw ExceptionUtilities.UnexpectedValue(_underlying.MethodKind); } } } ITypeSymbol IMethodSymbol.ReturnType { get { if (_lazyReturnType is null) { Interlocked.CompareExchange(ref _lazyReturnType, _underlying.ReturnTypeWithAnnotations.GetPublicSymbol(), null); } return _lazyReturnType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReturnNullableAnnotation { get { return _underlying.ReturnTypeWithAnnotations.ToPublicAnnotation(); } } ImmutableArray<ITypeSymbol> IMethodSymbol.TypeArguments { get { if (_lazyTypeArguments.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeArguments, _underlying.TypeArgumentsWithAnnotations.GetPublicSymbols(), default); } return _lazyTypeArguments; } } ImmutableArray<CodeAnalysis.NullableAnnotation> IMethodSymbol.TypeArgumentNullableAnnotations => _underlying.TypeArgumentsWithAnnotations.ToPublicAnnotations(); ImmutableArray<ITypeParameterSymbol> IMethodSymbol.TypeParameters { get { return _underlying.TypeParameters.GetPublicSymbols(); } } ImmutableArray<IParameterSymbol> IMethodSymbol.Parameters { get { return _underlying.Parameters.GetPublicSymbols(); } } IMethodSymbol IMethodSymbol.ConstructedFrom { get { return _underlying.ConstructedFrom.GetPublicSymbol(); } } bool IMethodSymbol.IsReadOnly { get { return _underlying.IsEffectivelyReadOnly; } } bool IMethodSymbol.IsInitOnly { get { return _underlying.IsInitOnly; } } IMethodSymbol IMethodSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.OverriddenMethod { get { return _underlying.OverriddenMethod.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.ReceiverType { get { if (_lazyReceiverType is null) { Interlocked.CompareExchange(ref _lazyReceiverType, _underlying.ReceiverType?.GetITypeSymbol(_underlying.ReceiverNullableAnnotation), null); } return _lazyReceiverType; } } CodeAnalysis.NullableAnnotation IMethodSymbol.ReceiverNullableAnnotation => _underlying.ReceiverNullableAnnotation; IMethodSymbol IMethodSymbol.ReducedFrom { get { return _underlying.ReducedFrom.GetPublicSymbol(); } } ITypeSymbol IMethodSymbol.GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { return _underlying.GetTypeInferredDuringReduction( reducedFromTypeParameter.EnsureCSharpSymbolOrNull(nameof(reducedFromTypeParameter))). GetPublicSymbol(); } IMethodSymbol IMethodSymbol.ReduceExtensionMethod(ITypeSymbol receiverType) { return _underlying.ReduceExtensionMethod( receiverType.EnsureCSharpSymbolOrNull(nameof(receiverType)), compilation: null). GetPublicSymbol(); } ImmutableArray<IMethodSymbol> IMethodSymbol.ExplicitInterfaceImplementations { get { return _underlying.ExplicitInterfaceImplementations.GetPublicSymbols(); } } ISymbol IMethodSymbol.AssociatedSymbol { get { return _underlying.AssociatedSymbol.GetPublicSymbol(); } } bool IMethodSymbol.IsGenericMethod { get { return _underlying.IsGenericMethod; } } bool IMethodSymbol.IsAsync { get { return _underlying.IsAsync; } } bool IMethodSymbol.HidesBaseMethodsByName { get { return _underlying.HidesBaseMethodsByName; } } ImmutableArray<CustomModifier> IMethodSymbol.ReturnTypeCustomModifiers { get { return _underlying.ReturnTypeWithAnnotations.CustomModifiers; } } ImmutableArray<CustomModifier> IMethodSymbol.RefCustomModifiers { get { return _underlying.RefCustomModifiers; } } ImmutableArray<AttributeData> IMethodSymbol.GetReturnTypeAttributes() { return _underlying.GetReturnTypeAttributes().Cast<CSharpAttributeData, AttributeData>(); } SignatureCallingConvention IMethodSymbol.CallingConvention => _underlying.CallingConvention.ToSignatureConvention(); ImmutableArray<INamedTypeSymbol> IMethodSymbol.UnmanagedCallingConventionTypes => _underlying.UnmanagedCallingConventionTypes.SelectAsArray(t => t.GetPublicSymbol()); IMethodSymbol IMethodSymbol.Construct(params ITypeSymbol[] typeArguments) { return _underlying.Construct(ConstructTypeArguments(typeArguments)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations) { return _underlying.Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations)).GetPublicSymbol(); } IMethodSymbol IMethodSymbol.PartialImplementationPart { get { return _underlying.PartialImplementationPart.GetPublicSymbol(); } } IMethodSymbol IMethodSymbol.PartialDefinitionPart { get { return _underlying.PartialDefinitionPart.GetPublicSymbol(); } } bool IMethodSymbol.IsPartialDefinition => _underlying.IsPartialDefinition(); INamedTypeSymbol IMethodSymbol.AssociatedAnonymousDelegate { get { return null; } } int IMethodSymbol.Arity => _underlying.Arity; bool IMethodSymbol.IsExtensionMethod => _underlying.IsExtensionMethod; System.Reflection.MethodImplAttributes IMethodSymbol.MethodImplementationFlags => _underlying.ImplementationAttributes; bool IMethodSymbol.IsVararg => _underlying.IsVararg; bool IMethodSymbol.IsCheckedBuiltin => _underlying.IsCheckedBuiltin; bool IMethodSymbol.ReturnsVoid => _underlying.ReturnsVoid; bool IMethodSymbol.ReturnsByRef => _underlying.ReturnsByRef; bool IMethodSymbol.ReturnsByRefReadonly => _underlying.ReturnsByRefReadonly; RefKind IMethodSymbol.RefKind => _underlying.RefKind; bool IMethodSymbol.IsConditional => _underlying.IsConditional; DllImportData IMethodSymbol.GetDllImportData() => _underlying.GetDllImportData(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitMethod(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitMethod(this); } #endregion } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpParenthesizedExpressionReducer.Rewriter.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.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpParenthesizedExpressionReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { } public override SyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { return SimplifyExpression( node, newNode: base.VisitParenthesizedExpression(node), simplifier: s_simplifyParentheses); } } } }
// 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.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpParenthesizedExpressionReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { } public override SyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { return SimplifyExpression( node, newNode: base.VisitParenthesizedExpression(node), simplifier: s_simplifyParentheses); } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/CSharpTest/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ReplaceDefaultLiteral; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReplaceDefaultLiteral { [Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDefaultLiteral)] public sealed class ReplaceDefaultLiteralTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ReplaceDefaultLiteralTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpReplaceDefaultLiteralCodeFixProvider()); private static readonly ImmutableArray<LanguageVersion> s_csharp7_1above = ImmutableArray.Create( LanguageVersion.CSharp7_1, LanguageVersion.Latest); private static readonly ImmutableArray<LanguageVersion> s_csharp7below = ImmutableArray.Create( LanguageVersion.CSharp7, LanguageVersion.CSharp6, LanguageVersion.CSharp5, LanguageVersion.CSharp4, LanguageVersion.CSharp3, LanguageVersion.CSharp2, LanguageVersion.CSharp1); private async Task TestWithLanguageVersionsAsync(string initialMarkup, string expectedMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(version)); } } private async Task TestMissingWithLanguageVersionsAsync(string initialMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); } } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default: } } }", @"class C { void M() { switch (1) { case 0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default): } } }", @"class C { void M() { switch (1) { case (0): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)): } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default when true: } } }", @"class C { void M() { switch (1) { case 0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default) when true: } } }", @"class C { void M() { switch (1) { case (0) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default when true: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default when true: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)) when true: } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default when true: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default) { } } }", @"class C { void M() { if (true is false) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is ([||]default)) { } } }", @"class C { void M() { if (true is (false)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is (bool)[||]default) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default(bool)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnFalseLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]false) { } } }", s_csharp7_1above); } [Theory] [InlineData("int", "0")] [InlineData("uint", "0U")] [InlineData("byte", "0")] [InlineData("sbyte", "0")] [InlineData("short", "0")] [InlineData("ushort", "0")] [InlineData("long", "0L")] [InlineData("ulong", "0UL")] [InlineData("float", "0F")] [InlineData("double", "0D")] [InlineData("decimal", "0M")] [InlineData("char", "'\\0'")] [InlineData("string", "null")] [InlineData("object", "null")] public async Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral) { await TestWithLanguageVersionsAsync( $@"class C {{ void M({type} value) {{ if (value is [||]default) {{ }} }} }}", $@"class C {{ void M({type} value) {{ if (value is {expectedLiteral}) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is [||]default) { } } }", @"class C { void M() { if (System.DateTime.Now is default(System.DateTime)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if ((0, true) is [||]default) { } } }", @"class C { void M() { if ((0, true) is default((int, bool))) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Type { }")] [InlineData("interface Type { }")] [InlineData("delegate void Type();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is null) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("enum Enum { }")] [InlineData("enum Enum { None = 0 }")] [InlineData("[Flags] enum Enum { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = 1 }")] [InlineData("[System.Flags] enum Enum { None = 1, None = 0 }")] [InlineData("[System.Flags] enum Enum { Some = 0 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithoutSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is 0) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("[System.Flags] enum Enum : int { None = 0 }")] [InlineData("[System.Flags] enum Enum : uint { None = 0 }")] [InlineData("[System.Flags] enum Enum : byte { None = 0 }")] [InlineData("[System.Flags] enum Enum : sbyte { None = 0 }")] [InlineData("[System.Flags] enum Enum : short { None = 0 }")] [InlineData("[System.Flags] enum Enum : ushort { None = 0 }")] [InlineData("[System.Flags] enum Enum : long { None = 0 }")] [InlineData("[System.Flags] enum Enum : ulong { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = default }")] [InlineData("[System.Flags] enum Enum { Some = 1, None = 0 }")] [InlineData("[System.FlagsAttribute] enum Enum { None = 0, Some = 1 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is Enum.None) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_CustomStruct() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { struct Struct { } void M() { if (new Struct() is [||]default) { } } }", @"class C { struct Struct { } void M() { if (new Struct() is default(Struct)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_AnonymousType() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (new { a = 0 } is [||]default) { } } }", @"class C { void M() { if (new { a = 0 } is null) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Container<T> { }")] [InlineData("interface Container<T> { }")] [InlineData("delegate void Container<T>();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceTypeOfAnonymousType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is null) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForCustomStructOfAnonymousType() { await TestMissingWithLanguageVersionsAsync( @"class C { struct Container<T> { } Container<T> ToContainer<T>(T value) => new Container<T>(); void M() { if (ToContainer(new { x = 0 }) is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({@namespace}.{type}) is [||]default) {{ }} }} }}", $@"class C {{ void M() {{ if (default({@namespace}.{type}) is {@namespace}.{type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is {type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("CancellationToken")] [InlineData("IntPtr")] [InlineData("UIntPtr")] public async Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType1() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var value; if (value is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ var value = {expression}; if (value is [||]default) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if ({expression} is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Lambda() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var value = () => { }; if (value is [||]default) { } } }", ImmutableArray.Create(LanguageVersion.CSharp7_1)); } [Fact] public async Task TestCSharpLatest_InIsPattern_Lambda() { await TestWithLanguageVersionsAsync( @"class C { void M() { var value = () => { }; if (value is [||]default) { } } }", @"class C { void M() { var value = () => { }; if (value is null) { } } }", ImmutableArray.Create(LanguageVersion.Latest)); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (true is /*a*/ false /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (System.DateTime.Now is /*a*/ default(System.DateTime) /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression_InvalidType() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var v = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7Lower_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7below); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ReplaceDefaultLiteral; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReplaceDefaultLiteral { [Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDefaultLiteral)] public sealed class ReplaceDefaultLiteralTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ReplaceDefaultLiteralTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpReplaceDefaultLiteralCodeFixProvider()); private static readonly ImmutableArray<LanguageVersion> s_csharp7_1above = ImmutableArray.Create( LanguageVersion.CSharp7_1, LanguageVersion.Latest); private static readonly ImmutableArray<LanguageVersion> s_csharp7below = ImmutableArray.Create( LanguageVersion.CSharp7, LanguageVersion.CSharp6, LanguageVersion.CSharp5, LanguageVersion.CSharp4, LanguageVersion.CSharp3, LanguageVersion.CSharp2, LanguageVersion.CSharp1); private async Task TestWithLanguageVersionsAsync(string initialMarkup, string expectedMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(version)); } } private async Task TestMissingWithLanguageVersionsAsync(string initialMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); } } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default: } } }", @"class C { void M() { switch (1) { case 0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default): } } }", @"class C { void M() { switch (1) { case (0): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)): } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default when true: } } }", @"class C { void M() { switch (1) { case 0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default) when true: } } }", @"class C { void M() { switch (1) { case (0) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default when true: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default when true: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)) when true: } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default when true: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default) { } } }", @"class C { void M() { if (true is false) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is ([||]default)) { } } }", @"class C { void M() { if (true is (false)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is (bool)[||]default) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default(bool)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnFalseLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]false) { } } }", s_csharp7_1above); } [Theory] [InlineData("int", "0")] [InlineData("uint", "0U")] [InlineData("byte", "0")] [InlineData("sbyte", "0")] [InlineData("short", "0")] [InlineData("ushort", "0")] [InlineData("long", "0L")] [InlineData("ulong", "0UL")] [InlineData("float", "0F")] [InlineData("double", "0D")] [InlineData("decimal", "0M")] [InlineData("char", "'\\0'")] [InlineData("string", "null")] [InlineData("object", "null")] public async Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral) { await TestWithLanguageVersionsAsync( $@"class C {{ void M({type} value) {{ if (value is [||]default) {{ }} }} }}", $@"class C {{ void M({type} value) {{ if (value is {expectedLiteral}) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is [||]default) { } } }", @"class C { void M() { if (System.DateTime.Now is default(System.DateTime)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if ((0, true) is [||]default) { } } }", @"class C { void M() { if ((0, true) is default((int, bool))) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Type { }")] [InlineData("interface Type { }")] [InlineData("delegate void Type();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is null) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("enum Enum { }")] [InlineData("enum Enum { None = 0 }")] [InlineData("[Flags] enum Enum { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = 1 }")] [InlineData("[System.Flags] enum Enum { None = 1, None = 0 }")] [InlineData("[System.Flags] enum Enum { Some = 0 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithoutSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is 0) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("[System.Flags] enum Enum : int { None = 0 }")] [InlineData("[System.Flags] enum Enum : uint { None = 0 }")] [InlineData("[System.Flags] enum Enum : byte { None = 0 }")] [InlineData("[System.Flags] enum Enum : sbyte { None = 0 }")] [InlineData("[System.Flags] enum Enum : short { None = 0 }")] [InlineData("[System.Flags] enum Enum : ushort { None = 0 }")] [InlineData("[System.Flags] enum Enum : long { None = 0 }")] [InlineData("[System.Flags] enum Enum : ulong { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = default }")] [InlineData("[System.Flags] enum Enum { Some = 1, None = 0 }")] [InlineData("[System.FlagsAttribute] enum Enum { None = 0, Some = 1 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is Enum.None) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_CustomStruct() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { struct Struct { } void M() { if (new Struct() is [||]default) { } } }", @"class C { struct Struct { } void M() { if (new Struct() is default(Struct)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_AnonymousType() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (new { a = 0 } is [||]default) { } } }", @"class C { void M() { if (new { a = 0 } is null) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Container<T> { }")] [InlineData("interface Container<T> { }")] [InlineData("delegate void Container<T>();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceTypeOfAnonymousType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is null) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForCustomStructOfAnonymousType() { await TestMissingWithLanguageVersionsAsync( @"class C { struct Container<T> { } Container<T> ToContainer<T>(T value) => new Container<T>(); void M() { if (ToContainer(new { x = 0 }) is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({@namespace}.{type}) is [||]default) {{ }} }} }}", $@"class C {{ void M() {{ if (default({@namespace}.{type}) is {@namespace}.{type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is {type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("CancellationToken")] [InlineData("IntPtr")] [InlineData("UIntPtr")] public async Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType1() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var value; if (value is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ var value = {expression}; if (value is [||]default) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if ({expression} is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Lambda() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var value = () => { }; if (value is [||]default) { } } }", ImmutableArray.Create(LanguageVersion.CSharp7_1)); } [Fact] public async Task TestCSharpLatest_InIsPattern_Lambda() { await TestWithLanguageVersionsAsync( @"class C { void M() { var value = () => { }; if (value is [||]default) { } } }", @"class C { void M() { var value = () => { }; if (value is null) { } } }", ImmutableArray.Create(LanguageVersion.Latest)); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (true is /*a*/ false /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (System.DateTime.Now is /*a*/ default(System.DateTime) /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression_InvalidType() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var v = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7Lower_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7below); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Core/Portable/InternalUtilities/OrderedMultiDictionary.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; using System.Collections.Generic; namespace Roslyn.Utilities { // Note that this is not threadsafe for concurrent reading and writing. internal sealed class OrderedMultiDictionary<K, V> : IEnumerable<KeyValuePair<K, SetWithInsertionOrder<V>>> where K : notnull { private readonly Dictionary<K, SetWithInsertionOrder<V>> _dictionary; private readonly List<K> _keys; public int Count => _dictionary.Count; public IEnumerable<K> Keys => _keys; // Returns an empty set if there is no such key in the dictionary. public SetWithInsertionOrder<V> this[K k] { get { SetWithInsertionOrder<V>? set; return _dictionary.TryGetValue(k, out set) ? set : new SetWithInsertionOrder<V>(); } } public OrderedMultiDictionary() { _dictionary = new Dictionary<K, SetWithInsertionOrder<V>>(); _keys = new List<K>(); } public void Add(K k, V v) { SetWithInsertionOrder<V>? set; if (!_dictionary.TryGetValue(k, out set)) { _keys.Add(k); set = new SetWithInsertionOrder<V>(); } set.Add(v); _dictionary[k] = set; } public void AddRange(K k, IEnumerable<V> values) { foreach (var v in values) { Add(k, v); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<KeyValuePair<K, SetWithInsertionOrder<V>>> GetEnumerator() { foreach (var key in _keys) { yield return new KeyValuePair<K, SetWithInsertionOrder<V>>( key, _dictionary[key]); } } } }
// 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; using System.Collections.Generic; namespace Roslyn.Utilities { // Note that this is not threadsafe for concurrent reading and writing. internal sealed class OrderedMultiDictionary<K, V> : IEnumerable<KeyValuePair<K, SetWithInsertionOrder<V>>> where K : notnull { private readonly Dictionary<K, SetWithInsertionOrder<V>> _dictionary; private readonly List<K> _keys; public int Count => _dictionary.Count; public IEnumerable<K> Keys => _keys; // Returns an empty set if there is no such key in the dictionary. public SetWithInsertionOrder<V> this[K k] { get { SetWithInsertionOrder<V>? set; return _dictionary.TryGetValue(k, out set) ? set : new SetWithInsertionOrder<V>(); } } public OrderedMultiDictionary() { _dictionary = new Dictionary<K, SetWithInsertionOrder<V>>(); _keys = new List<K>(); } public void Add(K k, V v) { SetWithInsertionOrder<V>? set; if (!_dictionary.TryGetValue(k, out set)) { _keys.Add(k); set = new SetWithInsertionOrder<V>(); } set.Add(v); _dictionary[k] = set; } public void AddRange(K k, IEnumerable<V> values) { foreach (var v in values) { Add(k, v); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<KeyValuePair<K, SetWithInsertionOrder<V>>> GetEnumerator() { foreach (var key in _keys) { yield return new KeyValuePair<K, SetWithInsertionOrder<V>>( key, _dictionary[key]); } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateType { [ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared] internal class CSharpGenerateTypeService : AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateTypeService() { } protected override string DefaultFileExtension => ".cs"; protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName) => simpleName.GetLeftSideOfDot(); protected override bool IsInCatchDeclaration(ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.CatchDeclaration); protected override bool IsArrayElementType(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.ArrayType) && expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression); } protected override bool IsInValueTypeConstraintContext( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList, out TypeArgumentListSyntax typeArgumentList)) { var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken); var symbol = symbolInfo.GetAnySymbol(); if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression); if (symbol is INamedTypeSymbol type) { type = type.OriginalDefinition; var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } if (symbol is IMethodSymbol method) { method = method.OriginalDefinition; var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } } return false; } protected override bool IsInInterfaceList(ExpressionSyntax expression) { if (expression is TypeSyntax && expression.Parent is BaseTypeSyntax baseType && baseType.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax baseList) && baseType.Type == expression) { // If it's after the first item, then it's definitely an interface. if (baseList.Types[0] != expression.Parent) { return true; } // If it's in the base list of an interface or struct, then it's definitely an // interface. return baseList.IsParentKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration); } if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax typeConstraint) && typeConstraint.IsParentKind(SyntaxKind.TypeParameterConstraintClause, out TypeParameterConstraintClauseSyntax constraintClause)) { var index = constraintClause.Constraints.IndexOf(typeConstraint); // If it's after the first item, then it's definitely an interface. return index > 0; } return false; } protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts) { return expression.TryGetNameParts(out nameParts); } protected override bool TryInitializeState( SemanticDocument document, SimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions) { generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions(); if (simpleName.IsVar) { return false; } if (SyntaxFacts.IsAliasQualifier(simpleName)) { return false; } // Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly // unlikely that this would be a location where a user would be wanting to generate // something. They're really just trying to reference something that exists but // isn't available for some reason (i.e. a missing reference). var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword) { return false; } ExpressionSyntax nameOrMemberAccessExpression = null; if (simpleName.IsRightSideOfDot()) { // This simplename comes from the cref if (simpleName.IsParentKind(SyntaxKind.NameMemberCref)) { return false; } nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent; // If we're on the right side of a dot, then the left side better be a name (and // not an arbitrary expression). var leftSideExpression = simpleName.GetLeftSideOfDot(); if (!leftSideExpression.IsKind( SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.AliasQualifiedName, SyntaxKind.GenericName, SyntaxKind.SimpleMemberAccessExpression)) { return false; } } else { nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName; } // BUG(5712): Don't offer generate type in an enum's base list. if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax && nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression && nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration)) { return false; } // If we can guarantee it's a type only context, great. Otherwise, we may not want to // provide this here. var semanticModel = document.SemanticModel; if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { // Don't offer Generate Type in an expression context *unless* we're on the left // side of a dot. In that case the user might be making a type that they're // accessing a static off of. var syntaxTree = semanticModel.SyntaxTree; var start = nameOrMemberAccessExpression.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel); var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken); var isExpressionOrStatementContext = isExpressionContext || isStatementContext; // Delegate Type Creation is not allowed in Non Type Namespace Context generateTypeServiceStateOptions.IsDelegateAllowed = false; if (!isExpressionOrStatementContext) { return false; } if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOfExpression(semanticModel, cancellationToken)) { if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot()) { return false; } var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol; var token = simpleName.GetLastToken().GetNextToken(); // We let only the Namespace to be left of the Dot if (leftSymbol == null || !leftSymbol.IsKind(SymbolKind.Namespace) || !token.IsKind(SyntaxKind.DotToken)) { return false; } else { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } // Global Namespace if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess && !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName)) { var token = simpleName.GetLastToken().GetNextToken(); if (token.IsKind(SyntaxKind.DotToken) && simpleName.Parent == token.Parent) { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } } var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null && fieldDeclaration.Parent is CompilationUnitSyntax && document.Document.SourceCodeKind == SourceCodeKind.Regular) { return false; } // Check to see if Module could be an option in the Type Generation in Cross Language Generation var nextToken = simpleName.GetLastToken().GetNextToken(); if (simpleName.IsLeftSideOfDot() || nextToken.IsKind(SyntaxKind.DotToken)) { if (simpleName.IsRightSideOfDot()) { if (simpleName.Parent is QualifiedNameSyntax parent) { var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol; if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace)) { generateTypeServiceStateOptions.IsMembersWithModule = true; } } } } if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { if (nextToken.IsKind(SyntaxKind.DotToken)) { // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName generateTypeServiceStateOptions.IsDelegateAllowed = false; generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; generateTypeServiceStateOptions.IsMembersWithModule = true; } // case: class Goo<T> where T: MyType if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any()) { generateTypeServiceStateOptions.IsClassInterfaceTypes = true; return true; } // Events if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() || nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any()) { // Case : event goo name11 // Only Delegate if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax)) { generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } // Case : event SomeSymbol.goo name11 if (nameOrMemberAccessExpression is QualifiedNameSyntax) { // Only Namespace, Class, Struct and Module are allowed to contain Delegate // Case : event Something.Mytype.<Delegate> Identifier if (nextToken.IsKind(SyntaxKind.DotToken)) { if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax) { return true; } throw ExceptionUtilities.Unreachable; } else { // Case : event Something.<Delegate> Identifier generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } } } } else { // MemberAccessExpression if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) && nameOrMemberAccessExpression.IsLeftSideOfDot()) { // Check to see if the expression is part of Invocation Expression ExpressionSyntax outerMostMemberAccessExpression = null; if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { outerMostMemberAccessExpression = nameOrMemberAccessExpression; } else { Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)); outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent; } outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile(n => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault(); if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax) { generateTypeServiceStateOptions.IsEnumNotAllowed = true; } } } // Cases: // // 1 - Function Address // var s2 = new MyD2(goo); // // 2 - Delegate // MyD1 d = null; // var s1 = new MyD2(d); // // 3 - Action // Action action1 = null; // var s3 = new MyD2(action1); // // 4 - Func // Func<int> lambda = () => { return 0; }; // var s4 = new MyD3(lambda); if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent; // Enum and Interface not Allowed in Object Creation Expression generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; if (objectCreationExpressionOpt.ArgumentList != null) { if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing) { return false; } // Get the Method symbol for the Delegate to be created if (generateTypeServiceStateOptions.IsDelegateAllowed && objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 && objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken); } else { generateTypeServiceStateOptions.IsDelegateAllowed = false; } } if (objectCreationExpressionOpt.Initializer != null) { foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions) { if (expression is not AssignmentExpressionSyntax simpleAssignmentExpression) { continue; } if (simpleAssignmentExpression.Left is not SimpleNameSyntax name) { continue; } generateTypeServiceStateOptions.PropertiesToGenerate.Add(name); } } } if (generateTypeServiceStateOptions.IsDelegateAllowed) { // MyD1 z1 = goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax variableDeclaration) && variableDeclaration.Variables.Count != 0) { var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null); if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken); } } // var w1 = (MyD1)goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) && castExpression.Expression != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken); } } return true; } private static IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression == null) { return null; } var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken); if (memberGroup.Length != 0) { return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null; } var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType.IsDelegateType()) { return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod; } var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (expressionSymbol.IsKind(SymbolKind.Method)) { return (IMethodSymbol)expressionSymbol; } return null; } private static Accessibility DetermineAccessibilityConstraint( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.DetermineAccessibilityConstraint( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } private static bool AllContainingTypesArePublicOrProtected( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.AllContainingTypesArePublicOrProtected( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } protected override ImmutableArray<ITypeParameterSymbol> GetTypeParameters( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { if (state.SimpleName is GenericNameSyntax) { var genericName = (GenericNameSyntax)state.SimpleName; var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList() : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity); return GetTypeParameters(state, semanticModel, typeArguments, cancellationToken); } return ImmutableArray<ITypeParameterSymbol>.Empty; } protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList) { if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null) { argumentList = objectCreationExpression.ArgumentList.Arguments.ToList(); return true; } argumentList = null; return false; } protected override IList<ParameterName> GenerateParameterNames( SemanticModel semanticModel, IList<ArgumentSyntax> arguments, CancellationToken cancellationToken) { return semanticModel.GenerateParameterNames(arguments, reservedNames: null, cancellationToken: cancellationToken); } public override string GetRootNamespace(CompilationOptions options) => string.Empty; protected override bool IsInVariableTypeContext(ExpressionSyntax expression) => false; protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken) => semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken); protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken); if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess) { var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken); if (accessibilityConstraint == Accessibility.Public || accessibilityConstraint == Accessibility.Internal) { accessibility = accessibilityConstraint; } else if (accessibilityConstraint == Accessibility.Protected || accessibilityConstraint == Accessibility.ProtectedOrInternal) { // If nested type is declared in public type then we should generate public type instead of internal accessibility = AllContainingTypesArePublicOrProtected(state, semanticModel, cancellationToken) ? Accessibility.Public : Accessibility.Internal; } } return accessibility; } protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) => argument.DetermineParameterType(semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; public override async Task<(INamespaceSymbol, INamespaceOrTypeSymbol, Location)> GetOrGenerateEnclosingNamespaceSymbolAsync( INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken) { var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot; var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (containers.Length != 0) { // Search the NS declaration in the root var containerList = new List<string>(containers); var enclosingNamespace = FindNamespaceInMemberDeclarations(compilationUnit.Members, indexDone: 0, containerList); if (enclosingNamespace != null) { var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken); if (enclosingNamespaceSymbol.Symbol is INamespaceSymbol namespaceSymbol) return (namespaceSymbol, namedTypeSymbol, enclosingNamespace.GetLastToken().GetLocation()); } } var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken); var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers); var lastMember = compilationUnit.Members.LastOrDefault(); var afterThisLocation = lastMember != null ? semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0)) : semanticModel.SyntaxTree.GetLocation(new TextSpan()); return (globalNamespace, rootNamespaceOrType, afterThisLocation); } private BaseNamespaceDeclarationSyntax FindNamespaceInMemberDeclarations(SyntaxList<MemberDeclarationSyntax> members, int indexDone, List<string> containers) { foreach (var member in members) { if (member is BaseNamespaceDeclarationSyntax namespaceDeclaration) { var found = FindNamespaceInNamespace(namespaceDeclaration, indexDone, containers); if (found != null) return found; } } return null; } private BaseNamespaceDeclarationSyntax FindNamespaceInNamespace(BaseNamespaceDeclarationSyntax namespaceDecl, int indexDone, List<string> containers) { if (namespaceDecl.Name is AliasQualifiedNameSyntax) return null; var namespaceContainers = new List<string>(); GetNamespaceContainers(namespaceDecl.Name, namespaceContainers); if (namespaceContainers.Count + indexDone > containers.Count || !IdentifierMatches(indexDone, namespaceContainers, containers)) { return null; } indexDone += namespaceContainers.Count; if (indexDone == containers.Count) return namespaceDecl; return FindNamespaceInMemberDeclarations(namespaceDecl.Members, indexDone, containers); } private static bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers) { for (var i = 0; i < namespaceContainers.Count; ++i) { if (namespaceContainers[i] != containers[indexDone + i]) { return false; } } return true; } private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers) { if (name is QualifiedNameSyntax qualifiedName) { GetNamespaceContainers(qualifiedName.Left, namespaceContainers); namespaceContainers.Add(qualifiedName.Right.Identifier.ValueText); } else { Debug.Assert(name is SimpleNameSyntax); namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText); } } internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue) { typeKindValue = TypeKindOptions.AllOptions; if (expression == null) { return false; } var node = expression as SyntaxNode; while (node != null) { if (node is BaseListSyntax) { if (node.Parent.IsKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration)) { typeKindValue = TypeKindOptions.Interface; return true; } typeKindValue = TypeKindOptions.BaseList; return true; } node = node.Parent; } return false; } internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project) { if (expression == null) { return false; } if (GeneratedTypesMustBePublic(project)) { return true; } var node = expression as SyntaxNode; SyntaxNode previousNode = null; while (node != null) { // Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { if (node.Parent is TypeDeclarationSyntax typeDecl) { if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return IsAllContainingTypeDeclsPublic(typeDecl); } else { // The Type Decl which contains the BaseList does not contain Public return false; } } throw ExceptionUtilities.Unreachable; } if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { // Make sure the GFU is not inside the Accessors if (previousNode != null && previousNode is AccessorListSyntax) { return false; } // Make sure that Event Declaration themselves are Public in the first place if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return false; } return IsAllContainingTypeDeclsPublic(node); } previousNode = node; node = node.Parent; } return false; } private static bool IsAllContainingTypeDeclsPublic(SyntaxNode node) { // Make sure that all the containing Type Declarations are also Public var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>(); if (containingTypeDeclarations.Count() == 0) { return true; } else { return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)); } } internal override bool IsGenericName(SimpleNameSyntax simpleName) => simpleName is GenericNameSyntax; internal override bool IsSimpleName(ExpressionSyntax expression) => expression is SimpleNameSyntax; internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken) { // Nothing to include if (string.IsNullOrWhiteSpace(includeUsingsOrImports)) { return updatedSolution; } SyntaxNode root = null; if (modifiedRoot == null) { root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } else { root = modifiedRoot; } if (root is CompilationUnitSyntax compilationRoot) { var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports)); // Check if the usings is already present if (compilationRoot.Usings.Where(n => n != null && n.Alias == null) .Select(n => n.Name.ToString()) .Any(n => n.Equals(includeUsingsOrImports))) { return updatedSolution; } // Check if the GFU is triggered from the namespace same as the usings namespace if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false)) { return updatedSolution; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity); } return updatedSolution; } private static ITypeSymbol GetPropertyType( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken) { if (propertyName.Parent is AssignmentExpressionSyntax parentAssignment) { return typeInference.InferType( semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken); } if (propertyName.Parent is IsPatternExpressionSyntax isPatternExpression) { return typeInference.InferType( semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken); } return null; } private static IPropertySymbol CreatePropertySymbol( SimpleNameSyntax propertyName, ITypeSymbol propertyType) { return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), explicitInterfaceImplementations: default, name: propertyName.Identifier.ValueText, type: propertyType, refKind: RefKind.None, parameters: default, getMethod: s_accessor, setMethod: s_accessor, isIndexer: false); } private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default, accessibility: Accessibility.Public, statements: default); internal override bool TryGenerateProperty( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property) { var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken); if (propertyType == null || propertyType is IErrorTypeSymbol) { property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType); return property != null; } property = CreatePropertySymbol(propertyName, propertyType); return property != 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.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateType { [ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared] internal class CSharpGenerateTypeService : AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateTypeService() { } protected override string DefaultFileExtension => ".cs"; protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName) => simpleName.GetLeftSideOfDot(); protected override bool IsInCatchDeclaration(ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.CatchDeclaration); protected override bool IsArrayElementType(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.ArrayType) && expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression); } protected override bool IsInValueTypeConstraintContext( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList, out TypeArgumentListSyntax typeArgumentList)) { var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken); var symbol = symbolInfo.GetAnySymbol(); if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression); if (symbol is INamedTypeSymbol type) { type = type.OriginalDefinition; var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } if (symbol is IMethodSymbol method) { method = method.OriginalDefinition; var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } } return false; } protected override bool IsInInterfaceList(ExpressionSyntax expression) { if (expression is TypeSyntax && expression.Parent is BaseTypeSyntax baseType && baseType.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax baseList) && baseType.Type == expression) { // If it's after the first item, then it's definitely an interface. if (baseList.Types[0] != expression.Parent) { return true; } // If it's in the base list of an interface or struct, then it's definitely an // interface. return baseList.IsParentKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration); } if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax typeConstraint) && typeConstraint.IsParentKind(SyntaxKind.TypeParameterConstraintClause, out TypeParameterConstraintClauseSyntax constraintClause)) { var index = constraintClause.Constraints.IndexOf(typeConstraint); // If it's after the first item, then it's definitely an interface. return index > 0; } return false; } protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts) { return expression.TryGetNameParts(out nameParts); } protected override bool TryInitializeState( SemanticDocument document, SimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions) { generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions(); if (simpleName.IsVar) { return false; } if (SyntaxFacts.IsAliasQualifier(simpleName)) { return false; } // Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly // unlikely that this would be a location where a user would be wanting to generate // something. They're really just trying to reference something that exists but // isn't available for some reason (i.e. a missing reference). var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword) { return false; } ExpressionSyntax nameOrMemberAccessExpression = null; if (simpleName.IsRightSideOfDot()) { // This simplename comes from the cref if (simpleName.IsParentKind(SyntaxKind.NameMemberCref)) { return false; } nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent; // If we're on the right side of a dot, then the left side better be a name (and // not an arbitrary expression). var leftSideExpression = simpleName.GetLeftSideOfDot(); if (!leftSideExpression.IsKind( SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.AliasQualifiedName, SyntaxKind.GenericName, SyntaxKind.SimpleMemberAccessExpression)) { return false; } } else { nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName; } // BUG(5712): Don't offer generate type in an enum's base list. if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax && nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression && nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration)) { return false; } // If we can guarantee it's a type only context, great. Otherwise, we may not want to // provide this here. var semanticModel = document.SemanticModel; if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { // Don't offer Generate Type in an expression context *unless* we're on the left // side of a dot. In that case the user might be making a type that they're // accessing a static off of. var syntaxTree = semanticModel.SyntaxTree; var start = nameOrMemberAccessExpression.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel); var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken); var isExpressionOrStatementContext = isExpressionContext || isStatementContext; // Delegate Type Creation is not allowed in Non Type Namespace Context generateTypeServiceStateOptions.IsDelegateAllowed = false; if (!isExpressionOrStatementContext) { return false; } if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOfExpression(semanticModel, cancellationToken)) { if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot()) { return false; } var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol; var token = simpleName.GetLastToken().GetNextToken(); // We let only the Namespace to be left of the Dot if (leftSymbol == null || !leftSymbol.IsKind(SymbolKind.Namespace) || !token.IsKind(SyntaxKind.DotToken)) { return false; } else { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } // Global Namespace if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess && !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName)) { var token = simpleName.GetLastToken().GetNextToken(); if (token.IsKind(SyntaxKind.DotToken) && simpleName.Parent == token.Parent) { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } } var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null && fieldDeclaration.Parent is CompilationUnitSyntax && document.Document.SourceCodeKind == SourceCodeKind.Regular) { return false; } // Check to see if Module could be an option in the Type Generation in Cross Language Generation var nextToken = simpleName.GetLastToken().GetNextToken(); if (simpleName.IsLeftSideOfDot() || nextToken.IsKind(SyntaxKind.DotToken)) { if (simpleName.IsRightSideOfDot()) { if (simpleName.Parent is QualifiedNameSyntax parent) { var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol; if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace)) { generateTypeServiceStateOptions.IsMembersWithModule = true; } } } } if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { if (nextToken.IsKind(SyntaxKind.DotToken)) { // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName generateTypeServiceStateOptions.IsDelegateAllowed = false; generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; generateTypeServiceStateOptions.IsMembersWithModule = true; } // case: class Goo<T> where T: MyType if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any()) { generateTypeServiceStateOptions.IsClassInterfaceTypes = true; return true; } // Events if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() || nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any()) { // Case : event goo name11 // Only Delegate if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax)) { generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } // Case : event SomeSymbol.goo name11 if (nameOrMemberAccessExpression is QualifiedNameSyntax) { // Only Namespace, Class, Struct and Module are allowed to contain Delegate // Case : event Something.Mytype.<Delegate> Identifier if (nextToken.IsKind(SyntaxKind.DotToken)) { if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax) { return true; } throw ExceptionUtilities.Unreachable; } else { // Case : event Something.<Delegate> Identifier generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } } } } else { // MemberAccessExpression if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) && nameOrMemberAccessExpression.IsLeftSideOfDot()) { // Check to see if the expression is part of Invocation Expression ExpressionSyntax outerMostMemberAccessExpression = null; if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { outerMostMemberAccessExpression = nameOrMemberAccessExpression; } else { Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)); outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent; } outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile(n => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault(); if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax) { generateTypeServiceStateOptions.IsEnumNotAllowed = true; } } } // Cases: // // 1 - Function Address // var s2 = new MyD2(goo); // // 2 - Delegate // MyD1 d = null; // var s1 = new MyD2(d); // // 3 - Action // Action action1 = null; // var s3 = new MyD2(action1); // // 4 - Func // Func<int> lambda = () => { return 0; }; // var s4 = new MyD3(lambda); if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent; // Enum and Interface not Allowed in Object Creation Expression generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; if (objectCreationExpressionOpt.ArgumentList != null) { if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing) { return false; } // Get the Method symbol for the Delegate to be created if (generateTypeServiceStateOptions.IsDelegateAllowed && objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 && objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken); } else { generateTypeServiceStateOptions.IsDelegateAllowed = false; } } if (objectCreationExpressionOpt.Initializer != null) { foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions) { if (expression is not AssignmentExpressionSyntax simpleAssignmentExpression) { continue; } if (simpleAssignmentExpression.Left is not SimpleNameSyntax name) { continue; } generateTypeServiceStateOptions.PropertiesToGenerate.Add(name); } } } if (generateTypeServiceStateOptions.IsDelegateAllowed) { // MyD1 z1 = goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax variableDeclaration) && variableDeclaration.Variables.Count != 0) { var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null); if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken); } } // var w1 = (MyD1)goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) && castExpression.Expression != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken); } } return true; } private static IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression == null) { return null; } var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken); if (memberGroup.Length != 0) { return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null; } var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType.IsDelegateType()) { return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod; } var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (expressionSymbol.IsKind(SymbolKind.Method)) { return (IMethodSymbol)expressionSymbol; } return null; } private static Accessibility DetermineAccessibilityConstraint( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.DetermineAccessibilityConstraint( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } private static bool AllContainingTypesArePublicOrProtected( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.AllContainingTypesArePublicOrProtected( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } protected override ImmutableArray<ITypeParameterSymbol> GetTypeParameters( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { if (state.SimpleName is GenericNameSyntax) { var genericName = (GenericNameSyntax)state.SimpleName; var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList() : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity); return GetTypeParameters(state, semanticModel, typeArguments, cancellationToken); } return ImmutableArray<ITypeParameterSymbol>.Empty; } protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList) { if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null) { argumentList = objectCreationExpression.ArgumentList.Arguments.ToList(); return true; } argumentList = null; return false; } protected override IList<ParameterName> GenerateParameterNames( SemanticModel semanticModel, IList<ArgumentSyntax> arguments, CancellationToken cancellationToken) { return semanticModel.GenerateParameterNames(arguments, reservedNames: null, cancellationToken: cancellationToken); } public override string GetRootNamespace(CompilationOptions options) => string.Empty; protected override bool IsInVariableTypeContext(ExpressionSyntax expression) => false; protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken) => semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken); protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken); if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess) { var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken); if (accessibilityConstraint == Accessibility.Public || accessibilityConstraint == Accessibility.Internal) { accessibility = accessibilityConstraint; } else if (accessibilityConstraint == Accessibility.Protected || accessibilityConstraint == Accessibility.ProtectedOrInternal) { // If nested type is declared in public type then we should generate public type instead of internal accessibility = AllContainingTypesArePublicOrProtected(state, semanticModel, cancellationToken) ? Accessibility.Public : Accessibility.Internal; } } return accessibility; } protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) => argument.DetermineParameterType(semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; public override async Task<(INamespaceSymbol, INamespaceOrTypeSymbol, Location)> GetOrGenerateEnclosingNamespaceSymbolAsync( INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken) { var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot; var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (containers.Length != 0) { // Search the NS declaration in the root var containerList = new List<string>(containers); var enclosingNamespace = FindNamespaceInMemberDeclarations(compilationUnit.Members, indexDone: 0, containerList); if (enclosingNamespace != null) { var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken); if (enclosingNamespaceSymbol.Symbol is INamespaceSymbol namespaceSymbol) return (namespaceSymbol, namedTypeSymbol, enclosingNamespace.GetLastToken().GetLocation()); } } var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken); var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers); var lastMember = compilationUnit.Members.LastOrDefault(); var afterThisLocation = lastMember != null ? semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0)) : semanticModel.SyntaxTree.GetLocation(new TextSpan()); return (globalNamespace, rootNamespaceOrType, afterThisLocation); } private BaseNamespaceDeclarationSyntax FindNamespaceInMemberDeclarations(SyntaxList<MemberDeclarationSyntax> members, int indexDone, List<string> containers) { foreach (var member in members) { if (member is BaseNamespaceDeclarationSyntax namespaceDeclaration) { var found = FindNamespaceInNamespace(namespaceDeclaration, indexDone, containers); if (found != null) return found; } } return null; } private BaseNamespaceDeclarationSyntax FindNamespaceInNamespace(BaseNamespaceDeclarationSyntax namespaceDecl, int indexDone, List<string> containers) { if (namespaceDecl.Name is AliasQualifiedNameSyntax) return null; var namespaceContainers = new List<string>(); GetNamespaceContainers(namespaceDecl.Name, namespaceContainers); if (namespaceContainers.Count + indexDone > containers.Count || !IdentifierMatches(indexDone, namespaceContainers, containers)) { return null; } indexDone += namespaceContainers.Count; if (indexDone == containers.Count) return namespaceDecl; return FindNamespaceInMemberDeclarations(namespaceDecl.Members, indexDone, containers); } private static bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers) { for (var i = 0; i < namespaceContainers.Count; ++i) { if (namespaceContainers[i] != containers[indexDone + i]) { return false; } } return true; } private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers) { if (name is QualifiedNameSyntax qualifiedName) { GetNamespaceContainers(qualifiedName.Left, namespaceContainers); namespaceContainers.Add(qualifiedName.Right.Identifier.ValueText); } else { Debug.Assert(name is SimpleNameSyntax); namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText); } } internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue) { typeKindValue = TypeKindOptions.AllOptions; if (expression == null) { return false; } var node = expression as SyntaxNode; while (node != null) { if (node is BaseListSyntax) { if (node.Parent.IsKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration)) { typeKindValue = TypeKindOptions.Interface; return true; } typeKindValue = TypeKindOptions.BaseList; return true; } node = node.Parent; } return false; } internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project) { if (expression == null) { return false; } if (GeneratedTypesMustBePublic(project)) { return true; } var node = expression as SyntaxNode; SyntaxNode previousNode = null; while (node != null) { // Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { if (node.Parent is TypeDeclarationSyntax typeDecl) { if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return IsAllContainingTypeDeclsPublic(typeDecl); } else { // The Type Decl which contains the BaseList does not contain Public return false; } } throw ExceptionUtilities.Unreachable; } if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { // Make sure the GFU is not inside the Accessors if (previousNode != null && previousNode is AccessorListSyntax) { return false; } // Make sure that Event Declaration themselves are Public in the first place if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return false; } return IsAllContainingTypeDeclsPublic(node); } previousNode = node; node = node.Parent; } return false; } private static bool IsAllContainingTypeDeclsPublic(SyntaxNode node) { // Make sure that all the containing Type Declarations are also Public var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>(); if (containingTypeDeclarations.Count() == 0) { return true; } else { return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)); } } internal override bool IsGenericName(SimpleNameSyntax simpleName) => simpleName is GenericNameSyntax; internal override bool IsSimpleName(ExpressionSyntax expression) => expression is SimpleNameSyntax; internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken) { // Nothing to include if (string.IsNullOrWhiteSpace(includeUsingsOrImports)) { return updatedSolution; } SyntaxNode root = null; if (modifiedRoot == null) { root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } else { root = modifiedRoot; } if (root is CompilationUnitSyntax compilationRoot) { var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports)); // Check if the usings is already present if (compilationRoot.Usings.Where(n => n != null && n.Alias == null) .Select(n => n.Name.ToString()) .Any(n => n.Equals(includeUsingsOrImports))) { return updatedSolution; } // Check if the GFU is triggered from the namespace same as the usings namespace if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false)) { return updatedSolution; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity); } return updatedSolution; } private static ITypeSymbol GetPropertyType( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken) { if (propertyName.Parent is AssignmentExpressionSyntax parentAssignment) { return typeInference.InferType( semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken); } if (propertyName.Parent is IsPatternExpressionSyntax isPatternExpression) { return typeInference.InferType( semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken); } return null; } private static IPropertySymbol CreatePropertySymbol( SimpleNameSyntax propertyName, ITypeSymbol propertyType) { return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), explicitInterfaceImplementations: default, name: propertyName.Identifier.ValueText, type: propertyType, refKind: RefKind.None, parameters: default, getMethod: s_accessor, setMethod: s_accessor, isIndexer: false); } private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default, accessibility: Accessibility.Public, statements: default); internal override bool TryGenerateProperty( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property) { var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken); if (propertyType == null || propertyType is IErrorTypeSymbol) { property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType); return property != null; } property = CreatePropertySymbol(propertyName, propertyType); return property != null; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Server/VBCSCompilerTests/TouchedFileLoggingTests.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.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.SharedResourceHelpers; using System.Reflection; using Microsoft.CodeAnalysis.CompilerServer; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class TouchedFileLoggingTests : TestBase { private static readonly string s_libDirectory = Environment.GetEnvironmentVariable("LIB"); private readonly string _baseDirectory = TempRoot.Root; private const string HelloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; private const string HelloWorldVB = @"Imports System Class C Shared Sub Main(args As String()) Console.WriteLine(""Hello, world"") End Sub End Class "; [ConditionalFact(typeof(DesktopOnly))] public void CSharpTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldCS).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new CSharpCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader(), driverCache: null); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (String f in filelist) { CleanupAllGeneratedFiles(f); } } [ConditionalFact(typeof(DesktopOnly))] public void VisualBasicTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldVB).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new VisualBasicCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader(), driverCache: null); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (string f in filelist) { CleanupAllGeneratedFiles(f); } } /// <summary> /// Builds the expected base of touched files. /// Adds a hook for temporary file creation as well, /// so this method must be called before the execution of /// Csc.Run. /// </summary> private static void BuildTouchedFiles(CommonCompiler cmd, string outputPath, out List<string> expectedReads, out List<string> expectedWrites) { expectedReads = new List<string>(); expectedReads.AddRange(cmd.Arguments.MetadataReferences.Select(r => r.Reference)); if (cmd.Arguments is VisualBasicCommandLineArguments { DefaultCoreLibraryReference: { } reference }) { expectedReads.Add(reference.Reference); } foreach (var file in cmd.Arguments.SourceFiles) { expectedReads.Add(file.Path); } var writes = new List<string>(); writes.Add(outputPath); expectedWrites = writes; } private static void AssertTouchedFilesEqual( List<string> expectedReads, List<string> expectedWrites, string touchedFilesBase) { var touchedReadPath = touchedFilesBase + ".read"; var touchedWritesPath = touchedFilesBase + ".write"; var expected = expectedReads.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedReadPath).Trim()); expected = expectedWrites.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedWritesPath).Trim()); } } }
// 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.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.SharedResourceHelpers; using System.Reflection; using Microsoft.CodeAnalysis.CompilerServer; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class TouchedFileLoggingTests : TestBase { private static readonly string s_libDirectory = Environment.GetEnvironmentVariable("LIB"); private readonly string _baseDirectory = TempRoot.Root; private const string HelloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; private const string HelloWorldVB = @"Imports System Class C Shared Sub Main(args As String()) Console.WriteLine(""Hello, world"") End Sub End Class "; [ConditionalFact(typeof(DesktopOnly))] public void CSharpTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldCS).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new CSharpCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader(), driverCache: null); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (String f in filelist) { CleanupAllGeneratedFiles(f); } } [ConditionalFact(typeof(DesktopOnly))] public void VisualBasicTrivialMetadataCaching() { var filelist = new List<string>(); // Do the following compilation twice. // The compiler server API should hold on to the mscorlib bits // in memory, but the file tracker should still map that it was // touched. for (int i = 0; i < 2; i++) { var source1 = Temp.CreateFile().WriteAllText(HelloWorldVB).Path; var touchedDir = Temp.CreateDirectory(); var touchedBase = Path.Combine(touchedDir.Path, "touched"); var clientDirectory = AppContext.BaseDirectory; filelist.Add(source1); var outWriter = new StringWriter(); var cmd = new VisualBasicCompilerServer( CompilerServerHost.SharedAssemblyReferenceProvider, responseFile: null, new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 }, new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()), s_libDirectory, new TestAnalyzerAssemblyLoader(), driverCache: null); List<string> expectedReads; List<string> expectedWrites; BuildTouchedFiles(cmd, Path.ChangeExtension(source1, "exe"), out expectedReads, out expectedWrites); var exitCode = cmd.Run(outWriter); Assert.Equal(string.Empty, outWriter.ToString().Trim()); Assert.Equal(0, exitCode); AssertTouchedFilesEqual(expectedReads, expectedWrites, touchedBase); } foreach (string f in filelist) { CleanupAllGeneratedFiles(f); } } /// <summary> /// Builds the expected base of touched files. /// Adds a hook for temporary file creation as well, /// so this method must be called before the execution of /// Csc.Run. /// </summary> private static void BuildTouchedFiles(CommonCompiler cmd, string outputPath, out List<string> expectedReads, out List<string> expectedWrites) { expectedReads = new List<string>(); expectedReads.AddRange(cmd.Arguments.MetadataReferences.Select(r => r.Reference)); if (cmd.Arguments is VisualBasicCommandLineArguments { DefaultCoreLibraryReference: { } reference }) { expectedReads.Add(reference.Reference); } foreach (var file in cmd.Arguments.SourceFiles) { expectedReads.Add(file.Path); } var writes = new List<string>(); writes.Add(outputPath); expectedWrites = writes; } private static void AssertTouchedFilesEqual( List<string> expectedReads, List<string> expectedWrites, string touchedFilesBase) { var touchedReadPath = touchedFilesBase + ".read"; var touchedWritesPath = touchedFilesBase + ".write"; var expected = expectedReads.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedReadPath).Trim()); expected = expectedWrites.Select(s => s.ToUpperInvariant()).OrderBy(s => s); Assert.Equal(string.Join("\r\n", expected), File.ReadAllText(touchedWritesPath).Trim()); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TryStatement.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 System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitTryStatement(BoundTryStatement node) { BoundBlock? tryBlock = (BoundBlock?)this.Visit(node.TryBlock); Debug.Assert(tryBlock is { }); var origSawAwait = _sawAwait; _sawAwait = false; var optimizing = _compilation.Options.OptimizationLevel == OptimizationLevel.Release; ImmutableArray<BoundCatchBlock> catchBlocks = // When optimizing and we have a try block without side-effects, we can discard the catch blocks. (optimizing && !HasSideEffects(tryBlock)) ? ImmutableArray<BoundCatchBlock>.Empty : this.VisitList(node.CatchBlocks); BoundBlock? finallyBlockOpt = (BoundBlock?)this.Visit(node.FinallyBlockOpt); _sawAwaitInExceptionHandler |= _sawAwait; _sawAwait |= origSawAwait; if (optimizing && !HasSideEffects(finallyBlockOpt)) { finallyBlockOpt = null; } return (catchBlocks.IsDefaultOrEmpty && finallyBlockOpt == null) ? (BoundNode)tryBlock : (BoundNode)node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler); } /// <summary> /// Is there any code to execute in the given statement that could have side-effects, /// such as throwing an exception? This implementation is conservative, in the sense /// that it may return true when the statement actually may have no side effects. /// </summary> private static bool HasSideEffects([NotNullWhen(true)] BoundStatement? statement) { if (statement == null) return false; switch (statement.Kind) { case BoundKind.NoOpStatement: return false; case BoundKind.Block: { var block = (BoundBlock)statement; foreach (var stmt in block.Statements) { if (HasSideEffects(stmt)) return true; } return false; } case BoundKind.SequencePoint: { var sequence = (BoundSequencePoint)statement; return HasSideEffects(sequence.StatementOpt); } case BoundKind.SequencePointWithSpan: { var sequence = (BoundSequencePointWithSpan)statement; return HasSideEffects(sequence.StatementOpt); } default: return true; } } public override BoundNode? VisitCatchBlock(BoundCatchBlock node) { if (node.ExceptionFilterOpt == null) { return base.VisitCatchBlock(node); } if (node.ExceptionFilterOpt.ConstantValue?.BooleanValue == false) { return null; } BoundExpression? rewrittenExceptionSourceOpt = (BoundExpression?)this.Visit(node.ExceptionSourceOpt); BoundStatementList? rewrittenFilterPrologue = (BoundStatementList?)this.Visit(node.ExceptionFilterPrologueOpt); BoundExpression? rewrittenFilter = (BoundExpression?)this.Visit(node.ExceptionFilterOpt); BoundBlock? rewrittenBody = (BoundBlock?)this.Visit(node.Body); Debug.Assert(rewrittenBody is { }); TypeSymbol? rewrittenExceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt); // 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 (rewrittenFilter != null && !node.WasCompilerGenerated && this.Instrument) { rewrittenFilter = _instrumenter.InstrumentCatchClauseFilter(node, rewrittenFilter, _factory); } return node.Update( node.Locals, rewrittenExceptionSourceOpt, rewrittenExceptionTypeOpt, rewrittenFilterPrologue, rewrittenFilter, rewrittenBody, node.IsSynthesizedAsyncCatchAll); } } }
// 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 System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitTryStatement(BoundTryStatement node) { BoundBlock? tryBlock = (BoundBlock?)this.Visit(node.TryBlock); Debug.Assert(tryBlock is { }); var origSawAwait = _sawAwait; _sawAwait = false; var optimizing = _compilation.Options.OptimizationLevel == OptimizationLevel.Release; ImmutableArray<BoundCatchBlock> catchBlocks = // When optimizing and we have a try block without side-effects, we can discard the catch blocks. (optimizing && !HasSideEffects(tryBlock)) ? ImmutableArray<BoundCatchBlock>.Empty : this.VisitList(node.CatchBlocks); BoundBlock? finallyBlockOpt = (BoundBlock?)this.Visit(node.FinallyBlockOpt); _sawAwaitInExceptionHandler |= _sawAwait; _sawAwait |= origSawAwait; if (optimizing && !HasSideEffects(finallyBlockOpt)) { finallyBlockOpt = null; } return (catchBlocks.IsDefaultOrEmpty && finallyBlockOpt == null) ? (BoundNode)tryBlock : (BoundNode)node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler); } /// <summary> /// Is there any code to execute in the given statement that could have side-effects, /// such as throwing an exception? This implementation is conservative, in the sense /// that it may return true when the statement actually may have no side effects. /// </summary> private static bool HasSideEffects([NotNullWhen(true)] BoundStatement? statement) { if (statement == null) return false; switch (statement.Kind) { case BoundKind.NoOpStatement: return false; case BoundKind.Block: { var block = (BoundBlock)statement; foreach (var stmt in block.Statements) { if (HasSideEffects(stmt)) return true; } return false; } case BoundKind.SequencePoint: { var sequence = (BoundSequencePoint)statement; return HasSideEffects(sequence.StatementOpt); } case BoundKind.SequencePointWithSpan: { var sequence = (BoundSequencePointWithSpan)statement; return HasSideEffects(sequence.StatementOpt); } default: return true; } } public override BoundNode? VisitCatchBlock(BoundCatchBlock node) { if (node.ExceptionFilterOpt == null) { return base.VisitCatchBlock(node); } if (node.ExceptionFilterOpt.ConstantValue?.BooleanValue == false) { return null; } BoundExpression? rewrittenExceptionSourceOpt = (BoundExpression?)this.Visit(node.ExceptionSourceOpt); BoundStatementList? rewrittenFilterPrologue = (BoundStatementList?)this.Visit(node.ExceptionFilterPrologueOpt); BoundExpression? rewrittenFilter = (BoundExpression?)this.Visit(node.ExceptionFilterOpt); BoundBlock? rewrittenBody = (BoundBlock?)this.Visit(node.Body); Debug.Assert(rewrittenBody is { }); TypeSymbol? rewrittenExceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt); // 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 (rewrittenFilter != null && !node.WasCompilerGenerated && this.Instrument) { rewrittenFilter = _instrumenter.InstrumentCatchClauseFilter(node, rewrittenFilter, _factory); } return node.Update( node.Locals, rewrittenExceptionSourceOpt, rewrittenExceptionTypeOpt, rewrittenFilterPrologue, rewrittenFilter, rewrittenBody, node.IsSynthesizedAsyncCatchAll); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/Core/Implementation/InlineRename/Taggers/RenameClassificationTaggerProvider.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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [TagType(typeof(IClassificationTag))] internal class RenameClassificationTaggerProvider : ITaggerProvider { private readonly InlineRenameService _renameService; private readonly IClassificationType _classificationType; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameClassificationTaggerProvider( InlineRenameService renameService, IClassificationTypeRegistryService classificationTypeRegistryService) { _renameService = renameService; _classificationType = classificationTypeRegistryService.GetClassificationType(ClassificationTypeDefinitions.InlineRenameField); } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new RenameClassificationTagger(buffer, _renameService, _classificationType) as ITagger<T>; } }
// 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [TagType(typeof(IClassificationTag))] internal class RenameClassificationTaggerProvider : ITaggerProvider { private readonly InlineRenameService _renameService; private readonly IClassificationType _classificationType; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameClassificationTaggerProvider( InlineRenameService renameService, IClassificationTypeRegistryService classificationTypeRegistryService) { _renameService = renameService; _classificationType = classificationTypeRegistryService.GetClassificationType(ClassificationTypeDefinitions.InlineRenameField); } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new RenameClassificationTagger(buffer, _renameService, _classificationType) as ITagger<T>; } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordOrdinaryMethod.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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Common base for ordinary methods synthesized by compiler for records. /// </summary> internal abstract class SynthesizedRecordOrdinaryMethod : SourceOrdinaryMethodSymbolBase { private readonly int _memberOffset; protected SynthesizedRecordOrdinaryMethod(SourceMemberContainerTypeSymbol containingType, string name, bool isReadOnly, bool hasBody, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, name, containingType.Locations[0], (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), MethodKind.Ordinary, isIterator: false, isExtensionMethod: false, isPartial: false, isReadOnly: isReadOnly, hasBody: hasBody, isNullableAnalysisEnabled: false, diagnostics) { _memberOffset = memberOffset; } protected sealed override bool HasAnyBody => true; internal sealed override bool IsExpressionBodied => false; public sealed override bool IsImplicitlyDeclared => true; protected sealed override Location ReturnTypeLocation => Locations[0]; protected sealed override MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) => null; internal sealed override LexicalSortKey GetLexicalSortKey() => LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); protected sealed override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) => ImmutableArray<TypeParameterSymbol>.Empty; public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void CompleteAsyncMethodChecksBetweenStartAndFinish() { } protected sealed override TypeSymbol? ExplicitInterfaceType => null; protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { } protected sealed override SourceMemberMethodSymbol? BoundAttributesSource => null; internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() => OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); public sealed override string? GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default) => null; public sealed override bool IsVararg => false; public sealed override RefKind RefKind => RefKind.None; internal sealed override bool GenerateDebugInfo => false; internal sealed override bool SynthesizesLoweredBoundBody => 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.Collections.Immutable; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Common base for ordinary methods synthesized by compiler for records. /// </summary> internal abstract class SynthesizedRecordOrdinaryMethod : SourceOrdinaryMethodSymbolBase { private readonly int _memberOffset; protected SynthesizedRecordOrdinaryMethod(SourceMemberContainerTypeSymbol containingType, string name, bool isReadOnly, bool hasBody, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, name, containingType.Locations[0], (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), MethodKind.Ordinary, isIterator: false, isExtensionMethod: false, isPartial: false, isReadOnly: isReadOnly, hasBody: hasBody, isNullableAnalysisEnabled: false, diagnostics) { _memberOffset = memberOffset; } protected sealed override bool HasAnyBody => true; internal sealed override bool IsExpressionBodied => false; public sealed override bool IsImplicitlyDeclared => true; protected sealed override Location ReturnTypeLocation => Locations[0]; protected sealed override MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) => null; internal sealed override LexicalSortKey GetLexicalSortKey() => LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); protected sealed override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) => ImmutableArray<TypeParameterSymbol>.Empty; public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void CompleteAsyncMethodChecksBetweenStartAndFinish() { } protected sealed override TypeSymbol? ExplicitInterfaceType => null; protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { } protected sealed override SourceMemberMethodSymbol? BoundAttributesSource => null; internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() => OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); public sealed override string? GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default) => null; public sealed override bool IsVararg => false; public sealed override RefKind RefKind => RefKind.None; internal sealed override bool GenerateDebugInfo => false; internal sealed override bool SynthesizesLoweredBoundBody => true; } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveWorkspace.SolutionAnalyzerSetter.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.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal partial class InteractiveWorkspace { internal sealed class SolutionAnalyzerSetter : ISolutionAnalyzerSetterWorkspaceService { [ExportWorkspaceServiceFactory(typeof(ISolutionAnalyzerSetterWorkspaceService), WorkspaceKind.Interactive), Shared] internal sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SolutionAnalyzerSetter((InteractiveWorkspace)workspaceServices.Workspace); } private readonly InteractiveWorkspace _workspace; public SolutionAnalyzerSetter(InteractiveWorkspace workspace) => _workspace = workspace; public void SetAnalyzerReferences(ImmutableArray<AnalyzerReference> references) => _workspace.SetCurrentSolution(s => s.WithAnalyzerReferences(references), WorkspaceChangeKind.SolutionChanged); } } }
// 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.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal partial class InteractiveWorkspace { internal sealed class SolutionAnalyzerSetter : ISolutionAnalyzerSetterWorkspaceService { [ExportWorkspaceServiceFactory(typeof(ISolutionAnalyzerSetterWorkspaceService), WorkspaceKind.Interactive), Shared] internal sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SolutionAnalyzerSetter((InteractiveWorkspace)workspaceServices.Workspace); } private readonly InteractiveWorkspace _workspace; public SolutionAnalyzerSetter(InteractiveWorkspace workspace) => _workspace = workspace; public void SetAnalyzerReferences(ImmutableArray<AnalyzerReference> references) => _workspace.SetCurrentSolution(s => s.WithAnalyzerReferences(references), WorkspaceChangeKind.SolutionChanged); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddParameter; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable { internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> : AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>, IGenerateVariableService where TService : AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> where TSimpleNameSyntax : TExpressionSyntax where TExpressionSyntax : SyntaxNode { protected AbstractGenerateVariableService() { } protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node); protected abstract bool IsIdentifierNameGeneration(SyntaxNode node); protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeIdentifierNameState(SemanticDocument document, TSimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isinConditionalAccessExpression); protected abstract bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxNode newRoot); public async Task<ImmutableArray<CodeAction>> GenerateVariableAsync( Document document, SyntaxNode node, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateVariable, cancellationToken)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false); if (state == null) { return ImmutableArray<CodeAction>.Empty; } using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions); var canGenerateMember = CodeGenerator.CanAdd(document.Project.Solution, state.TypeToGenerateIn, cancellationToken); if (canGenerateMember && state.CanGeneratePropertyOrField()) { // prefer fields over properties (and vice versa) depending on the casing of the member. // lowercase -> fields. title case -> properties. var name = state.IdentifierToken.ValueText; if (char.IsUpper(name.ToCharArray().FirstOrDefault())) { AddPropertyCodeActions(actions, semanticDocument, state); AddFieldCodeActions(actions, semanticDocument, state); } else { AddFieldCodeActions(actions, semanticDocument, state); AddPropertyCodeActions(actions, semanticDocument, state); } } AddLocalCodeActions(actions, document, state); AddParameterCodeActions(actions, document, state); if (actions.Count > 1) { // Wrap the generate variable actions into a single top level suggestion // so as to not clutter the list. return ImmutableArray.Create<CodeAction>(new MyCodeAction( string.Format(FeaturesResources.Generate_variable_0, state.IdentifierToken.ValueText), actions.ToImmutable())); } return actions.ToImmutable(); } } protected virtual bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => false; private static void AddPropertyCodeActions( ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { if (state.IsInOutContext) { return; } if (state.IsConstant) { return; } if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface && state.IsStatic) { return; } var isOnlyReadAndIsInInterface = state.TypeToGenerateIn.TypeKind == TypeKind.Interface && !state.IsWrittenTo; if (isOnlyReadAndIsInInterface || state.IsInConstructor) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: true, isReadonly: true, isConstant: false, refKind: GetRefKindFromContext(state))); } GenerateWritableProperty(result, document, state); } private static void GenerateWritableProperty(ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: true, isReadonly: false, isConstant: false, refKind: GetRefKindFromContext(state))); } private static void AddFieldCodeActions(ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { if (state.TypeToGenerateIn.TypeKind != TypeKind.Interface) { if (state.IsConstant) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: false, isReadonly: false, isConstant: true, refKind: RefKind.None)); } else { if (!state.OfferReadOnlyFieldFirst) { GenerateWriteableField(result, document, state); } // If we haven't written to the field, or we're in the constructor for the type // we're writing into, then we can generate this field read-only. if (!state.IsWrittenTo || state.IsInConstructor) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: false, isReadonly: true, isConstant: false, refKind: RefKind.None)); } if (state.OfferReadOnlyFieldFirst) { GenerateWriteableField(result, document, state); } } } } private static void GenerateWriteableField(ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: false, isReadonly: false, isConstant: false, refKind: RefKind.None)); } private void AddLocalCodeActions(ArrayBuilder<CodeAction> result, Document document, State state) { if (state.CanGenerateLocal()) { result.Add(new GenerateLocalCodeAction((TService)this, document, state)); } } private static void AddParameterCodeActions(ArrayBuilder<CodeAction> result, Document document, State state) { if (state.CanGenerateParameter()) { result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: false)); if (AddParameterService.Instance.HasCascadingDeclarations(state.ContainingMethod)) result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: true)); } } private static RefKind GetRefKindFromContext(State state) { if (state.IsInRefContext) { return RefKind.Ref; } else if (state.IsInInContext) { return RefKind.RefReadOnly; } else { return RefKind.None; } } private class MyCodeAction : CodeAction.CodeActionWithNestedActions { public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions) : base(title, nestedActions, isInlinable: 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. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddParameter; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable { internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> : AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>, IGenerateVariableService where TService : AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> where TSimpleNameSyntax : TExpressionSyntax where TExpressionSyntax : SyntaxNode { protected AbstractGenerateVariableService() { } protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node); protected abstract bool IsIdentifierNameGeneration(SyntaxNode node); protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeIdentifierNameState(SemanticDocument document, TSimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isinConditionalAccessExpression); protected abstract bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxNode newRoot); public async Task<ImmutableArray<CodeAction>> GenerateVariableAsync( Document document, SyntaxNode node, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateVariable, cancellationToken)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false); if (state == null) { return ImmutableArray<CodeAction>.Empty; } using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions); var canGenerateMember = CodeGenerator.CanAdd(document.Project.Solution, state.TypeToGenerateIn, cancellationToken); if (canGenerateMember && state.CanGeneratePropertyOrField()) { // prefer fields over properties (and vice versa) depending on the casing of the member. // lowercase -> fields. title case -> properties. var name = state.IdentifierToken.ValueText; if (char.IsUpper(name.ToCharArray().FirstOrDefault())) { AddPropertyCodeActions(actions, semanticDocument, state); AddFieldCodeActions(actions, semanticDocument, state); } else { AddFieldCodeActions(actions, semanticDocument, state); AddPropertyCodeActions(actions, semanticDocument, state); } } AddLocalCodeActions(actions, document, state); AddParameterCodeActions(actions, document, state); if (actions.Count > 1) { // Wrap the generate variable actions into a single top level suggestion // so as to not clutter the list. return ImmutableArray.Create<CodeAction>(new MyCodeAction( string.Format(FeaturesResources.Generate_variable_0, state.IdentifierToken.ValueText), actions.ToImmutable())); } return actions.ToImmutable(); } } protected virtual bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => false; private static void AddPropertyCodeActions( ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { if (state.IsInOutContext) { return; } if (state.IsConstant) { return; } if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface && state.IsStatic) { return; } var isOnlyReadAndIsInInterface = state.TypeToGenerateIn.TypeKind == TypeKind.Interface && !state.IsWrittenTo; if (isOnlyReadAndIsInInterface || state.IsInConstructor) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: true, isReadonly: true, isConstant: false, refKind: GetRefKindFromContext(state))); } GenerateWritableProperty(result, document, state); } private static void GenerateWritableProperty(ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: true, isReadonly: false, isConstant: false, refKind: GetRefKindFromContext(state))); } private static void AddFieldCodeActions(ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { if (state.TypeToGenerateIn.TypeKind != TypeKind.Interface) { if (state.IsConstant) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: false, isReadonly: false, isConstant: true, refKind: RefKind.None)); } else { if (!state.OfferReadOnlyFieldFirst) { GenerateWriteableField(result, document, state); } // If we haven't written to the field, or we're in the constructor for the type // we're writing into, then we can generate this field read-only. if (!state.IsWrittenTo || state.IsInConstructor) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: false, isReadonly: true, isConstant: false, refKind: RefKind.None)); } if (state.OfferReadOnlyFieldFirst) { GenerateWriteableField(result, document, state); } } } } private static void GenerateWriteableField(ArrayBuilder<CodeAction> result, SemanticDocument document, State state) { result.Add(new GenerateVariableCodeAction( document, state, generateProperty: false, isReadonly: false, isConstant: false, refKind: RefKind.None)); } private void AddLocalCodeActions(ArrayBuilder<CodeAction> result, Document document, State state) { if (state.CanGenerateLocal()) { result.Add(new GenerateLocalCodeAction((TService)this, document, state)); } } private static void AddParameterCodeActions(ArrayBuilder<CodeAction> result, Document document, State state) { if (state.CanGenerateParameter()) { result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: false)); if (AddParameterService.Instance.HasCascadingDeclarations(state.ContainingMethod)) result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: true)); } } private static RefKind GetRefKindFromContext(State state) { if (state.IsInRefContext) { return RefKind.Ref; } else if (state.IsInInContext) { return RefKind.RefReadOnly; } else { return RefKind.None; } } private class MyCodeAction : CodeAction.CodeActionWithNestedActions { public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions) : base(title, nestedActions, isInlinable: true) { } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/ProjectTelemetry/IProjectTelemetryListener.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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ProjectTelemetry { /// <summary> /// Callback the host (VS) passes to the OOP service to allow it to send batch notifications /// about telemetry. /// </summary> internal interface IProjectTelemetryListener { ValueTask ReportProjectTelemetryDataAsync(ProjectTelemetryData data, CancellationToken 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ProjectTelemetry { /// <summary> /// Callback the host (VS) passes to the OOP service to allow it to send batch notifications /// about telemetry. /// </summary> internal interface IProjectTelemetryListener { ValueTask ReportProjectTelemetryDataAsync(ProjectTelemetryData data, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/CoreTest/Host/WorkspaceServices/TestOptionsServiceFactory.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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { [ExportWorkspaceServiceFactory(typeof(IOptionService), ServiceLayer.Host), Shared] internal class TestOptionsServiceFactory : IWorkspaceServiceFactory { private readonly IWorkspaceThreadingService? _workspaceThreadingService; private readonly ImmutableArray<Lazy<IOptionProvider, LanguageMetadata>> _providers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestOptionsServiceFactory( [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService, [ImportMany] IEnumerable<Lazy<IOptionProvider, LanguageMetadata>> optionProviders) { _workspaceThreadingService = workspaceThreadingService; _providers = optionProviders.ToImmutableArray(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { // give out new option service per workspace return new OptionServiceFactory.OptionService( new GlobalOptionService(_workspaceThreadingService, _providers, SpecializedCollections.EmptyEnumerable<Lazy<IOptionPersisterProvider>>()), workspaceServices); } } }
// 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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { [ExportWorkspaceServiceFactory(typeof(IOptionService), ServiceLayer.Host), Shared] internal class TestOptionsServiceFactory : IWorkspaceServiceFactory { private readonly IWorkspaceThreadingService? _workspaceThreadingService; private readonly ImmutableArray<Lazy<IOptionProvider, LanguageMetadata>> _providers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestOptionsServiceFactory( [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService, [ImportMany] IEnumerable<Lazy<IOptionProvider, LanguageMetadata>> optionProviders) { _workspaceThreadingService = workspaceThreadingService; _providers = optionProviders.ToImmutableArray(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { // give out new option service per workspace return new OptionServiceFactory.OptionService( new GlobalOptionService(_workspaceThreadingService, _providers, SpecializedCollections.EmptyEnumerable<Lazy<IOptionPersisterProvider>>()), workspaceServices); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Tools/AnalyzerRunner/AnalyzerRunnerHelper.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.MSBuild; namespace AnalyzerRunner { public static class AnalyzerRunnerHelper { static AnalyzerRunnerHelper() { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); #if NETCOREAPP // Since we do not inherit msbuild.deps.json when referencing the SDK copy // of MSBuild and because the SDK no longer ships with version matched assemblies, we // register an assembly loader that will load assemblies from the msbuild path with // equal or higher version numbers than requested. LooseVersionAssemblyLoader.Register(msBuildInstance.MSBuildPath); #endif MSBuildLocator.RegisterInstance(msBuildInstance); } public static MSBuildWorkspace CreateWorkspace() { var properties = new Dictionary<string, string> { #if NETCOREAPP // This property ensures that XAML files will be compiled in the current AppDomain // rather than a separate one. Any tasks isolated in AppDomains or tasks that create // AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16. { "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString }, #endif // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "latest" }, }; return MSBuildWorkspace.Create(properties, AnalyzerRunnerMefHostServices.DefaultServices); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.MSBuild; namespace AnalyzerRunner { public static class AnalyzerRunnerHelper { static AnalyzerRunnerHelper() { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); #if NETCOREAPP // Since we do not inherit msbuild.deps.json when referencing the SDK copy // of MSBuild and because the SDK no longer ships with version matched assemblies, we // register an assembly loader that will load assemblies from the msbuild path with // equal or higher version numbers than requested. LooseVersionAssemblyLoader.Register(msBuildInstance.MSBuildPath); #endif MSBuildLocator.RegisterInstance(msBuildInstance); } public static MSBuildWorkspace CreateWorkspace() { var properties = new Dictionary<string, string> { #if NETCOREAPP // This property ensures that XAML files will be compiled in the current AppDomain // rather than a separate one. Any tasks isolated in AppDomains or tasks that create // AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16. { "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString }, #endif // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "latest" }, }; return MSBuildWorkspace.Create(properties, AnalyzerRunnerMefHostServices.DefaultServices); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/Storage/SQLite/Interop/OpenFlags.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.SQLite.Interop { // From: https://sqlite.org/c3ref/c_open_autoproxy.html // Uncomment what you need. Leave the rest commented out to make it clear // what we are/aren't using. internal enum OpenFlags { // SQLITE_OPEN_READONLY = 0x00000001, /* Ok for sqlite3_open_v2() */ SQLITE_OPEN_READWRITE = 0x00000002, /* Ok for sqlite3_open_v2() */ SQLITE_OPEN_CREATE = 0x00000004, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_DELETEONCLOSE = 0x00000008, /* VFS only */ // SQLITE_OPEN_EXCLUSIVE = 0x00000010, /* VFS only */ // SQLITE_OPEN_AUTOPROXY = 0x00000020, /* VFS only */ SQLITE_OPEN_URI = 0x00000040, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_MEMORY = 0x00000080, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_MAIN_DB = 0x00000100, /* VFS only */ // SQLITE_OPEN_TEMP_DB = 0x00000200, /* VFS only */ // SQLITE_OPEN_TRANSIENT_DB = 0x00000400, /* VFS only */ // SQLITE_OPEN_MAIN_JOURNAL = 0x00000800, /* VFS only */ // SQLITE_OPEN_TEMP_JOURNAL = 0x00001000, /* VFS only */ // SQLITE_OPEN_SUBJOURNAL = 0x00002000, /* VFS only */ // SQLITE_OPEN_MASTER_JOURNAL = 0x00004000, /* VFS only */ SQLITE_OPEN_NOMUTEX = 0x00008000, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_FULLMUTEX = 0x00010000, /* Ok for sqlite3_open_v2() */ SQLITE_OPEN_SHAREDCACHE = 0x00020000, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_PRIVATECACHE = 0x00040000, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_WAL = 0x00080000, /* VFS only */ } }
// 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.SQLite.Interop { // From: https://sqlite.org/c3ref/c_open_autoproxy.html // Uncomment what you need. Leave the rest commented out to make it clear // what we are/aren't using. internal enum OpenFlags { // SQLITE_OPEN_READONLY = 0x00000001, /* Ok for sqlite3_open_v2() */ SQLITE_OPEN_READWRITE = 0x00000002, /* Ok for sqlite3_open_v2() */ SQLITE_OPEN_CREATE = 0x00000004, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_DELETEONCLOSE = 0x00000008, /* VFS only */ // SQLITE_OPEN_EXCLUSIVE = 0x00000010, /* VFS only */ // SQLITE_OPEN_AUTOPROXY = 0x00000020, /* VFS only */ SQLITE_OPEN_URI = 0x00000040, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_MEMORY = 0x00000080, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_MAIN_DB = 0x00000100, /* VFS only */ // SQLITE_OPEN_TEMP_DB = 0x00000200, /* VFS only */ // SQLITE_OPEN_TRANSIENT_DB = 0x00000400, /* VFS only */ // SQLITE_OPEN_MAIN_JOURNAL = 0x00000800, /* VFS only */ // SQLITE_OPEN_TEMP_JOURNAL = 0x00001000, /* VFS only */ // SQLITE_OPEN_SUBJOURNAL = 0x00002000, /* VFS only */ // SQLITE_OPEN_MASTER_JOURNAL = 0x00004000, /* VFS only */ SQLITE_OPEN_NOMUTEX = 0x00008000, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_FULLMUTEX = 0x00010000, /* Ok for sqlite3_open_v2() */ SQLITE_OPEN_SHAREDCACHE = 0x00020000, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_PRIVATECACHE = 0x00040000, /* Ok for sqlite3_open_v2() */ // SQLITE_OPEN_WAL = 0x00080000, /* VFS only */ } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Errors/LazyUseSiteDiagnosticsInfoForNullableType.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.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUseSiteDiagnosticsInfoForNullableType : LazyDiagnosticInfo { private readonly LanguageVersion _languageVersion; private readonly TypeWithAnnotations _possiblyNullableTypeSymbol; internal LazyUseSiteDiagnosticsInfoForNullableType(LanguageVersion languageVersion, TypeWithAnnotations possiblyNullableTypeSymbol) { _languageVersion = languageVersion; _possiblyNullableTypeSymbol = possiblyNullableTypeSymbol; } protected override DiagnosticInfo? ResolveInfo() { if (_possiblyNullableTypeSymbol.IsNullableType()) { return _possiblyNullableTypeSymbol.Type.OriginalDefinition.GetUseSiteInfo().DiagnosticInfo; } return Binder.GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(_languageVersion, _possiblyNullableTypeSymbol); } } }
// 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.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUseSiteDiagnosticsInfoForNullableType : LazyDiagnosticInfo { private readonly LanguageVersion _languageVersion; private readonly TypeWithAnnotations _possiblyNullableTypeSymbol; internal LazyUseSiteDiagnosticsInfoForNullableType(LanguageVersion languageVersion, TypeWithAnnotations possiblyNullableTypeSymbol) { _languageVersion = languageVersion; _possiblyNullableTypeSymbol = possiblyNullableTypeSymbol; } protected override DiagnosticInfo? ResolveInfo() { if (_possiblyNullableTypeSymbol.IsNullableType()) { return _possiblyNullableTypeSymbol.Type.OriginalDefinition.GetUseSiteInfo().DiagnosticInfo; } return Binder.GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(_languageVersion, _possiblyNullableTypeSymbol); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Xaml/Impl/Features/QuickInfo/XamlQuickInfo.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; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal sealed class XamlQuickInfo { public TextSpan Span { get; } public IEnumerable<TaggedText> Description { get; } public ISymbol Symbol { get; } private XamlQuickInfo( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol) { Span = span; Description = description; Symbol = symbol; } public static XamlQuickInfo Create( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol = null) { return new XamlQuickInfo(span, description, symbol); } } }
// 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; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal sealed class XamlQuickInfo { public TextSpan Span { get; } public IEnumerable<TaggedText> Description { get; } public ISymbol Symbol { get; } private XamlQuickInfo( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol) { Span = span; Description = description; Symbol = symbol; } public static XamlQuickInfo Create( TextSpan span, IEnumerable<TaggedText> description, ISymbol symbol = null) { return new XamlQuickInfo(span, description, symbol); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/CSharp/Portable/Formatting/CSharpNewDocumentFormattingService.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.Composition; using System.Linq; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Formatting { [ExportLanguageService(typeof(INewDocumentFormattingService), LanguageNames.CSharp)] [Shared] internal class CSharpNewDocumentFormattingService : AbstractNewDocumentFormattingService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpNewDocumentFormattingService([ImportMany] IEnumerable<Lazy<INewDocumentFormattingProvider, LanguageMetadata>> providers) : base(providers) { } protected override string Language => 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. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Formatting { [ExportLanguageService(typeof(INewDocumentFormattingService), LanguageNames.CSharp)] [Shared] internal class CSharpNewDocumentFormattingService : AbstractNewDocumentFormattingService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpNewDocumentFormattingService([ImportMany] IEnumerable<Lazy<INewDocumentFormattingProvider, LanguageMetadata>> providers) : base(providers) { } protected override string Language => LanguageNames.CSharp; } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/Core/Portable/ExtractMethod/ExtractMethodOptionsProvider.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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ExtractMethod { [ExportOptionProvider, Shared] internal class ExtractMethodOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExtractMethodOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ExtractMethodOptions.AllowBestEffort, ExtractMethodOptions.DontPutOutOrRefOnStruct); } }
// 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ExtractMethod { [ExportOptionProvider, Shared] internal class ExtractMethodOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExtractMethodOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ExtractMethodOptions.AllowBestEffort, ExtractMethodOptions.DontPutOutOrRefOnStruct); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Remote/Core/RemoteEndPoint.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.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Helper type that abstract out JsonRpc communication with extra capability of /// using raw stream to move over big chunk of data /// </summary> internal sealed class RemoteEndPoint : IDisposable { private const string UnexpectedExceptionLogMessage = "Unexpected exception from JSON-RPC"; private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new JsonRpcTargetOptions() { // Do not allow JSON-RPC to automatically subscribe to events and remote their calls. NotifyClientOfEvents = false, // Only allow public methods (may be on internal types) to be invoked remotely. AllowNonPublicInvocation = false }; private static int s_id; private readonly int _id; private readonly TraceSource _logger; private readonly JsonRpc _rpc; private bool _startedListening; private JsonRpcDisconnectedEventArgs? _disconnectedReason; public event Action<JsonRpcDisconnectedEventArgs>? Disconnected; public event Action<Exception>? UnexpectedExceptionThrown; public RemoteEndPoint(Stream stream, TraceSource logger, object? incomingCallTarget, IEnumerable<JsonConverter>? jsonConverters = null) { RoslynDebug.Assert(stream != null); RoslynDebug.Assert(logger != null); _id = Interlocked.Increment(ref s_id); _logger = logger; var jsonFormatter = new JsonMessageFormatter(); if (jsonConverters != null) { jsonFormatter.JsonSerializer.Converters.AddRange(jsonConverters); } jsonFormatter.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance); _rpc = new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter)) { CancelLocallyInvokedMethodsWhenConnectionIsClosed = true, TraceSource = logger, ExceptionStrategy = ExceptionProcessing.ISerializable, }; if (incomingCallTarget != null) { _rpc.AddLocalRpcTarget(incomingCallTarget, s_jsonRpcTargetOptions); } _rpc.Disconnected += OnDisconnected; } /// <summary> /// Must be called before any communication commences. /// See https://github.com/dotnet/roslyn/issues/16900#issuecomment-277378950. /// </summary> public void StartListening() { _rpc.StartListening(); _startedListening = true; } public bool IsDisposed => _rpc.IsDisposed; public void Dispose() { _rpc.Disconnected -= OnDisconnected; _rpc.Dispose(); } public async Task InvokeAsync(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_startedListening); // if this end-point is already disconnected do not log more errors: var logError = _disconnectedReason == null; try { await _rpc.InvokeWithCancellationAsync(targetName, arguments, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, cancellationToken)) { // Remote call may fail with different exception even when our cancellation token is signaled // (e.g. on shutdown if the connection is dropped): cancellationToken.ThrowIfCancellationRequested(); throw CreateSoftCrashException(ex, cancellationToken); } } public async Task TryInvokeAsync(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_startedListening); if (_rpc.IsDisposed) { return; } try { await _rpc.InvokeWithCancellationAsync(targetName, arguments, cancellationToken).ConfigureAwait(false); } catch { // ignore } } public async Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_startedListening); // if this end-point is already disconnected do not log more errors: var logError = _disconnectedReason == null; try { return await _rpc.InvokeWithCancellationAsync<T>(targetName, arguments, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, cancellationToken)) { // Remote call may fail with different exception even when our cancellation token is signaled // (e.g. on shutdown if the connection is dropped): cancellationToken.ThrowIfCancellationRequested(); throw CreateSoftCrashException(ex, cancellationToken); } } /// <summary> /// Invokes a remote method <paramref name="targetName"/> with specified <paramref name="arguments"/> and /// establishes a pipe through which the target method may transfer large binary data. The name of the pipe is /// passed to the target method as an additional argument following the specified <paramref name="arguments"/>. /// The target method is expected to use /// <see cref="WriteDataToNamedPipeAsync{TData}(string, TData, Func{Stream, TData, CancellationToken, Task}, CancellationToken)"/> /// to write the data to the pipe stream. /// </summary> public async Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>> dataReader, CancellationToken cancellationToken) { const int BufferSize = 12 * 1024; Contract.ThrowIfFalse(_startedListening); // if this end-point is already disconnected do not log more errors: var logError = _disconnectedReason == null; // Create a separate cancellation token for the reader, which we keep open until after the call to invoke // completes. If we close the reader before cancellation is processed by the remote call, it might block // (deadlock) while writing to a stream which is no longer processing data. using var readerCancellationSource = new CancellationTokenSource(); var pipeName = Guid.NewGuid().ToString(); var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, maxNumberOfServerInstances: 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); try { // send request to asset source var task = _rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(pipeName).ToArray(), cancellationToken); // if invoke throws an exception, make sure we raise cancellation. readerCancellationSource.CancelOnAbnormalCompletion(task); var task2 = Task.Run(async () => { // Transfer ownership of the pipe to BufferedStream, it will dispose it: using var stream = new BufferedStream(pipe, BufferSize); // wait for asset source to respond await pipe.WaitForConnectionAsync(readerCancellationSource.Token).ConfigureAwait(false); // run user task with direct stream return await dataReader(stream, readerCancellationSource.Token).ConfigureAwait(false); }, readerCancellationSource.Token); // Wait for all tasks to finish. If we return while one of the tasks is still in flight, the task would // operate as a fire-and-forget operation where the caller might release state objects still in use by // the task. await Task.WhenAll(task, task2).ConfigureAwait(false); Debug.Assert(task2.Status == TaskStatus.RanToCompletion); return task2.Result; } catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, readerCancellationSource.Token, cancellationToken)) { // Remote call may fail with different exception even when our cancellation token is signaled // (e.g. on shutdown if the connection is dropped). // It's important to use cancelationToken here rather than linked token as there is a slight // delay in between linked token being signaled and cancellation token being signaled. cancellationToken.ThrowIfCancellationRequested(); throw CreateSoftCrashException(ex, cancellationToken); } } public static Task WriteDataToNamedPipeAsync<TData>(string pipeName, TData data, Func<ObjectWriter, TData, CancellationToken, Task> dataWriter, CancellationToken cancellationToken) => WriteDataToNamedPipeAsync(pipeName, data, async (stream, data, cancellationToken) => { using var objectWriter = new ObjectWriter(stream, leaveOpen: true, cancellationToken); await dataWriter(objectWriter, data, cancellationToken).ConfigureAwait(false); }, cancellationToken); public static async Task WriteDataToNamedPipeAsync<TData>(string pipeName, TData data, Func<Stream, TData, CancellationToken, Task> dataWriter, CancellationToken cancellationToken) { const int BufferSize = 4 * 1024; try { var pipe = new NamedPipeClientStream(serverName: ".", pipeName, PipeDirection.Out); var success = false; try { await ConnectPipeAsync(pipe, cancellationToken).ConfigureAwait(false); success = true; } finally { if (!success) { pipe.Dispose(); } } // Transfer ownership of the pipe to BufferedStream, it will dispose it: using var stream = new BufferedStream(pipe, BufferSize); await dataWriter(stream, data, cancellationToken).ConfigureAwait(false); await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } catch (Exception) when (cancellationToken.IsCancellationRequested) { // The stream has closed before we had chance to check cancellation. cancellationToken.ThrowIfCancellationRequested(); } } private static async Task ConnectPipeAsync(NamedPipeClientStream pipe, CancellationToken cancellationToken) { const int ConnectWithoutTimeout = 1; const int MaxRetryAttemptsForFileNotFoundException = 3; const int ErrorSemTimeoutHResult = unchecked((int)0x80070079); var connectRetryInterval = TimeSpan.FromMilliseconds(20); var retryCount = 0; while (true) { try { // Try connecting without wait. // Connecting with anything else will consume CPU causing a spin wait. pipe.Connect(ConnectWithoutTimeout); return; } catch (ObjectDisposedException) { // Prefer to throw OperationCanceledException if the caller requested cancellation. cancellationToken.ThrowIfCancellationRequested(); throw; } catch (IOException ex) when (ex.HResult == ErrorSemTimeoutHResult) { // Ignore and retry. } catch (TimeoutException) { // Ignore and retry. } catch (FileNotFoundException) when (retryCount < MaxRetryAttemptsForFileNotFoundException) { // Ignore and retry retryCount++; } cancellationToken.ThrowIfCancellationRequested(); await Task.Delay(connectRetryInterval, cancellationToken).ConfigureAwait(false); } } private static bool ReportUnlessCanceled(Exception ex, CancellationToken linkedCancellationToken, CancellationToken cancellationToken) { // check whether we are in cancellation mode // things are either cancelled by us (cancellationToken) or cancelled by OOP (linkedCancellationToken). // "cancelled by us" means operation user invoked is cancelled by another user action such as explicit cancel, or typing. // "cancelled by OOP" means operation user invoked is cancelled due to issue on OOP such as user killed OOP process. if (cancellationToken.IsCancellationRequested) { // we are under our own cancellation, we don't care what the exception is. // due to the way we do cancellation (forcefully closing connection in the middle of reading/writing) // various exceptions can be thrown. for example, if we close our own named pipe stream in the middle of // object reader/writer using it, we could get invalid operation exception or invalid cast exception. return true; } if (linkedCancellationToken.IsCancellationRequested) { // Connection can be closed when the remote process is killed. // That will manifest as remote token cancellation. return true; } ReportNonFatalWatson(ex); return true; } private static bool ReportUnlessCanceled(Exception ex, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { ReportNonFatalWatson(ex); } return true; } private static void ReportNonFatalWatson(Exception exception) { FatalError.ReportAndCatch(exception); } private SoftCrashException CreateSoftCrashException(Exception ex, CancellationToken cancellationToken) { // TODO: revisit https://github.com/dotnet/roslyn/issues/40476 // We are getting unexpected exception from service hub. Rather than doing hard crash on unexpected exception, // we decided to do soft crash where we show info bar to users saying "VS got corrupted and users should save // their works and close VS" UnexpectedExceptionThrown?.Invoke(ex); // throw soft crash exception return new SoftCrashException(UnexpectedExceptionLogMessage, ex, cancellationToken); } private void LogError(string message) { var currentProcess = Process.GetCurrentProcess(); _logger.TraceEvent(TraceEventType.Error, _id, $" [{currentProcess.ProcessName}:{currentProcess.Id}] {message}"); } private void LogDisconnectInfo(JsonRpcDisconnectedEventArgs? e) { if (e != null) { LogError($@"Stream disconnected unexpectedly: {e.Reason}, '{e.Description}', Exception: {e.Exception?.Message}"); } } /// <summary> /// Handle disconnection event, so that we detect disconnection as soon as it happens /// without waiting for the next failing remote call. The remote call may not happen /// if there is an issue with the connection. E.g. the client end point might not receive /// a callback from server, or the server end point might not receive a call from client. /// </summary> private void OnDisconnected(object? sender, JsonRpcDisconnectedEventArgs e) { _disconnectedReason = e; // Don't log info in cases that are common - such as if we dispose the connection or the remote host process shuts down. if (e.Reason != DisconnectedReason.LocallyDisposed && e.Reason != DisconnectedReason.RemotePartyTerminated) { LogDisconnectInfo(e); } Disconnected?.Invoke(e); } } }
// 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.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Helper type that abstract out JsonRpc communication with extra capability of /// using raw stream to move over big chunk of data /// </summary> internal sealed class RemoteEndPoint : IDisposable { private const string UnexpectedExceptionLogMessage = "Unexpected exception from JSON-RPC"; private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new JsonRpcTargetOptions() { // Do not allow JSON-RPC to automatically subscribe to events and remote their calls. NotifyClientOfEvents = false, // Only allow public methods (may be on internal types) to be invoked remotely. AllowNonPublicInvocation = false }; private static int s_id; private readonly int _id; private readonly TraceSource _logger; private readonly JsonRpc _rpc; private bool _startedListening; private JsonRpcDisconnectedEventArgs? _disconnectedReason; public event Action<JsonRpcDisconnectedEventArgs>? Disconnected; public event Action<Exception>? UnexpectedExceptionThrown; public RemoteEndPoint(Stream stream, TraceSource logger, object? incomingCallTarget, IEnumerable<JsonConverter>? jsonConverters = null) { RoslynDebug.Assert(stream != null); RoslynDebug.Assert(logger != null); _id = Interlocked.Increment(ref s_id); _logger = logger; var jsonFormatter = new JsonMessageFormatter(); if (jsonConverters != null) { jsonFormatter.JsonSerializer.Converters.AddRange(jsonConverters); } jsonFormatter.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance); _rpc = new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter)) { CancelLocallyInvokedMethodsWhenConnectionIsClosed = true, TraceSource = logger, ExceptionStrategy = ExceptionProcessing.ISerializable, }; if (incomingCallTarget != null) { _rpc.AddLocalRpcTarget(incomingCallTarget, s_jsonRpcTargetOptions); } _rpc.Disconnected += OnDisconnected; } /// <summary> /// Must be called before any communication commences. /// See https://github.com/dotnet/roslyn/issues/16900#issuecomment-277378950. /// </summary> public void StartListening() { _rpc.StartListening(); _startedListening = true; } public bool IsDisposed => _rpc.IsDisposed; public void Dispose() { _rpc.Disconnected -= OnDisconnected; _rpc.Dispose(); } public async Task InvokeAsync(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_startedListening); // if this end-point is already disconnected do not log more errors: var logError = _disconnectedReason == null; try { await _rpc.InvokeWithCancellationAsync(targetName, arguments, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, cancellationToken)) { // Remote call may fail with different exception even when our cancellation token is signaled // (e.g. on shutdown if the connection is dropped): cancellationToken.ThrowIfCancellationRequested(); throw CreateSoftCrashException(ex, cancellationToken); } } public async Task TryInvokeAsync(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_startedListening); if (_rpc.IsDisposed) { return; } try { await _rpc.InvokeWithCancellationAsync(targetName, arguments, cancellationToken).ConfigureAwait(false); } catch { // ignore } } public async Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken) { Contract.ThrowIfFalse(_startedListening); // if this end-point is already disconnected do not log more errors: var logError = _disconnectedReason == null; try { return await _rpc.InvokeWithCancellationAsync<T>(targetName, arguments, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, cancellationToken)) { // Remote call may fail with different exception even when our cancellation token is signaled // (e.g. on shutdown if the connection is dropped): cancellationToken.ThrowIfCancellationRequested(); throw CreateSoftCrashException(ex, cancellationToken); } } /// <summary> /// Invokes a remote method <paramref name="targetName"/> with specified <paramref name="arguments"/> and /// establishes a pipe through which the target method may transfer large binary data. The name of the pipe is /// passed to the target method as an additional argument following the specified <paramref name="arguments"/>. /// The target method is expected to use /// <see cref="WriteDataToNamedPipeAsync{TData}(string, TData, Func{Stream, TData, CancellationToken, Task}, CancellationToken)"/> /// to write the data to the pipe stream. /// </summary> public async Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>> dataReader, CancellationToken cancellationToken) { const int BufferSize = 12 * 1024; Contract.ThrowIfFalse(_startedListening); // if this end-point is already disconnected do not log more errors: var logError = _disconnectedReason == null; // Create a separate cancellation token for the reader, which we keep open until after the call to invoke // completes. If we close the reader before cancellation is processed by the remote call, it might block // (deadlock) while writing to a stream which is no longer processing data. using var readerCancellationSource = new CancellationTokenSource(); var pipeName = Guid.NewGuid().ToString(); var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, maxNumberOfServerInstances: 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); try { // send request to asset source var task = _rpc.InvokeWithCancellationAsync(targetName, arguments.Concat(pipeName).ToArray(), cancellationToken); // if invoke throws an exception, make sure we raise cancellation. readerCancellationSource.CancelOnAbnormalCompletion(task); var task2 = Task.Run(async () => { // Transfer ownership of the pipe to BufferedStream, it will dispose it: using var stream = new BufferedStream(pipe, BufferSize); // wait for asset source to respond await pipe.WaitForConnectionAsync(readerCancellationSource.Token).ConfigureAwait(false); // run user task with direct stream return await dataReader(stream, readerCancellationSource.Token).ConfigureAwait(false); }, readerCancellationSource.Token); // Wait for all tasks to finish. If we return while one of the tasks is still in flight, the task would // operate as a fire-and-forget operation where the caller might release state objects still in use by // the task. await Task.WhenAll(task, task2).ConfigureAwait(false); Debug.Assert(task2.Status == TaskStatus.RanToCompletion); return task2.Result; } catch (Exception ex) when (!logError || ReportUnlessCanceled(ex, readerCancellationSource.Token, cancellationToken)) { // Remote call may fail with different exception even when our cancellation token is signaled // (e.g. on shutdown if the connection is dropped). // It's important to use cancelationToken here rather than linked token as there is a slight // delay in between linked token being signaled and cancellation token being signaled. cancellationToken.ThrowIfCancellationRequested(); throw CreateSoftCrashException(ex, cancellationToken); } } public static Task WriteDataToNamedPipeAsync<TData>(string pipeName, TData data, Func<ObjectWriter, TData, CancellationToken, Task> dataWriter, CancellationToken cancellationToken) => WriteDataToNamedPipeAsync(pipeName, data, async (stream, data, cancellationToken) => { using var objectWriter = new ObjectWriter(stream, leaveOpen: true, cancellationToken); await dataWriter(objectWriter, data, cancellationToken).ConfigureAwait(false); }, cancellationToken); public static async Task WriteDataToNamedPipeAsync<TData>(string pipeName, TData data, Func<Stream, TData, CancellationToken, Task> dataWriter, CancellationToken cancellationToken) { const int BufferSize = 4 * 1024; try { var pipe = new NamedPipeClientStream(serverName: ".", pipeName, PipeDirection.Out); var success = false; try { await ConnectPipeAsync(pipe, cancellationToken).ConfigureAwait(false); success = true; } finally { if (!success) { pipe.Dispose(); } } // Transfer ownership of the pipe to BufferedStream, it will dispose it: using var stream = new BufferedStream(pipe, BufferSize); await dataWriter(stream, data, cancellationToken).ConfigureAwait(false); await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } catch (Exception) when (cancellationToken.IsCancellationRequested) { // The stream has closed before we had chance to check cancellation. cancellationToken.ThrowIfCancellationRequested(); } } private static async Task ConnectPipeAsync(NamedPipeClientStream pipe, CancellationToken cancellationToken) { const int ConnectWithoutTimeout = 1; const int MaxRetryAttemptsForFileNotFoundException = 3; const int ErrorSemTimeoutHResult = unchecked((int)0x80070079); var connectRetryInterval = TimeSpan.FromMilliseconds(20); var retryCount = 0; while (true) { try { // Try connecting without wait. // Connecting with anything else will consume CPU causing a spin wait. pipe.Connect(ConnectWithoutTimeout); return; } catch (ObjectDisposedException) { // Prefer to throw OperationCanceledException if the caller requested cancellation. cancellationToken.ThrowIfCancellationRequested(); throw; } catch (IOException ex) when (ex.HResult == ErrorSemTimeoutHResult) { // Ignore and retry. } catch (TimeoutException) { // Ignore and retry. } catch (FileNotFoundException) when (retryCount < MaxRetryAttemptsForFileNotFoundException) { // Ignore and retry retryCount++; } cancellationToken.ThrowIfCancellationRequested(); await Task.Delay(connectRetryInterval, cancellationToken).ConfigureAwait(false); } } private static bool ReportUnlessCanceled(Exception ex, CancellationToken linkedCancellationToken, CancellationToken cancellationToken) { // check whether we are in cancellation mode // things are either cancelled by us (cancellationToken) or cancelled by OOP (linkedCancellationToken). // "cancelled by us" means operation user invoked is cancelled by another user action such as explicit cancel, or typing. // "cancelled by OOP" means operation user invoked is cancelled due to issue on OOP such as user killed OOP process. if (cancellationToken.IsCancellationRequested) { // we are under our own cancellation, we don't care what the exception is. // due to the way we do cancellation (forcefully closing connection in the middle of reading/writing) // various exceptions can be thrown. for example, if we close our own named pipe stream in the middle of // object reader/writer using it, we could get invalid operation exception or invalid cast exception. return true; } if (linkedCancellationToken.IsCancellationRequested) { // Connection can be closed when the remote process is killed. // That will manifest as remote token cancellation. return true; } ReportNonFatalWatson(ex); return true; } private static bool ReportUnlessCanceled(Exception ex, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { ReportNonFatalWatson(ex); } return true; } private static void ReportNonFatalWatson(Exception exception) { FatalError.ReportAndCatch(exception); } private SoftCrashException CreateSoftCrashException(Exception ex, CancellationToken cancellationToken) { // TODO: revisit https://github.com/dotnet/roslyn/issues/40476 // We are getting unexpected exception from service hub. Rather than doing hard crash on unexpected exception, // we decided to do soft crash where we show info bar to users saying "VS got corrupted and users should save // their works and close VS" UnexpectedExceptionThrown?.Invoke(ex); // throw soft crash exception return new SoftCrashException(UnexpectedExceptionLogMessage, ex, cancellationToken); } private void LogError(string message) { var currentProcess = Process.GetCurrentProcess(); _logger.TraceEvent(TraceEventType.Error, _id, $" [{currentProcess.ProcessName}:{currentProcess.Id}] {message}"); } private void LogDisconnectInfo(JsonRpcDisconnectedEventArgs? e) { if (e != null) { LogError($@"Stream disconnected unexpectedly: {e.Reason}, '{e.Description}', Exception: {e.Exception?.Message}"); } } /// <summary> /// Handle disconnection event, so that we detect disconnection as soon as it happens /// without waiting for the next failing remote call. The remote call may not happen /// if there is an issue with the connection. E.g. the client end point might not receive /// a callback from server, or the server end point might not receive a call from client. /// </summary> private void OnDisconnected(object? sender, JsonRpcDisconnectedEventArgs e) { _disconnectedReason = e; // Don't log info in cases that are common - such as if we dispose the connection or the remote host process shuts down. if (e.Reason != DisconnectedReason.LocallyDisposed && e.Reason != DisconnectedReason.RemotePartyTerminated) { LogDisconnectInfo(e); } Disconnected?.Invoke(e); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitlyTypeArraysTests.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitlyTypeArraysTests : SemanticModelTestBase { #region "Functionality tests" [Fact] public void ImplicitlyTypedArrayLocal() { var compilation = CreateCompilation(@" class M {} class C { public void F() { var a = new[] { new M() }; } } "); compilation.VerifyDiagnostics(); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("F").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var locDecl = (BoundLocalDeclaration)block.Statements.Single(); var localA = (ArrayTypeSymbol)locDecl.DeclaredTypeOpt.Display; var typeM = compilation.GlobalNamespace.GetMember<TypeSymbol>("M"); Assert.Equal(typeM, localA.ElementType); } [Fact] public void ImplicitlyTypedArray_BindArrayInitializer() { var text = @" class C { public void F() { var a = ""; var b = new[] { ""hello"", /*<bind>*/ a /*</bind>*/, null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Local, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.NotNull(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ImplicitlyTypedArray_BindImplicitlyTypedLocal() { var text = @" class C { public void F() { /*<bind>*/ var a /*</bind>*/ = new[] { ""hello"", "", null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String[]", symInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.ArrayType, symInfo.Symbol.Kind); var typeInfo = model.GetTypeInfo(expr); Assert.NotNull(typeInfo.Type); Assert.NotNull(typeInfo.ConvertedType); } #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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitlyTypeArraysTests : SemanticModelTestBase { #region "Functionality tests" [Fact] public void ImplicitlyTypedArrayLocal() { var compilation = CreateCompilation(@" class M {} class C { public void F() { var a = new[] { new M() }; } } "); compilation.VerifyDiagnostics(); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("F").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var locDecl = (BoundLocalDeclaration)block.Statements.Single(); var localA = (ArrayTypeSymbol)locDecl.DeclaredTypeOpt.Display; var typeM = compilation.GlobalNamespace.GetMember<TypeSymbol>("M"); Assert.Equal(typeM, localA.ElementType); } [Fact] public void ImplicitlyTypedArray_BindArrayInitializer() { var text = @" class C { public void F() { var a = ""; var b = new[] { ""hello"", /*<bind>*/ a /*</bind>*/, null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Local, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.NotNull(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ImplicitlyTypedArray_BindImplicitlyTypedLocal() { var text = @" class C { public void F() { /*<bind>*/ var a /*</bind>*/ = new[] { ""hello"", "", null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String[]", symInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.ArrayType, symInfo.Symbol.Kind); var typeInfo = model.GetTypeInfo(expr); Assert.NotNull(typeInfo.Type); Assert.NotNull(typeInfo.ConvertedType); } #endregion } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Core/Portable/DiaSymReader/Metadata/MetadataImportFieldOffset.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; namespace Microsoft.DiaSymReader { [StructLayout(LayoutKind.Sequential)] internal struct MetadataImportFieldOffset { public int FieldDef; public uint Offset; } }
// 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; namespace Microsoft.DiaSymReader { [StructLayout(LayoutKind.Sequential)] internal struct MetadataImportFieldOffset { public int FieldDef; public uint Offset; } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Core/Portable/PEWriter/Types.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.CodeAnalysis; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Symbols; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal enum PlatformType { SystemObject = CodeAnalysis.SpecialType.System_Object, SystemDecimal = CodeAnalysis.SpecialType.System_Decimal, SystemTypedReference = CodeAnalysis.SpecialType.System_TypedReference, SystemType = CodeAnalysis.WellKnownType.System_Type, SystemInt32 = CodeAnalysis.SpecialType.System_Int32, SystemVoid = CodeAnalysis.SpecialType.System_Void, SystemString = CodeAnalysis.SpecialType.System_String, } /// <summary> /// This interface models the metadata representation of an array type reference. /// </summary> internal interface IArrayTypeReference : ITypeReference { /// <summary> /// The type of the elements of this array. /// </summary> ITypeReference GetElementType(EmitContext context); /// <summary> /// This type of array is a single dimensional array with zero lower bound for index values. /// </summary> bool IsSZArray { get; // ^ ensures result ==> Rank == 1; } /// <summary> /// A possibly empty list of lower bounds for dimension indices. When not explicitly specified, a lower bound defaults to zero. /// The first lower bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// </summary> ImmutableArray<int> LowerBounds { get; // ^ ensures count(result) <= Rank; } /// <summary> /// The number of array dimensions. /// </summary> int Rank { get; // ^ ensures result > 0; } /// <summary> /// A possible empty list of upper bounds for dimension indices. /// The first upper bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// An unspecified upper bound means that instances of this type can have an arbitrary upper bound for that dimension. /// </summary> ImmutableArray<int> Sizes { get; // ^ ensures count(result) <= Rank; } } /// <summary> /// Modifies the set of allowed values for a type, or the semantics of operations allowed on those values. /// Custom modifiers are not associated directly with types, but rather with typed storage locations for values. /// </summary> internal interface ICustomModifier { /// <summary> /// If true, a language may use the modified storage location without being aware of the meaning of the modification. /// </summary> bool IsOptional { get; } /// <summary> /// A type used as a tag that indicates which type of modification applies to the storage location. /// </summary> ITypeReference GetModifier(EmitContext context); } /// <summary> /// Information that describes a method or property parameter, but does not include all the information in a IParameterDefinition. /// </summary> internal interface IParameterTypeInformation : IParameterListEntry { /// <summary> /// The list of custom modifiers, if any, associated with the parameter type. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the ref modifier. /// </summary> ImmutableArray<ICustomModifier> RefCustomModifiers { get; } /// <summary> /// True if the parameter is passed by reference (using a managed pointer). /// </summary> bool IsByReference { get; } /// <summary> /// The type of argument value that corresponds to this parameter. /// </summary> ITypeReference GetType(EmitContext context); } /// <summary> /// The definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameter : IGenericParameterReference { /// <summary> /// A list of classes or interfaces. All type arguments matching this parameter must be derived from all of the classes and implement all of the interfaces. /// </summary> IEnumerable<TypeReferenceWithAttributes> GetConstraints(EmitContext context); /// <summary> /// True if all type arguments matching this parameter are constrained to be reference types. /// </summary> bool MustBeReferenceType { get; // ^ ensures result ==> !this.MustBeValueType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types. /// </summary> bool MustBeValueType { get; // ^ ensures result ==> !this.MustBeReferenceType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types or concrete classes with visible default constructors. /// </summary> bool MustHaveDefaultConstructor { get; } /// <summary> /// Indicates if the generic type or method with this type parameter is co-, contra-, or non variant with respect to this type parameter. /// </summary> TypeParameterVariance Variance { get; } IGenericMethodParameter? AsGenericMethodParameter { get; } IGenericTypeParameter? AsGenericTypeParameter { get; } } /// <summary> /// A reference to the definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameterReference : ITypeReference, INamedEntity, IParameterListEntry { } /// <summary> /// The definition of a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameter : IGenericParameter, IGenericMethodParameterReference { /// <summary> /// The generic method that defines this type parameter. /// </summary> new IMethodDefinition DefiningMethod { get; // ^ ensures result.IsGeneric; } } /// <summary> /// A reference to a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic method that defines the referenced type parameter. /// </summary> IMethodReference DefiningMethod { get; } } /// <summary> /// A generic type instantiated with a list of type arguments /// </summary> internal interface IGenericTypeInstanceReference : ITypeReference { /// <summary> /// The type arguments that were used to instantiate this.GenericType in order to create this type. /// </summary> ImmutableArray<ITypeReference> GetGenericArguments(EmitContext context); // ^ ensures result.GetEnumerator().MoveNext(); // The collection is always non empty. /// <summary> /// Returns the generic type of which this type is an instance. /// Equivalent to Symbol.OriginalDefinition /// </summary> INamedTypeReference GetGenericType(EmitContext context); // ^ ensures result.ResolvedType.IsGeneric; } /// <summary> /// The definition of a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameter : IGenericParameter, IGenericTypeParameterReference { /// <summary> /// The generic type that defines this type parameter. /// </summary> new ITypeDefinition DefiningType { get; } } /// <summary> /// A reference to a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic type that defines the referenced type parameter. /// </summary> ITypeReference DefiningType { get; } } /// <summary> /// A reference to a named type, such as an INamespaceTypeReference or an INestedTypeReference. /// </summary> internal interface INamedTypeReference : ITypeReference, INamedEntity { /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { get; } /// <summary> /// If true, the persisted type name is mangled by appending "`n" where n is the number of type parameters, if the number of type parameters is greater than 0. /// </summary> bool MangleName { get; } } /// <summary> /// A named type definition, such as an INamespaceTypeDefinition or an INestedTypeDefinition. /// </summary> internal interface INamedTypeDefinition : ITypeDefinition, INamedTypeReference { } /// <summary> /// A type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeDefinition : INamedTypeDefinition, INamespaceTypeReference { /// <summary> /// True if the type can be accessed from other assemblies. /// </summary> bool IsPublic { get; } } /// <summary> /// Represents a namespace. /// </summary> internal interface INamespace : INamedEntity { /// <summary> /// Containing namespace or null if this namespace is global. /// </summary> INamespace ContainingNamespace { get; } /// <summary> /// Returns underlying internal symbol object, if any. /// </summary> INamespaceSymbolInternal GetInternalSymbol(); } /// <summary> /// A reference to a type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeReference : INamedTypeReference { /// <summary> /// A reference to the unit that defines the referenced type. /// </summary> IUnitReference GetUnit(EmitContext context); /// <summary> /// Fully qualified name of the containing namespace. /// </summary> string NamespaceName { get; } } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeDefinition : INamedTypeDefinition, ITypeDefinitionMember, INestedTypeReference { } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeReference : INamedTypeReference, ITypeMemberReference { } /// <summary> /// A reference to a type definition that is a specialized nested type. /// </summary> internal interface ISpecializedNestedTypeReference : INestedTypeReference { /// <summary> /// A reference to the nested type that has been specialized to obtain this nested type reference. When the containing type is an instance of type which is itself a specialized member (i.e. it is a nested /// type of a generic type instance), then the unspecialized member refers to a member from the unspecialized containing type. (I.e. the unspecialized member always /// corresponds to a definition that is not obtained via specialization.) /// </summary> [return: NotNull] INestedTypeReference GetUnspecializedVersion(EmitContext context); } /// <summary> /// Models an explicit implementation or override of a base class virtual method or an explicit implementation of an interface method. /// </summary> internal struct MethodImplementation { /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public readonly Cci.IMethodDefinition ImplementingMethod; /// <summary> /// A reference to the method that provides the implementation. /// </summary> public readonly Cci.IMethodReference ImplementedMethod; public MethodImplementation(Cci.IMethodDefinition ImplementingMethod, Cci.IMethodReference ImplementedMethod) { this.ImplementingMethod = ImplementingMethod; this.ImplementedMethod = ImplementedMethod; } /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public Cci.ITypeDefinition ContainingType { get { return ImplementingMethod.ContainingTypeDefinition; } } } /// <summary> /// A type reference that has custom modifiers associated with it. For example a reference to the target type of a managed pointer to a constant. /// </summary> internal interface IModifiedTypeReference : ITypeReference { /// <summary> /// Returns the list of custom modifiers associated with the type reference. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// An unmodified type reference. /// </summary> ITypeReference UnmodifiedType { get; } } /// <summary> /// This interface models the metadata representation of a pointer to a location in unmanaged memory. /// </summary> internal interface IPointerTypeReference : ITypeReference { /// <summary> /// The type of value stored at the target memory location. /// </summary> ITypeReference GetTargetType(EmitContext context); } /// <summary> /// This interface models the metadata representation of a pointer to a function in unmanaged memory. /// </summary> internal interface IFunctionPointerTypeReference : ITypeReference { /// <summary> /// The signature of the function located at the target memory address. /// </summary> ISignature Signature { get; } } /// <summary> /// A type ref with attributes attached directly to the type reference /// itself. Unlike <see cref="IReference.GetAttributes(EmitContext)"/> a /// <see cref="TypeReferenceWithAttributes"/> will never provide attributes /// for the "pointed at" declaration, and all attributes will be emitted /// directly on the type ref, rather than the declaration. /// </summary> // TODO(https://github.com/dotnet/roslyn/issues/12677): // Consider: This is basically just a work-around for our overly loose // interpretation of IReference and IDefinition. This type would probably // be unnecessary if we added a GetAttributes method onto IDefinition and // properly segregated attributes that are on type references and attributes // that are on underlying type definitions. internal struct TypeReferenceWithAttributes { /// <summary> /// The type reference. /// </summary> public ITypeReference TypeRef { get; } /// <summary> /// The attributes on the type reference itself. /// </summary> public ImmutableArray<ICustomAttribute> Attributes { get; } public TypeReferenceWithAttributes( ITypeReference typeRef, ImmutableArray<ICustomAttribute> attributes = default(ImmutableArray<ICustomAttribute>)) { TypeRef = typeRef; Attributes = attributes.NullToEmpty(); } } /// <summary> /// This interface models the metadata representation of a type. /// </summary> internal interface ITypeDefinition : IDefinition, ITypeReference { /// <summary> /// The byte alignment that values of the given type ought to have. Must be a power of 2. If zero, the alignment is decided at runtime. /// </summary> ushort Alignment { get; } /// <summary> /// Returns null for interfaces and System.Object. /// </summary> ITypeReference? GetBaseClass(EmitContext context); // ^ ensures result == null || result.ResolvedType.IsClass; /// <summary> /// Zero or more events defined by this type. /// </summary> IEnumerable<IEventDefinition> GetEvents(EmitContext context); /// <summary> /// Zero or more implementation overrides provided by the class. /// </summary> IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context); /// <summary> /// Zero or more fields defined by this type. /// </summary> IEnumerable<IFieldDefinition> GetFields(EmitContext context); /// <summary> /// Zero or more parameters that can be used as type annotations. /// </summary> IEnumerable<IGenericTypeParameter> GenericParameters { get; // ^ requires this.IsGeneric; } /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { // TODO: remove this get; // ^ ensures !this.IsGeneric ==> result == 0; // ^ ensures this.IsGeneric ==> result > 0; } /// <summary> /// True if this type has a non empty collection of SecurityAttributes or the System.Security.SuppressUnmanagedCodeSecurityAttribute. /// </summary> bool HasDeclarativeSecurity { get; } /// <summary> /// Zero or more interfaces implemented by this type. /// </summary> IEnumerable<TypeReferenceWithAttributes> Interfaces(EmitContext context); /// <summary> /// True if the type may not be instantiated. /// </summary> bool IsAbstract { get; } /// <summary> /// Is type initialized anytime before first access to static field /// </summary> bool IsBeforeFieldInit { get; } /// <summary> /// Is this imported from COM type library /// </summary> bool IsComObject { get; } /// <summary> /// True if this type is parameterized (this.GenericParameters is a non empty collection). /// </summary> bool IsGeneric { get; } /// <summary> /// True if the type is an interface. /// </summary> bool IsInterface { get; } /// <summary> /// True if the type is a delegate. /// </summary> bool IsDelegate { get; } /// <summary> /// True if this type gets special treatment from the runtime. /// </summary> bool IsRuntimeSpecial { get; } /// <summary> /// True if this type is serializable. /// </summary> bool IsSerializable { get; } /// <summary> /// True if the type has special name. /// </summary> bool IsSpecialName { get; } /// <summary> /// True if the type is a Windows runtime type. /// </summary> /// <remarks> /// A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. /// WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. /// This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. /// These two assemblies are special as they implement the CLR's support for WinRT. /// </remarks> bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type may not be subtyped. /// </summary> bool IsSealed { get; } /// <summary> /// Layout of the type. /// </summary> LayoutKind Layout { get; } /// <summary> /// Zero or more methods defined by this type. /// </summary> IEnumerable<IMethodDefinition> GetMethods(EmitContext context); /// <summary> /// Zero or more nested types defined by this type. /// </summary> IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context); /// <summary> /// Zero or more properties defined by this type. /// </summary> IEnumerable<IPropertyDefinition> GetProperties(EmitContext context); /// <summary> /// Declarative security actions for this type. Will be empty if this.HasSecurity is false. /// </summary> IEnumerable<SecurityAttribute> SecurityAttributes { get; } /// <summary> /// Size of an object of this type. In bytes. If zero, the size is unspecified and will be determined at runtime. /// </summary> uint SizeOf { get; } /// <summary> /// Default marshalling of the Strings in this class. /// </summary> CharSet StringFormat { get; } } /// <summary> /// A reference to a type. /// </summary> internal interface ITypeReference : IReference { /// <summary> /// True if the type is an enumeration (it extends System.Enum and is sealed). Corresponds to C# enum. /// </summary> bool IsEnum { get; } /// <summary> /// True if the type is a value type. /// Value types are sealed and extend System.ValueType or System.Enum. /// A type parameter for which MustBeValueType (the struct constraint in C#) is true also returns true for this property. /// </summary> bool IsValueType { get; } /// <summary> /// The type definition being referred to. /// </summary> ITypeDefinition? GetResolvedType(EmitContext context); /// <summary> /// Unless the value of TypeCode is PrimitiveTypeCode.NotPrimitive, the type corresponds to a "primitive" CLR type (such as System.Int32) and /// the type code identifies which of the primitive types it corresponds to. /// </summary> PrimitiveTypeCode TypeCode { get; } /// <summary> /// TypeDefs defined in modules linked to the assembly being emitted are listed in the ExportedTypes table. /// </summary> TypeDefinitionHandle TypeDef { get; } IGenericMethodParameterReference? AsGenericMethodParameterReference { get; } IGenericTypeInstanceReference? AsGenericTypeInstanceReference { get; } IGenericTypeParameterReference? AsGenericTypeParameterReference { get; } INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context); INamespaceTypeReference? AsNamespaceTypeReference { get; } INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context); INestedTypeReference? AsNestedTypeReference { get; } ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference { get; } ITypeDefinition? AsTypeDefinition(EmitContext context); } /// <summary> /// A enumeration of all of the value types that are built into the Runtime (and thus have specialized IL instructions that manipulate them). /// </summary> internal enum PrimitiveTypeCode { /// <summary> /// A single bit. /// </summary> Boolean, /// <summary> /// An unsigned 16 bit integer representing a Unicode UTF16 code point. /// </summary> Char, /// <summary> /// A signed 8 bit integer. /// </summary> Int8, /// <summary> /// A 32 bit IEEE floating point number. /// </summary> Float32, /// <summary> /// A 64 bit IEEE floating point number. /// </summary> Float64, /// <summary> /// A signed 16 bit integer. /// </summary> Int16, /// <summary> /// A signed 32 bit integer. /// </summary> Int32, /// <summary> /// A signed 64 bit integer. /// </summary> Int64, /// <summary> /// A signed 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> IntPtr, /// <summary> /// A pointer to fixed or unmanaged memory. /// </summary> Pointer, /// <summary> /// A reference to managed memory. /// </summary> Reference, /// <summary> /// A string. /// </summary> String, /// <summary> /// An unsigned 8 bit integer. /// </summary> UInt8, /// <summary> /// An unsigned 16 bit integer. /// </summary> UInt16, /// <summary> /// An unsigned 32 bit integer. /// </summary> UInt32, /// <summary> /// An unsigned 64 bit integer. /// </summary> UInt64, /// <summary> /// An unsigned 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> UIntPtr, /// <summary> /// A type that denotes the absence of a value. /// </summary> Void, /// <summary> /// Not a primitive type. /// </summary> NotPrimitive, /// <summary> /// A pointer to a function in fixed or managed memory. /// </summary> FunctionPointer, /// <summary> /// Type is a dummy type. /// </summary> Invalid, } /// <summary> /// Enumerates the different kinds of levels of visibility a type member can have. /// </summary> internal enum TypeMemberVisibility { /// <summary> /// The member is visible only within its own type. /// </summary> Private = 1, /// <summary> /// The member is visible only within the intersection of its family (its own type and any subtypes) and assembly. /// </summary> FamilyAndAssembly = 2, /// <summary> /// The member is visible only within its own assembly. /// </summary> Assembly = 3, /// <summary> /// The member is visible only within its own type and any subtypes. /// </summary> Family = 4, /// <summary> /// The member is visible only within the union of its family and assembly. /// </summary> FamilyOrAssembly = 5, /// <summary> /// The member is visible everywhere its declaring type is visible. /// </summary> Public = 6 } /// <summary> /// Enumerates the different kinds of variance a generic method or generic type parameter may have. /// </summary> internal enum TypeParameterVariance { /// <summary> /// Two type or method instances are compatible only if they have exactly the same type argument for this parameter. /// </summary> NonVariant = 0, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a subtype of the type the /// other instance has for this parameter. /// </summary> Covariant = 1, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a supertype of the type the /// other instance has for this parameter. /// </summary> Contravariant = 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. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Symbols; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal enum PlatformType { SystemObject = CodeAnalysis.SpecialType.System_Object, SystemDecimal = CodeAnalysis.SpecialType.System_Decimal, SystemTypedReference = CodeAnalysis.SpecialType.System_TypedReference, SystemType = CodeAnalysis.WellKnownType.System_Type, SystemInt32 = CodeAnalysis.SpecialType.System_Int32, SystemVoid = CodeAnalysis.SpecialType.System_Void, SystemString = CodeAnalysis.SpecialType.System_String, } /// <summary> /// This interface models the metadata representation of an array type reference. /// </summary> internal interface IArrayTypeReference : ITypeReference { /// <summary> /// The type of the elements of this array. /// </summary> ITypeReference GetElementType(EmitContext context); /// <summary> /// This type of array is a single dimensional array with zero lower bound for index values. /// </summary> bool IsSZArray { get; // ^ ensures result ==> Rank == 1; } /// <summary> /// A possibly empty list of lower bounds for dimension indices. When not explicitly specified, a lower bound defaults to zero. /// The first lower bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// </summary> ImmutableArray<int> LowerBounds { get; // ^ ensures count(result) <= Rank; } /// <summary> /// The number of array dimensions. /// </summary> int Rank { get; // ^ ensures result > 0; } /// <summary> /// A possible empty list of upper bounds for dimension indices. /// The first upper bound in the list corresponds to the first dimension. Dimensions cannot be skipped. /// An unspecified upper bound means that instances of this type can have an arbitrary upper bound for that dimension. /// </summary> ImmutableArray<int> Sizes { get; // ^ ensures count(result) <= Rank; } } /// <summary> /// Modifies the set of allowed values for a type, or the semantics of operations allowed on those values. /// Custom modifiers are not associated directly with types, but rather with typed storage locations for values. /// </summary> internal interface ICustomModifier { /// <summary> /// If true, a language may use the modified storage location without being aware of the meaning of the modification. /// </summary> bool IsOptional { get; } /// <summary> /// A type used as a tag that indicates which type of modification applies to the storage location. /// </summary> ITypeReference GetModifier(EmitContext context); } /// <summary> /// Information that describes a method or property parameter, but does not include all the information in a IParameterDefinition. /// </summary> internal interface IParameterTypeInformation : IParameterListEntry { /// <summary> /// The list of custom modifiers, if any, associated with the parameter type. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the ref modifier. /// </summary> ImmutableArray<ICustomModifier> RefCustomModifiers { get; } /// <summary> /// True if the parameter is passed by reference (using a managed pointer). /// </summary> bool IsByReference { get; } /// <summary> /// The type of argument value that corresponds to this parameter. /// </summary> ITypeReference GetType(EmitContext context); } /// <summary> /// The definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameter : IGenericParameterReference { /// <summary> /// A list of classes or interfaces. All type arguments matching this parameter must be derived from all of the classes and implement all of the interfaces. /// </summary> IEnumerable<TypeReferenceWithAttributes> GetConstraints(EmitContext context); /// <summary> /// True if all type arguments matching this parameter are constrained to be reference types. /// </summary> bool MustBeReferenceType { get; // ^ ensures result ==> !this.MustBeValueType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types. /// </summary> bool MustBeValueType { get; // ^ ensures result ==> !this.MustBeReferenceType; } /// <summary> /// True if all type arguments matching this parameter are constrained to be value types or concrete classes with visible default constructors. /// </summary> bool MustHaveDefaultConstructor { get; } /// <summary> /// Indicates if the generic type or method with this type parameter is co-, contra-, or non variant with respect to this type parameter. /// </summary> TypeParameterVariance Variance { get; } IGenericMethodParameter? AsGenericMethodParameter { get; } IGenericTypeParameter? AsGenericTypeParameter { get; } } /// <summary> /// A reference to the definition of a type parameter of a generic type or method. /// </summary> internal interface IGenericParameterReference : ITypeReference, INamedEntity, IParameterListEntry { } /// <summary> /// The definition of a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameter : IGenericParameter, IGenericMethodParameterReference { /// <summary> /// The generic method that defines this type parameter. /// </summary> new IMethodDefinition DefiningMethod { get; // ^ ensures result.IsGeneric; } } /// <summary> /// A reference to a type parameter of a generic method. /// </summary> internal interface IGenericMethodParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic method that defines the referenced type parameter. /// </summary> IMethodReference DefiningMethod { get; } } /// <summary> /// A generic type instantiated with a list of type arguments /// </summary> internal interface IGenericTypeInstanceReference : ITypeReference { /// <summary> /// The type arguments that were used to instantiate this.GenericType in order to create this type. /// </summary> ImmutableArray<ITypeReference> GetGenericArguments(EmitContext context); // ^ ensures result.GetEnumerator().MoveNext(); // The collection is always non empty. /// <summary> /// Returns the generic type of which this type is an instance. /// Equivalent to Symbol.OriginalDefinition /// </summary> INamedTypeReference GetGenericType(EmitContext context); // ^ ensures result.ResolvedType.IsGeneric; } /// <summary> /// The definition of a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameter : IGenericParameter, IGenericTypeParameterReference { /// <summary> /// The generic type that defines this type parameter. /// </summary> new ITypeDefinition DefiningType { get; } } /// <summary> /// A reference to a type parameter of a generic type. /// </summary> internal interface IGenericTypeParameterReference : IGenericParameterReference { /// <summary> /// A reference to the generic type that defines the referenced type parameter. /// </summary> ITypeReference DefiningType { get; } } /// <summary> /// A reference to a named type, such as an INamespaceTypeReference or an INestedTypeReference. /// </summary> internal interface INamedTypeReference : ITypeReference, INamedEntity { /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { get; } /// <summary> /// If true, the persisted type name is mangled by appending "`n" where n is the number of type parameters, if the number of type parameters is greater than 0. /// </summary> bool MangleName { get; } } /// <summary> /// A named type definition, such as an INamespaceTypeDefinition or an INestedTypeDefinition. /// </summary> internal interface INamedTypeDefinition : ITypeDefinition, INamedTypeReference { } /// <summary> /// A type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeDefinition : INamedTypeDefinition, INamespaceTypeReference { /// <summary> /// True if the type can be accessed from other assemblies. /// </summary> bool IsPublic { get; } } /// <summary> /// Represents a namespace. /// </summary> internal interface INamespace : INamedEntity { /// <summary> /// Containing namespace or null if this namespace is global. /// </summary> INamespace ContainingNamespace { get; } /// <summary> /// Returns underlying internal symbol object, if any. /// </summary> INamespaceSymbolInternal GetInternalSymbol(); } /// <summary> /// A reference to a type definition that is a member of a namespace definition. /// </summary> internal interface INamespaceTypeReference : INamedTypeReference { /// <summary> /// A reference to the unit that defines the referenced type. /// </summary> IUnitReference GetUnit(EmitContext context); /// <summary> /// Fully qualified name of the containing namespace. /// </summary> string NamespaceName { get; } } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeDefinition : INamedTypeDefinition, ITypeDefinitionMember, INestedTypeReference { } /// <summary> /// A type definition that is a member of another type definition. /// </summary> internal interface INestedTypeReference : INamedTypeReference, ITypeMemberReference { } /// <summary> /// A reference to a type definition that is a specialized nested type. /// </summary> internal interface ISpecializedNestedTypeReference : INestedTypeReference { /// <summary> /// A reference to the nested type that has been specialized to obtain this nested type reference. When the containing type is an instance of type which is itself a specialized member (i.e. it is a nested /// type of a generic type instance), then the unspecialized member refers to a member from the unspecialized containing type. (I.e. the unspecialized member always /// corresponds to a definition that is not obtained via specialization.) /// </summary> [return: NotNull] INestedTypeReference GetUnspecializedVersion(EmitContext context); } /// <summary> /// Models an explicit implementation or override of a base class virtual method or an explicit implementation of an interface method. /// </summary> internal struct MethodImplementation { /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public readonly Cci.IMethodDefinition ImplementingMethod; /// <summary> /// A reference to the method that provides the implementation. /// </summary> public readonly Cci.IMethodReference ImplementedMethod; public MethodImplementation(Cci.IMethodDefinition ImplementingMethod, Cci.IMethodReference ImplementedMethod) { this.ImplementingMethod = ImplementingMethod; this.ImplementedMethod = ImplementedMethod; } /// <summary> /// The type that is explicitly implementing or overriding the base class virtual method or explicitly implementing an interface method. /// </summary> public Cci.ITypeDefinition ContainingType { get { return ImplementingMethod.ContainingTypeDefinition; } } } /// <summary> /// A type reference that has custom modifiers associated with it. For example a reference to the target type of a managed pointer to a constant. /// </summary> internal interface IModifiedTypeReference : ITypeReference { /// <summary> /// Returns the list of custom modifiers associated with the type reference. /// </summary> ImmutableArray<ICustomModifier> CustomModifiers { get; } /// <summary> /// An unmodified type reference. /// </summary> ITypeReference UnmodifiedType { get; } } /// <summary> /// This interface models the metadata representation of a pointer to a location in unmanaged memory. /// </summary> internal interface IPointerTypeReference : ITypeReference { /// <summary> /// The type of value stored at the target memory location. /// </summary> ITypeReference GetTargetType(EmitContext context); } /// <summary> /// This interface models the metadata representation of a pointer to a function in unmanaged memory. /// </summary> internal interface IFunctionPointerTypeReference : ITypeReference { /// <summary> /// The signature of the function located at the target memory address. /// </summary> ISignature Signature { get; } } /// <summary> /// A type ref with attributes attached directly to the type reference /// itself. Unlike <see cref="IReference.GetAttributes(EmitContext)"/> a /// <see cref="TypeReferenceWithAttributes"/> will never provide attributes /// for the "pointed at" declaration, and all attributes will be emitted /// directly on the type ref, rather than the declaration. /// </summary> // TODO(https://github.com/dotnet/roslyn/issues/12677): // Consider: This is basically just a work-around for our overly loose // interpretation of IReference and IDefinition. This type would probably // be unnecessary if we added a GetAttributes method onto IDefinition and // properly segregated attributes that are on type references and attributes // that are on underlying type definitions. internal struct TypeReferenceWithAttributes { /// <summary> /// The type reference. /// </summary> public ITypeReference TypeRef { get; } /// <summary> /// The attributes on the type reference itself. /// </summary> public ImmutableArray<ICustomAttribute> Attributes { get; } public TypeReferenceWithAttributes( ITypeReference typeRef, ImmutableArray<ICustomAttribute> attributes = default(ImmutableArray<ICustomAttribute>)) { TypeRef = typeRef; Attributes = attributes.NullToEmpty(); } } /// <summary> /// This interface models the metadata representation of a type. /// </summary> internal interface ITypeDefinition : IDefinition, ITypeReference { /// <summary> /// The byte alignment that values of the given type ought to have. Must be a power of 2. If zero, the alignment is decided at runtime. /// </summary> ushort Alignment { get; } /// <summary> /// Returns null for interfaces and System.Object. /// </summary> ITypeReference? GetBaseClass(EmitContext context); // ^ ensures result == null || result.ResolvedType.IsClass; /// <summary> /// Zero or more events defined by this type. /// </summary> IEnumerable<IEventDefinition> GetEvents(EmitContext context); /// <summary> /// Zero or more implementation overrides provided by the class. /// </summary> IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context); /// <summary> /// Zero or more fields defined by this type. /// </summary> IEnumerable<IFieldDefinition> GetFields(EmitContext context); /// <summary> /// Zero or more parameters that can be used as type annotations. /// </summary> IEnumerable<IGenericTypeParameter> GenericParameters { get; // ^ requires this.IsGeneric; } /// <summary> /// The number of generic parameters. Zero if the type is not generic. /// </summary> ushort GenericParameterCount { // TODO: remove this get; // ^ ensures !this.IsGeneric ==> result == 0; // ^ ensures this.IsGeneric ==> result > 0; } /// <summary> /// True if this type has a non empty collection of SecurityAttributes or the System.Security.SuppressUnmanagedCodeSecurityAttribute. /// </summary> bool HasDeclarativeSecurity { get; } /// <summary> /// Zero or more interfaces implemented by this type. /// </summary> IEnumerable<TypeReferenceWithAttributes> Interfaces(EmitContext context); /// <summary> /// True if the type may not be instantiated. /// </summary> bool IsAbstract { get; } /// <summary> /// Is type initialized anytime before first access to static field /// </summary> bool IsBeforeFieldInit { get; } /// <summary> /// Is this imported from COM type library /// </summary> bool IsComObject { get; } /// <summary> /// True if this type is parameterized (this.GenericParameters is a non empty collection). /// </summary> bool IsGeneric { get; } /// <summary> /// True if the type is an interface. /// </summary> bool IsInterface { get; } /// <summary> /// True if the type is a delegate. /// </summary> bool IsDelegate { get; } /// <summary> /// True if this type gets special treatment from the runtime. /// </summary> bool IsRuntimeSpecial { get; } /// <summary> /// True if this type is serializable. /// </summary> bool IsSerializable { get; } /// <summary> /// True if the type has special name. /// </summary> bool IsSpecialName { get; } /// <summary> /// True if the type is a Windows runtime type. /// </summary> /// <remarks> /// A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. /// WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. /// This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. /// These two assemblies are special as they implement the CLR's support for WinRT. /// </remarks> bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type may not be subtyped. /// </summary> bool IsSealed { get; } /// <summary> /// Layout of the type. /// </summary> LayoutKind Layout { get; } /// <summary> /// Zero or more methods defined by this type. /// </summary> IEnumerable<IMethodDefinition> GetMethods(EmitContext context); /// <summary> /// Zero or more nested types defined by this type. /// </summary> IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context); /// <summary> /// Zero or more properties defined by this type. /// </summary> IEnumerable<IPropertyDefinition> GetProperties(EmitContext context); /// <summary> /// Declarative security actions for this type. Will be empty if this.HasSecurity is false. /// </summary> IEnumerable<SecurityAttribute> SecurityAttributes { get; } /// <summary> /// Size of an object of this type. In bytes. If zero, the size is unspecified and will be determined at runtime. /// </summary> uint SizeOf { get; } /// <summary> /// Default marshalling of the Strings in this class. /// </summary> CharSet StringFormat { get; } } /// <summary> /// A reference to a type. /// </summary> internal interface ITypeReference : IReference { /// <summary> /// True if the type is an enumeration (it extends System.Enum and is sealed). Corresponds to C# enum. /// </summary> bool IsEnum { get; } /// <summary> /// True if the type is a value type. /// Value types are sealed and extend System.ValueType or System.Enum. /// A type parameter for which MustBeValueType (the struct constraint in C#) is true also returns true for this property. /// </summary> bool IsValueType { get; } /// <summary> /// The type definition being referred to. /// </summary> ITypeDefinition? GetResolvedType(EmitContext context); /// <summary> /// Unless the value of TypeCode is PrimitiveTypeCode.NotPrimitive, the type corresponds to a "primitive" CLR type (such as System.Int32) and /// the type code identifies which of the primitive types it corresponds to. /// </summary> PrimitiveTypeCode TypeCode { get; } /// <summary> /// TypeDefs defined in modules linked to the assembly being emitted are listed in the ExportedTypes table. /// </summary> TypeDefinitionHandle TypeDef { get; } IGenericMethodParameterReference? AsGenericMethodParameterReference { get; } IGenericTypeInstanceReference? AsGenericTypeInstanceReference { get; } IGenericTypeParameterReference? AsGenericTypeParameterReference { get; } INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context); INamespaceTypeReference? AsNamespaceTypeReference { get; } INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context); INestedTypeReference? AsNestedTypeReference { get; } ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference { get; } ITypeDefinition? AsTypeDefinition(EmitContext context); } /// <summary> /// A enumeration of all of the value types that are built into the Runtime (and thus have specialized IL instructions that manipulate them). /// </summary> internal enum PrimitiveTypeCode { /// <summary> /// A single bit. /// </summary> Boolean, /// <summary> /// An unsigned 16 bit integer representing a Unicode UTF16 code point. /// </summary> Char, /// <summary> /// A signed 8 bit integer. /// </summary> Int8, /// <summary> /// A 32 bit IEEE floating point number. /// </summary> Float32, /// <summary> /// A 64 bit IEEE floating point number. /// </summary> Float64, /// <summary> /// A signed 16 bit integer. /// </summary> Int16, /// <summary> /// A signed 32 bit integer. /// </summary> Int32, /// <summary> /// A signed 64 bit integer. /// </summary> Int64, /// <summary> /// A signed 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> IntPtr, /// <summary> /// A pointer to fixed or unmanaged memory. /// </summary> Pointer, /// <summary> /// A reference to managed memory. /// </summary> Reference, /// <summary> /// A string. /// </summary> String, /// <summary> /// An unsigned 8 bit integer. /// </summary> UInt8, /// <summary> /// An unsigned 16 bit integer. /// </summary> UInt16, /// <summary> /// An unsigned 32 bit integer. /// </summary> UInt32, /// <summary> /// An unsigned 64 bit integer. /// </summary> UInt64, /// <summary> /// An unsigned 32 bit integer or 64 bit integer, depending on the native word size of the underlying processor. /// </summary> UIntPtr, /// <summary> /// A type that denotes the absence of a value. /// </summary> Void, /// <summary> /// Not a primitive type. /// </summary> NotPrimitive, /// <summary> /// A pointer to a function in fixed or managed memory. /// </summary> FunctionPointer, /// <summary> /// Type is a dummy type. /// </summary> Invalid, } /// <summary> /// Enumerates the different kinds of levels of visibility a type member can have. /// </summary> internal enum TypeMemberVisibility { /// <summary> /// The member is visible only within its own type. /// </summary> Private = 1, /// <summary> /// The member is visible only within the intersection of its family (its own type and any subtypes) and assembly. /// </summary> FamilyAndAssembly = 2, /// <summary> /// The member is visible only within its own assembly. /// </summary> Assembly = 3, /// <summary> /// The member is visible only within its own type and any subtypes. /// </summary> Family = 4, /// <summary> /// The member is visible only within the union of its family and assembly. /// </summary> FamilyOrAssembly = 5, /// <summary> /// The member is visible everywhere its declaring type is visible. /// </summary> Public = 6 } /// <summary> /// Enumerates the different kinds of variance a generic method or generic type parameter may have. /// </summary> internal enum TypeParameterVariance { /// <summary> /// Two type or method instances are compatible only if they have exactly the same type argument for this parameter. /// </summary> NonVariant = 0, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a subtype of the type the /// other instance has for this parameter. /// </summary> Covariant = 1, /// <summary> /// A type or method instance will match another instance if it has a type for this parameter that is the same or a supertype of the type the /// other instance has for this parameter. /// </summary> Contravariant = 2, } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LoweredDynamicOperation.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.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The dynamic operation factories below return this struct so that the caller /// have the option of separating the call-site initialization from its invocation. /// /// Most callers just call <see cref="ToExpression"/> to get the combo but some (object and array initializers) /// hoist all call-site initialization code and emit multiple invocations of the same site. /// </summary> internal struct LoweredDynamicOperation { private readonly SyntheticBoundNodeFactory? _factory; private readonly TypeSymbol _resultType; private readonly ImmutableArray<LocalSymbol> _temps; public readonly BoundExpression? SiteInitialization; public readonly BoundExpression SiteInvocation; public LoweredDynamicOperation(SyntheticBoundNodeFactory? factory, BoundExpression? siteInitialization, BoundExpression siteInvocation, TypeSymbol resultType, ImmutableArray<LocalSymbol> temps) { _factory = factory; _resultType = resultType; _temps = temps; this.SiteInitialization = siteInitialization; this.SiteInvocation = siteInvocation; } public static LoweredDynamicOperation Bad( BoundExpression? loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, BoundExpression? loweredRight, TypeSymbol resultType) { var children = ArrayBuilder<BoundExpression>.GetInstance(); children.AddOptional(loweredReceiver); children.AddRange(loweredArguments); children.AddOptional(loweredRight); return LoweredDynamicOperation.Bad(resultType, children.ToImmutableAndFree()); } public static LoweredDynamicOperation Bad(TypeSymbol resultType, ImmutableArray<BoundExpression> children) { Debug.Assert(children.Length > 0); var bad = new BoundBadExpression(children[0].Syntax, LookupResultKind.Empty, ImmutableArray<Symbol?>.Empty, children, resultType); return new LoweredDynamicOperation(null, null, bad, resultType, default(ImmutableArray<LocalSymbol>)); } public BoundExpression ToExpression() { if (_factory == null) { Debug.Assert(SiteInitialization == null && SiteInvocation is BoundBadExpression && _temps.IsDefaultOrEmpty); return SiteInvocation; } // TODO (tomat): we might be able to use SiteInvocation.Type instead of resultType once we stop using GetLoweredType Debug.Assert(SiteInitialization is { }); if (_temps.IsDefaultOrEmpty) { return _factory.Sequence(new[] { SiteInitialization }, SiteInvocation, _resultType); } else { return new BoundSequence(_factory.Syntax, _temps, ImmutableArray.Create(SiteInitialization), SiteInvocation, _resultType) { WasCompilerGenerated = 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.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The dynamic operation factories below return this struct so that the caller /// have the option of separating the call-site initialization from its invocation. /// /// Most callers just call <see cref="ToExpression"/> to get the combo but some (object and array initializers) /// hoist all call-site initialization code and emit multiple invocations of the same site. /// </summary> internal struct LoweredDynamicOperation { private readonly SyntheticBoundNodeFactory? _factory; private readonly TypeSymbol _resultType; private readonly ImmutableArray<LocalSymbol> _temps; public readonly BoundExpression? SiteInitialization; public readonly BoundExpression SiteInvocation; public LoweredDynamicOperation(SyntheticBoundNodeFactory? factory, BoundExpression? siteInitialization, BoundExpression siteInvocation, TypeSymbol resultType, ImmutableArray<LocalSymbol> temps) { _factory = factory; _resultType = resultType; _temps = temps; this.SiteInitialization = siteInitialization; this.SiteInvocation = siteInvocation; } public static LoweredDynamicOperation Bad( BoundExpression? loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, BoundExpression? loweredRight, TypeSymbol resultType) { var children = ArrayBuilder<BoundExpression>.GetInstance(); children.AddOptional(loweredReceiver); children.AddRange(loweredArguments); children.AddOptional(loweredRight); return LoweredDynamicOperation.Bad(resultType, children.ToImmutableAndFree()); } public static LoweredDynamicOperation Bad(TypeSymbol resultType, ImmutableArray<BoundExpression> children) { Debug.Assert(children.Length > 0); var bad = new BoundBadExpression(children[0].Syntax, LookupResultKind.Empty, ImmutableArray<Symbol?>.Empty, children, resultType); return new LoweredDynamicOperation(null, null, bad, resultType, default(ImmutableArray<LocalSymbol>)); } public BoundExpression ToExpression() { if (_factory == null) { Debug.Assert(SiteInitialization == null && SiteInvocation is BoundBadExpression && _temps.IsDefaultOrEmpty); return SiteInvocation; } // TODO (tomat): we might be able to use SiteInvocation.Type instead of resultType once we stop using GetLoweredType Debug.Assert(SiteInitialization is { }); if (_temps.IsDefaultOrEmpty) { return _factory.Sequence(new[] { SiteInitialization }, SiteInvocation, _resultType); } else { return new BoundSequence(_factory.Syntax, _temps, ImmutableArray.Create(SiteInitialization), SiteInvocation, _resultType) { WasCompilerGenerated = true }; } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/CSharp/Portable/FlowAnalysis/FlowAnalysisPass.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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal class FlowAnalysisPass { /// <summary> /// The flow analysis pass. This pass reports required diagnostics for unreachable /// statements and uninitialized variables (through the call to FlowAnalysisWalker.Analyze), /// and inserts a final return statement if the end of a void-returning method is reachable. /// </summary> /// <param name="method">the method to be analyzed</param> /// <param name="block">the method's body</param> /// <param name="diagnostics">the receiver of the reported diagnostics</param> /// <param name="hasTrailingExpression">indicates whether this Script had a trailing expression</param> /// <param name="originalBodyNested">the original method body is the last statement in the block</param> /// <returns>the rewritten block for the method (with a return statement possibly inserted)</returns> public static BoundBlock Rewrite( MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics, bool hasTrailingExpression, bool originalBodyNested) { #if DEBUG // We should only see a trailingExpression if we're in a Script initializer. Debug.Assert(!hasTrailingExpression || method.IsScriptInitializer); var initialDiagnosticCount = diagnostics.ToReadOnly().Length; #endif var compilation = method.DeclaringCompilation; if (method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(compilation)) { // we don't analyze synthesized void methods. if ((method.IsImplicitlyDeclared && !method.IsScriptInitializer) || Analyze(compilation, method, block, diagnostics)) { block = AppendImplicitReturn(block, method, originalBodyNested); } } else if (Analyze(compilation, method, block, diagnostics)) { // If the method is a lambda expression being converted to a non-void delegate type // and the end point is reachable then suppress the error here; a special error // will be reported by the lambda binder. Debug.Assert(method.MethodKind != MethodKind.AnonymousFunction); // Add implicit "return default(T)" if this is a submission that does not have a trailing expression. var submissionResultType = (method as SynthesizedInteractiveInitializerMethod)?.ResultType; if (!hasTrailingExpression && ((object)submissionResultType != null)) { Debug.Assert(!submissionResultType.IsVoidType()); var trailingExpression = new BoundDefaultExpression(method.GetNonNullSyntaxNode(), submissionResultType); var newStatements = block.Statements.Add(new BoundReturnStatement(trailingExpression.Syntax, RefKind.None, trailingExpression)); block = new BoundBlock(block.Syntax, ImmutableArray<LocalSymbol>.Empty, newStatements) { WasCompilerGenerated = true }; #if DEBUG // It should not be necessary to repeat analysis after adding this node, because adding a trailing // return in cases where one was missing should never produce different Diagnostics. IEnumerable<Diagnostic> GetErrorsOnly(IEnumerable<Diagnostic> diags) => diags.Where(d => d.Severity == DiagnosticSeverity.Error); var flowAnalysisDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(!Analyze(compilation, method, block, flowAnalysisDiagnostics)); // Ignore warnings since flow analysis reports nullability mismatches. Debug.Assert(GetErrorsOnly(flowAnalysisDiagnostics.ToReadOnly()).SequenceEqual(GetErrorsOnly(diagnostics.ToReadOnly().Skip(initialDiagnosticCount)))); flowAnalysisDiagnostics.Free(); #endif } // If there's more than one location, then the method is partial and we // have already reported a non-void partial method error. else if (method.Locations.Length == 1) { diagnostics.Add(ErrorCode.ERR_ReturnExpected, method.Locations[0], method); } } return block; } private static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method, bool originalBodyNested) { if (originalBodyNested) { var statements = body.Statements; int n = statements.Length; var builder = ArrayBuilder<BoundStatement>.GetInstance(n); builder.AddRange(statements, n - 1); builder.Add(AppendImplicitReturn((BoundBlock)statements[n - 1], method)); return body.Update(body.Locals, ImmutableArray<LocalFunctionSymbol>.Empty, builder.ToImmutableAndFree()); } else { return AppendImplicitReturn(body, method); } } // insert the implicit "return" statement at the end of the method body // Normally, we wouldn't bother attaching syntax trees to compiler-generated nodes, but these // ones are going to have sequence points. internal static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method) { Debug.Assert(body != null); Debug.Assert(method != null); SyntaxNode syntax = body.Syntax; Debug.Assert(body.WasCompilerGenerated || syntax.IsKind(SyntaxKind.Block) || syntax.IsKind(SyntaxKind.ArrowExpressionClause) || syntax.IsKind(SyntaxKind.ConstructorDeclaration) || syntax.IsKind(SyntaxKind.CompilationUnit)); BoundStatement ret = (method.IsIterator && !method.IsAsync) ? (BoundStatement)BoundYieldBreakStatement.Synthesized(syntax) : BoundReturnStatement.Synthesized(syntax, RefKind.None, null); return body.Update(body.Locals, body.LocalFunctions, body.Statements.Add(ret)); } private static bool Analyze( CSharpCompilation compilation, MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics) { var result = ControlFlowPass.Analyze(compilation, method, block, diagnostics); DefiniteAssignmentPass.Analyze(compilation, method, block, diagnostics); return result; } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal class FlowAnalysisPass { /// <summary> /// The flow analysis pass. This pass reports required diagnostics for unreachable /// statements and uninitialized variables (through the call to FlowAnalysisWalker.Analyze), /// and inserts a final return statement if the end of a void-returning method is reachable. /// </summary> /// <param name="method">the method to be analyzed</param> /// <param name="block">the method's body</param> /// <param name="diagnostics">the receiver of the reported diagnostics</param> /// <param name="hasTrailingExpression">indicates whether this Script had a trailing expression</param> /// <param name="originalBodyNested">the original method body is the last statement in the block</param> /// <returns>the rewritten block for the method (with a return statement possibly inserted)</returns> public static BoundBlock Rewrite( MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics, bool hasTrailingExpression, bool originalBodyNested) { #if DEBUG // We should only see a trailingExpression if we're in a Script initializer. Debug.Assert(!hasTrailingExpression || method.IsScriptInitializer); var initialDiagnosticCount = diagnostics.ToReadOnly().Length; #endif var compilation = method.DeclaringCompilation; if (method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(compilation)) { // we don't analyze synthesized void methods. if ((method.IsImplicitlyDeclared && !method.IsScriptInitializer) || Analyze(compilation, method, block, diagnostics)) { block = AppendImplicitReturn(block, method, originalBodyNested); } } else if (Analyze(compilation, method, block, diagnostics)) { // If the method is a lambda expression being converted to a non-void delegate type // and the end point is reachable then suppress the error here; a special error // will be reported by the lambda binder. Debug.Assert(method.MethodKind != MethodKind.AnonymousFunction); // Add implicit "return default(T)" if this is a submission that does not have a trailing expression. var submissionResultType = (method as SynthesizedInteractiveInitializerMethod)?.ResultType; if (!hasTrailingExpression && ((object)submissionResultType != null)) { Debug.Assert(!submissionResultType.IsVoidType()); var trailingExpression = new BoundDefaultExpression(method.GetNonNullSyntaxNode(), submissionResultType); var newStatements = block.Statements.Add(new BoundReturnStatement(trailingExpression.Syntax, RefKind.None, trailingExpression)); block = new BoundBlock(block.Syntax, ImmutableArray<LocalSymbol>.Empty, newStatements) { WasCompilerGenerated = true }; #if DEBUG // It should not be necessary to repeat analysis after adding this node, because adding a trailing // return in cases where one was missing should never produce different Diagnostics. IEnumerable<Diagnostic> GetErrorsOnly(IEnumerable<Diagnostic> diags) => diags.Where(d => d.Severity == DiagnosticSeverity.Error); var flowAnalysisDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(!Analyze(compilation, method, block, flowAnalysisDiagnostics)); // Ignore warnings since flow analysis reports nullability mismatches. Debug.Assert(GetErrorsOnly(flowAnalysisDiagnostics.ToReadOnly()).SequenceEqual(GetErrorsOnly(diagnostics.ToReadOnly().Skip(initialDiagnosticCount)))); flowAnalysisDiagnostics.Free(); #endif } // If there's more than one location, then the method is partial and we // have already reported a non-void partial method error. else if (method.Locations.Length == 1) { diagnostics.Add(ErrorCode.ERR_ReturnExpected, method.Locations[0], method); } } return block; } private static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method, bool originalBodyNested) { if (originalBodyNested) { var statements = body.Statements; int n = statements.Length; var builder = ArrayBuilder<BoundStatement>.GetInstance(n); builder.AddRange(statements, n - 1); builder.Add(AppendImplicitReturn((BoundBlock)statements[n - 1], method)); return body.Update(body.Locals, ImmutableArray<LocalFunctionSymbol>.Empty, builder.ToImmutableAndFree()); } else { return AppendImplicitReturn(body, method); } } // insert the implicit "return" statement at the end of the method body // Normally, we wouldn't bother attaching syntax trees to compiler-generated nodes, but these // ones are going to have sequence points. internal static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method) { Debug.Assert(body != null); Debug.Assert(method != null); SyntaxNode syntax = body.Syntax; Debug.Assert(body.WasCompilerGenerated || syntax.IsKind(SyntaxKind.Block) || syntax.IsKind(SyntaxKind.ArrowExpressionClause) || syntax.IsKind(SyntaxKind.ConstructorDeclaration) || syntax.IsKind(SyntaxKind.CompilationUnit)); BoundStatement ret = (method.IsIterator && !method.IsAsync) ? (BoundStatement)BoundYieldBreakStatement.Synthesized(syntax) : BoundReturnStatement.Synthesized(syntax, RefKind.None, null); return body.Update(body.Locals, body.LocalFunctions, body.Statements.Add(ret)); } private static bool Analyze( CSharpCompilation compilation, MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics) { var result = ControlFlowPass.Analyze(compilation, method, block, diagnostics); DefiniteAssignmentPass.Analyze(compilation, method, block, diagnostics); return result; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller_NavigationKeys.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.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal bool TryHandleUpKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectPreviousItem()); } internal bool TryHandleDownKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectNextItem()); } private bool ChangeSelection(Action computationAction) { AssertIsForeground(); if (!IsSessionActive) { // No computation running, so just let the editor handle this. return false; } // If we haven't started our editor session yet, just abort. // The user hasn't seen a SigHelp presentation yet, so they're // probably not trying to change the currently visible overload. if (!sessionOpt.PresenterSession.EditorSessionIsActive) { DismissSessionIfActive(); return false; } // If we've finished computing the items then use the navigation commands to change the // selected item. Otherwise, the user was just typing and is now moving through the // file. In this case stop everything we're doing. var model = sessionOpt.InitialUnfilteredModel != null ? WaitForController() : null; // Check if completion is still active. Then update the computation appropriately. // // Also, if we only computed one item, then the user doesn't want to select anything // else. Just stop and let the editor handle the nav character. if (model != null && model.Items.Count > 1) { computationAction(); return true; } else { // Dismiss ourselves and actually allow the editor to navigate. DismissSessionIfActive(); 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; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal bool TryHandleUpKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectPreviousItem()); } internal bool TryHandleDownKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectNextItem()); } private bool ChangeSelection(Action computationAction) { AssertIsForeground(); if (!IsSessionActive) { // No computation running, so just let the editor handle this. return false; } // If we haven't started our editor session yet, just abort. // The user hasn't seen a SigHelp presentation yet, so they're // probably not trying to change the currently visible overload. if (!sessionOpt.PresenterSession.EditorSessionIsActive) { DismissSessionIfActive(); return false; } // If we've finished computing the items then use the navigation commands to change the // selected item. Otherwise, the user was just typing and is now moving through the // file. In this case stop everything we're doing. var model = sessionOpt.InitialUnfilteredModel != null ? WaitForController() : null; // Check if completion is still active. Then update the computation appropriately. // // Also, if we only computed one item, then the user doesn't want to select anything // else. Just stop and let the editor handle the nav character. if (model != null && model.Items.Count > 1) { computationAction(); return true; } else { // Dismiss ourselves and actually allow the editor to navigate. DismissSessionIfActive(); return false; } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingIncrementalAnalyzerProviderMetadataWrapper.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 Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { [Obsolete] internal readonly struct UnitTestingIncrementalAnalyzerProviderMetadataWrapper { public UnitTestingIncrementalAnalyzerProviderMetadataWrapper( string name, bool highPriorityForActiveFile, params string[] workspaceKinds) => UnderlyingObject = new IncrementalAnalyzerProviderMetadata(name, highPriorityForActiveFile, workspaceKinds); internal UnitTestingIncrementalAnalyzerProviderMetadataWrapper(IncrementalAnalyzerProviderMetadata underlyingObject) => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); internal IncrementalAnalyzerProviderMetadata UnderlyingObject { 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 Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { [Obsolete] internal readonly struct UnitTestingIncrementalAnalyzerProviderMetadataWrapper { public UnitTestingIncrementalAnalyzerProviderMetadataWrapper( string name, bool highPriorityForActiveFile, params string[] workspaceKinds) => UnderlyingObject = new IncrementalAnalyzerProviderMetadata(name, highPriorityForActiveFile, workspaceKinds); internal UnitTestingIncrementalAnalyzerProviderMetadataWrapper(IncrementalAnalyzerProviderMetadata underlyingObject) => UnderlyingObject = underlyingObject ?? throw new ArgumentNullException(nameof(underlyingObject)); internal IncrementalAnalyzerProviderMetadata UnderlyingObject { get; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.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.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public abstract class RemoveUnusedValuesTestsBase : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { protected RemoveUnusedValuesTestsBase(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); private protected abstract OptionsCollection PreferNone { get; } private protected abstract OptionsCollection PreferDiscard { get; } private protected abstract OptionsCollection PreferUnusedLocal { get; } private protected OptionsCollection GetOptions(string optionName) { switch (optionName) { case nameof(PreferDiscard): return PreferDiscard; case nameof(PreferUnusedLocal): return PreferUnusedLocal; default: return PreferNone; } } private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, string optionName, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, GetOptions(optionName), parseOptions); protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, string optionName, ParseOptions parseOptions = null) => TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: GetOptions(optionName), parseOptions: parseOptions); // Helpers to test all options - only used by tests which already have InlineData for custom input test code snippets. protected async Task TestInRegularAndScriptWithAllOptionsAsync(string initialMarkup, string expectedMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: options, parseOptions: parseOptions); } } protected async Task TestMissingInRegularAndScriptWithAllOptionsAsync(string initialMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); } } } }
// 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.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public abstract class RemoveUnusedValuesTestsBase : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { protected RemoveUnusedValuesTestsBase(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); private protected abstract OptionsCollection PreferNone { get; } private protected abstract OptionsCollection PreferDiscard { get; } private protected abstract OptionsCollection PreferUnusedLocal { get; } private protected OptionsCollection GetOptions(string optionName) { switch (optionName) { case nameof(PreferDiscard): return PreferDiscard; case nameof(PreferUnusedLocal): return PreferUnusedLocal; default: return PreferNone; } } private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, OptionsCollection options, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, string optionName, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, GetOptions(optionName), parseOptions); protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, string optionName, ParseOptions parseOptions = null) => TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: GetOptions(optionName), parseOptions: parseOptions); // Helpers to test all options - only used by tests which already have InlineData for custom input test code snippets. protected async Task TestInRegularAndScriptWithAllOptionsAsync(string initialMarkup, string expectedMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: options, parseOptions: parseOptions); } } protected async Task TestMissingInRegularAndScriptWithAllOptionsAsync(string initialMarkup, ParseOptions parseOptions = null) { foreach (var options in new[] { PreferDiscard, PreferUnusedLocal }) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/Workspace/Host/EventListener/EventListenerMetadata.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 Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// MEF metadata class used to find exports declared for a specific <see cref="IEventListener"/>. /// </summary> internal class EventListenerMetadata : WorkspaceKindMetadata { public string Service { get; } public EventListenerMetadata(IDictionary<string, object> data) : base(data) { this.Service = (string)data.GetValueOrDefault("Service"); } public EventListenerMetadata(string service, params string[] workspaceKinds) : base(workspaceKinds) { if (workspaceKinds?.Length == 0) { throw new ArgumentException(nameof(workspaceKinds)); } this.Service = service ?? throw new ArgumentException(nameof(service)); } } }
// 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 Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// MEF metadata class used to find exports declared for a specific <see cref="IEventListener"/>. /// </summary> internal class EventListenerMetadata : WorkspaceKindMetadata { public string Service { get; } public EventListenerMetadata(IDictionary<string, object> data) : base(data) { this.Service = (string)data.GetValueOrDefault("Service"); } public EventListenerMetadata(string service, params string[] workspaceKinds) : base(workspaceKinds) { if (workspaceKinds?.Length == 0) { throw new ArgumentException(nameof(workspaceKinds)); } this.Service = service ?? throw new ArgumentException(nameof(service)); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/WinMdTests.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 System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateEmptyCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); }); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateEmptyCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); }); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108135")] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateEmptyCompilation(source, compileReferences, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(5, parameters.Length); var actualReturnType = parameters[0].Type; Assert.Equal(TypeKind.Class, actualReturnType.TypeKind); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } }); } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")] [ConditionalFact(typeof(OSVersionWin8), typeof(IsRelease))] // https://github.com/dotnet/roslyn/issues/25702 public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")), runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); }); } [WorkItem(1117084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1117084")] [Fact] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); var result = context.CompileExpression( "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity(); Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single()); }); } [WorkItem(1154988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1154988")] [ConditionalFact(typeof(OSVersionWin8))] public void WinMdAssemblyReferenceRequiresRedirect() { var source = @"class C : Windows.UI.Xaml.Controls.UserControl { static void M(C c) { } }"; var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")), runtime => { string errorMessage; var testData = new CompilationTestData(); ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.SelectAsArray(m => m.MetadataBlock), "c.Dispatcher", ImmutableArray<Alias>.Empty, (metadataBlocks, _) => { return CreateMethodContext(runtime, "C.M"); }, (AssemblyIdentity assembly, out uint size) => { // Compilation should succeed without retry if we redirect assembly refs correctly. // Throwing so that we don't loop forever (as we did before fix)... throw ExceptionUtilities.Unreachable; }, out errorMessage, out testData); Assert.Null(errorMessage); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get"" IL_0006: ret }"); }); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
// 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 System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateEmptyCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); }); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateEmptyCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); }); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108135")] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateEmptyCompilation(source, compileReferences, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(5, parameters.Length); var actualReturnType = parameters[0].Type; Assert.Equal(TypeKind.Class, actualReturnType.TypeKind); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } }); } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")] [ConditionalFact(typeof(OSVersionWin8), typeof(IsRelease))] // https://github.com/dotnet/roslyn/issues/25702 public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")), runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); }); } [WorkItem(1117084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1117084")] [Fact] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); var result = context.CompileExpression( "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity(); Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single()); }); } [WorkItem(1154988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1154988")] [ConditionalFact(typeof(OSVersionWin8))] public void WinMdAssemblyReferenceRequiresRedirect() { var source = @"class C : Windows.UI.Xaml.Controls.UserControl { static void M(C c) { } }"; var compilation = CreateEmptyCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")), runtime => { string errorMessage; var testData = new CompilationTestData(); ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.SelectAsArray(m => m.MetadataBlock), "c.Dispatcher", ImmutableArray<Alias>.Empty, (metadataBlocks, _) => { return CreateMethodContext(runtime, "C.M"); }, (AssemblyIdentity assembly, out uint size) => { // Compilation should succeed without retry if we redirect assembly refs correctly. // Throwing so that we don't loop forever (as we did before fix)... throw ExceptionUtilities.Unreachable; }, out errorMessage, out testData); Assert.Null(errorMessage); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get"" IL_0006: ret }"); }); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/SourceGeneratorItem.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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratorItem : BaseItem { public ProjectId ProjectId { get; } public string GeneratorAssemblyName { get; } // Since the type name is also used for the display text, we can just reuse that. We'll still have an explicit // property so the assembly name/type name pair that is used in other places is also used here. public string GeneratorTypeName => base.Text; public AnalyzerReference AnalyzerReference { get; } public SourceGeneratorItem(ProjectId projectId, ISourceGenerator generator, AnalyzerReference analyzerReference) : base(name: SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator)) { ProjectId = projectId; GeneratorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); AnalyzerReference = analyzerReference; } // TODO: do we need an icon for our use? public override ImageMoniker IconMoniker => KnownMonikers.Process; public override object GetBrowseObject() { return new BrowseObject(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. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratorItem : BaseItem { public ProjectId ProjectId { get; } public string GeneratorAssemblyName { get; } // Since the type name is also used for the display text, we can just reuse that. We'll still have an explicit // property so the assembly name/type name pair that is used in other places is also used here. public string GeneratorTypeName => base.Text; public AnalyzerReference AnalyzerReference { get; } public SourceGeneratorItem(ProjectId projectId, ISourceGenerator generator, AnalyzerReference analyzerReference) : base(name: SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator)) { ProjectId = projectId; GeneratorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); AnalyzerReference = analyzerReference; } // TODO: do we need an icon for our use? public override ImageMoniker IconMoniker => KnownMonikers.Process; public override object GetBrowseObject() { return new BrowseObject(this); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/Simplification/Simplifier.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Simplification { /// <summary> /// Expands and Reduces subtrees. /// /// Expansion: /// 1) Makes inferred names explicit (on anonymous types and tuples). /// 2) Replaces names with fully qualified dotted names. /// 3) Adds parentheses around expressions /// 4) Adds explicit casts/conversions where implicit conversions exist /// 5) Adds escaping to identifiers /// 6) Rewrites extension method invocations with explicit calls on the class containing the extension method. /// /// Reduction: /// 1) Shortens dotted names to their minimally qualified form /// 2) Removes unnecessary parentheses /// 3) Removes unnecessary casts/conversions /// 4) Removes unnecessary escaping /// 5) Rewrites explicit calls to extension methods to use dot notation /// 6) Removes unnecessary tuple element names and anonymous type member names /// </summary> public static partial class Simplifier { /// <summary> /// The annotation the reducer uses to identify sub trees to be reduced. /// The Expand operations add this annotation to nodes so that the Reduce operations later find them. /// </summary> public static SyntaxAnnotation Annotation { get; } = new SyntaxAnnotation(); /// <summary> /// This is the annotation used by the simplifier and expander to identify Predefined type and preserving /// them from over simplification /// </summary> public static SyntaxAnnotation SpecialTypeAnnotation { get; } = new SyntaxAnnotation(); /// <summary> /// The annotation <see cref="CodeAction.CleanupDocumentAsync"/> used to identify sub trees to look for symbol annotations on. /// It will then add import directives for these symbol annotations. /// </summary> public static SyntaxAnnotation AddImportsAnnotation { get; } = new SyntaxAnnotation(); /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static async Task<TNode> ExpandAsync<TNode>(TNode node, Document document, Func<SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, CancellationToken cancellationToken = default) where TNode : SyntaxNode { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (document == null) { throw new ArgumentNullException(nameof(document)); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); return Expand(node, semanticModel, document.Project.Solution.Workspace, expandInsideNode, expandParameter, cancellationToken); } /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static TNode Expand<TNode>(TNode node, SemanticModel semanticModel, Workspace workspace, Func<SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, CancellationToken cancellationToken = default) where TNode : SyntaxNode { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } var result = workspace.Services.GetLanguageServices(node.Language).GetService<ISimplificationService>() .Expand(node, semanticModel, annotationForReplacedAliasIdentifier: null, expandInsideNode: expandInsideNode, expandParameter: expandParameter, cancellationToken: cancellationToken); return (TNode)result; } /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static async Task<SyntaxToken> ExpandAsync(SyntaxToken token, Document document, Func<SyntaxNode, bool> expandInsideNode = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); return Expand(token, semanticModel, document.Project.Solution.Workspace, expandInsideNode, cancellationToken); } /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static SyntaxToken Expand(SyntaxToken token, SemanticModel semanticModel, Workspace workspace, Func<SyntaxNode, bool> expandInsideNode = null, CancellationToken cancellationToken = default) { if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } return workspace.Services.GetLanguageServices(token.Language).GetService<ISimplificationService>() .Expand(token, semanticModel, expandInsideNode, cancellationToken); } /// <summary> /// Reduce all sub-trees annotated with <see cref="Annotation" /> found within the document. The annotated node and all child nodes will be reduced. /// </summary> public static async Task<Document> ReduceAsync(Document document, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return await ReduceAsync(document, root.FullSpan, optionSet, cancellationToken).ConfigureAwait(false); } /// <summary> /// Reduce the sub-trees annotated with <see cref="Annotation" /> found within the subtrees identified with the specified <paramref name="annotation"/>. /// The annotated node and all child nodes will be reduced. /// </summary> public static async Task<Document> ReduceAsync(Document document, SyntaxAnnotation annotation, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (annotation == null) { throw new ArgumentNullException(nameof(annotation)); } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return await ReduceAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), optionSet, cancellationToken).ConfigureAwait(false); } /// <summary> /// Reduce the sub-trees annotated with <see cref="Annotation" /> found within the specified span. /// The annotated node and all child nodes will be reduced. /// </summary> public static Task<Document> ReduceAsync(Document document, TextSpan span, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return ReduceAsync(document, SpecializedCollections.SingletonEnumerable(span), optionSet, cancellationToken); } /// <summary> /// Reduce the sub-trees annotated with <see cref="Annotation" /> found within the specified spans. /// The annotated node and all child nodes will be reduced. /// </summary> public static Task<Document> ReduceAsync(Document document, IEnumerable<TextSpan> spans, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (spans == null) { throw new ArgumentNullException(nameof(spans)); } return document.GetLanguageService<ISimplificationService>().ReduceAsync( document, spans.ToImmutableArrayOrEmpty(), optionSet, cancellationToken: cancellationToken); } internal static async Task<Document> ReduceAsync( Document document, ImmutableArray<AbstractReducer> reducers, OptionSet optionSet = null, CancellationToken cancellationToken = default) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return await document.GetLanguageService<ISimplificationService>() .ReduceAsync(document, ImmutableArray.Create(root.FullSpan), optionSet, reducers, 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. #nullable disable 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.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Simplification { /// <summary> /// Expands and Reduces subtrees. /// /// Expansion: /// 1) Makes inferred names explicit (on anonymous types and tuples). /// 2) Replaces names with fully qualified dotted names. /// 3) Adds parentheses around expressions /// 4) Adds explicit casts/conversions where implicit conversions exist /// 5) Adds escaping to identifiers /// 6) Rewrites extension method invocations with explicit calls on the class containing the extension method. /// /// Reduction: /// 1) Shortens dotted names to their minimally qualified form /// 2) Removes unnecessary parentheses /// 3) Removes unnecessary casts/conversions /// 4) Removes unnecessary escaping /// 5) Rewrites explicit calls to extension methods to use dot notation /// 6) Removes unnecessary tuple element names and anonymous type member names /// </summary> public static partial class Simplifier { /// <summary> /// The annotation the reducer uses to identify sub trees to be reduced. /// The Expand operations add this annotation to nodes so that the Reduce operations later find them. /// </summary> public static SyntaxAnnotation Annotation { get; } = new SyntaxAnnotation(); /// <summary> /// This is the annotation used by the simplifier and expander to identify Predefined type and preserving /// them from over simplification /// </summary> public static SyntaxAnnotation SpecialTypeAnnotation { get; } = new SyntaxAnnotation(); /// <summary> /// The annotation <see cref="CodeAction.CleanupDocumentAsync"/> used to identify sub trees to look for symbol annotations on. /// It will then add import directives for these symbol annotations. /// </summary> public static SyntaxAnnotation AddImportsAnnotation { get; } = new SyntaxAnnotation(); /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static async Task<TNode> ExpandAsync<TNode>(TNode node, Document document, Func<SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, CancellationToken cancellationToken = default) where TNode : SyntaxNode { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (document == null) { throw new ArgumentNullException(nameof(document)); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); return Expand(node, semanticModel, document.Project.Solution.Workspace, expandInsideNode, expandParameter, cancellationToken); } /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static TNode Expand<TNode>(TNode node, SemanticModel semanticModel, Workspace workspace, Func<SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, CancellationToken cancellationToken = default) where TNode : SyntaxNode { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } var result = workspace.Services.GetLanguageServices(node.Language).GetService<ISimplificationService>() .Expand(node, semanticModel, annotationForReplacedAliasIdentifier: null, expandInsideNode: expandInsideNode, expandParameter: expandParameter, cancellationToken: cancellationToken); return (TNode)result; } /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static async Task<SyntaxToken> ExpandAsync(SyntaxToken token, Document document, Func<SyntaxNode, bool> expandInsideNode = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); return Expand(token, semanticModel, document.Project.Solution.Workspace, expandInsideNode, cancellationToken); } /// <summary> /// Expand qualifying parts of the specified subtree, annotating the parts using the <see cref="Annotation" /> annotation. /// </summary> public static SyntaxToken Expand(SyntaxToken token, SemanticModel semanticModel, Workspace workspace, Func<SyntaxNode, bool> expandInsideNode = null, CancellationToken cancellationToken = default) { if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } return workspace.Services.GetLanguageServices(token.Language).GetService<ISimplificationService>() .Expand(token, semanticModel, expandInsideNode, cancellationToken); } /// <summary> /// Reduce all sub-trees annotated with <see cref="Annotation" /> found within the document. The annotated node and all child nodes will be reduced. /// </summary> public static async Task<Document> ReduceAsync(Document document, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return await ReduceAsync(document, root.FullSpan, optionSet, cancellationToken).ConfigureAwait(false); } /// <summary> /// Reduce the sub-trees annotated with <see cref="Annotation" /> found within the subtrees identified with the specified <paramref name="annotation"/>. /// The annotated node and all child nodes will be reduced. /// </summary> public static async Task<Document> ReduceAsync(Document document, SyntaxAnnotation annotation, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (annotation == null) { throw new ArgumentNullException(nameof(annotation)); } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return await ReduceAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), optionSet, cancellationToken).ConfigureAwait(false); } /// <summary> /// Reduce the sub-trees annotated with <see cref="Annotation" /> found within the specified span. /// The annotated node and all child nodes will be reduced. /// </summary> public static Task<Document> ReduceAsync(Document document, TextSpan span, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return ReduceAsync(document, SpecializedCollections.SingletonEnumerable(span), optionSet, cancellationToken); } /// <summary> /// Reduce the sub-trees annotated with <see cref="Annotation" /> found within the specified spans. /// The annotated node and all child nodes will be reduced. /// </summary> public static Task<Document> ReduceAsync(Document document, IEnumerable<TextSpan> spans, OptionSet optionSet = null, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (spans == null) { throw new ArgumentNullException(nameof(spans)); } return document.GetLanguageService<ISimplificationService>().ReduceAsync( document, spans.ToImmutableArrayOrEmpty(), optionSet, cancellationToken: cancellationToken); } internal static async Task<Document> ReduceAsync( Document document, ImmutableArray<AbstractReducer> reducers, OptionSet optionSet = null, CancellationToken cancellationToken = default) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return await document.GetLanguageService<ISimplificationService>() .ReduceAsync(document, ImmutableArray.Create(root.FullSpan), optionSet, reducers, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/CoreTestUtilities/WorkspaceExtensions.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.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { public static partial class WorkspaceExtensions { public static DocumentId AddDocument(this Workspace workspace, ProjectId projectId, IEnumerable<string> folders, string name, SourceText initialText, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular) { var id = projectId.CreateDocumentId(name, folders); var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddDocument(id, name, initialText, folders).GetDocument(id)!.WithSourceCodeKind(sourceCodeKind).Project.Solution; workspace.TryApplyChanges(newSolution); return id; } public static void RemoveDocument(this Workspace workspace, DocumentId documentId) { var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.RemoveDocument(documentId); workspace.TryApplyChanges(newSolution); } public static void UpdateDocument(this Workspace workspace, DocumentId documentId, SourceText newText) { var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.WithDocumentText(documentId, newText); workspace.TryApplyChanges(newSolution); } /// <summary> /// Create a new DocumentId based on a name and optional folders /// </summary> public static DocumentId CreateDocumentId(this ProjectId projectId, string name, IEnumerable<string>? folders = null) { if (folders != null) { var uniqueName = string.Join("/", folders) + "/" + name; return DocumentId.CreateNewId(projectId, uniqueName); } else { return DocumentId.CreateNewId(projectId, name); } } public static IEnumerable<Project> GetProjectsByName(this Solution solution, string name) => solution.Projects.Where(p => string.Compare(p.Name, name, StringComparison.OrdinalIgnoreCase) == 0); internal static EventWaiter VerifyWorkspaceChangedEvent(this Workspace workspace, Action<WorkspaceChangeEventArgs> action) { var wew = new EventWaiter(); workspace.WorkspaceChanged += wew.Wrap<WorkspaceChangeEventArgs>((sender, args) => action(args)); return wew; } } }
// 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.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { public static partial class WorkspaceExtensions { public static DocumentId AddDocument(this Workspace workspace, ProjectId projectId, IEnumerable<string> folders, string name, SourceText initialText, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular) { var id = projectId.CreateDocumentId(name, folders); var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.AddDocument(id, name, initialText, folders).GetDocument(id)!.WithSourceCodeKind(sourceCodeKind).Project.Solution; workspace.TryApplyChanges(newSolution); return id; } public static void RemoveDocument(this Workspace workspace, DocumentId documentId) { var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.RemoveDocument(documentId); workspace.TryApplyChanges(newSolution); } public static void UpdateDocument(this Workspace workspace, DocumentId documentId, SourceText newText) { var oldSolution = workspace.CurrentSolution; var newSolution = oldSolution.WithDocumentText(documentId, newText); workspace.TryApplyChanges(newSolution); } /// <summary> /// Create a new DocumentId based on a name and optional folders /// </summary> public static DocumentId CreateDocumentId(this ProjectId projectId, string name, IEnumerable<string>? folders = null) { if (folders != null) { var uniqueName = string.Join("/", folders) + "/" + name; return DocumentId.CreateNewId(projectId, uniqueName); } else { return DocumentId.CreateNewId(projectId, name); } } public static IEnumerable<Project> GetProjectsByName(this Solution solution, string name) => solution.Projects.Where(p => string.Compare(p.Name, name, StringComparison.OrdinalIgnoreCase) == 0); internal static EventWaiter VerifyWorkspaceChangedEvent(this Workspace workspace, Action<WorkspaceChangeEventArgs> action) { var wew = new EventWaiter(); workspace.WorkspaceChanged += wew.Wrap<WorkspaceChangeEventArgs>((sender, args) => action(args)); return wew; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Core/Portable/CommandLine/CommonCompiler.ExistingReferencesResolver.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.Diagnostics; using System.IO; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class ExistingReferencesResolver : MetadataReferenceResolver, IEquatable<ExistingReferencesResolver> { private readonly MetadataReferenceResolver _resolver; private readonly ImmutableArray<MetadataReference> _availableReferences; private readonly Lazy<HashSet<AssemblyIdentity>> _lazyAvailableReferences; public ExistingReferencesResolver(MetadataReferenceResolver resolver, ImmutableArray<MetadataReference> availableReferences) { Debug.Assert(resolver != null); Debug.Assert(availableReferences != null); _resolver = resolver; _availableReferences = availableReferences; // Delay reading assembly identities until they are actually needed (only when #r is encountered). _lazyAvailableReferences = new Lazy<HashSet<AssemblyIdentity>>(() => new HashSet<AssemblyIdentity>( from reference in _availableReferences let identity = TryGetIdentity(reference) where identity != null select identity!)); } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) { var resolvedReferences = _resolver.ResolveReference(reference, baseFilePath, properties); return resolvedReferences.WhereAsArray(r => _lazyAvailableReferences.Value.Contains(TryGetIdentity(r)!)); } private static AssemblyIdentity? TryGetIdentity(MetadataReference metadataReference) { var peReference = metadataReference as PortableExecutableReference; if (peReference == null || peReference.Properties.Kind != MetadataImageKind.Assembly) { return null; } try { PEAssembly assembly = ((AssemblyMetadata)peReference.GetMetadataNoCopy()).GetAssembly()!; return assembly.Identity; } catch (Exception e) when (e is BadImageFormatException || e is IOException) { // ignore, metadata reading errors are reported by the compiler for the existing references return null; } } public override int GetHashCode() { return _resolver.GetHashCode(); } public bool Equals(ExistingReferencesResolver? other) { return other is object && _resolver.Equals(other._resolver) && _availableReferences.SequenceEqual(other._availableReferences); } public override bool Equals(object? other) => other is ExistingReferencesResolver obj && Equals(obj); } } }
// 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.Diagnostics; using System.IO; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class ExistingReferencesResolver : MetadataReferenceResolver, IEquatable<ExistingReferencesResolver> { private readonly MetadataReferenceResolver _resolver; private readonly ImmutableArray<MetadataReference> _availableReferences; private readonly Lazy<HashSet<AssemblyIdentity>> _lazyAvailableReferences; public ExistingReferencesResolver(MetadataReferenceResolver resolver, ImmutableArray<MetadataReference> availableReferences) { Debug.Assert(resolver != null); Debug.Assert(availableReferences != null); _resolver = resolver; _availableReferences = availableReferences; // Delay reading assembly identities until they are actually needed (only when #r is encountered). _lazyAvailableReferences = new Lazy<HashSet<AssemblyIdentity>>(() => new HashSet<AssemblyIdentity>( from reference in _availableReferences let identity = TryGetIdentity(reference) where identity != null select identity!)); } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) { var resolvedReferences = _resolver.ResolveReference(reference, baseFilePath, properties); return resolvedReferences.WhereAsArray(r => _lazyAvailableReferences.Value.Contains(TryGetIdentity(r)!)); } private static AssemblyIdentity? TryGetIdentity(MetadataReference metadataReference) { var peReference = metadataReference as PortableExecutableReference; if (peReference == null || peReference.Properties.Kind != MetadataImageKind.Assembly) { return null; } try { PEAssembly assembly = ((AssemblyMetadata)peReference.GetMetadataNoCopy()).GetAssembly()!; return assembly.Identity; } catch (Exception e) when (e is BadImageFormatException || e is IOException) { // ignore, metadata reading errors are reported by the compiler for the existing references return null; } } public override int GetHashCode() { return _resolver.GetHashCode(); } public bool Equals(ExistingReferencesResolver? other) { return other is object && _resolver.Equals(other._resolver) && _availableReferences.SequenceEqual(other._availableReferences); } public override bool Equals(object? other) => other is ExistingReferencesResolver obj && Equals(obj); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameTokenSimplificationAnnotation.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.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal class RenameTokenSimplificationAnnotation : RenameAnnotation { public TextSpan OriginalTextSpan { get; set; } } }
// 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.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal class RenameTokenSimplificationAnnotation : RenameAnnotation { public TextSpan OriginalTextSpan { get; set; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.ExpressionCodeGenerator.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 Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private Class VisualBasicCodeGenerator Private Class ExpressionCodeGenerator Inherits VisualBasicCodeGenerator Public Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) MyBase.New(insertionPoint, selectionResult, analyzerResult) End Sub Public Shared Function IsExtractMethodOnExpression(code As SelectionResult) As Boolean Return code.SelectionInExpression End Function Protected Overrides Function CreateMethodName() As SyntaxToken Dim methodName = "NewMethod" Dim containingScope = VBSelectionResult.GetContainingScope() methodName = GetMethodNameBasedOnExpression(methodName, containingScope) Dim semanticModel = SemanticDocument.SemanticModel Dim nameGenerator = New UniqueNameGenerator(semanticModel) Return SyntaxFactory.Identifier( nameGenerator.CreateUniqueMethodName(containingScope, methodName)) End Function Private Shared Function GetMethodNameBasedOnExpression(methodName As String, expression As SyntaxNode) As String If expression.IsParentKind(SyntaxKind.EqualsValue) AndAlso expression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then Dim varDecl = DirectCast(expression.Parent.Parent, VariableDeclaratorSyntax) If varDecl.Names.Count <> 1 Then Return methodName End If Dim identifierNode = varDecl.Names(0) If identifierNode Is Nothing Then Return methodName End If Dim name = identifierNode.Identifier.ValueText Return If(name IsNot Nothing AndAlso name.Length > 0, MakeMethodName("Get", name, camelCase:=False), methodName) End If If TypeOf expression Is MemberAccessExpressionSyntax Then expression = CType(expression, MemberAccessExpressionSyntax).Name End If If TypeOf expression Is NameSyntax Then Dim lastDottedName = CType(expression, NameSyntax).GetLastDottedName() Dim plainName = CType(lastDottedName, SimpleNameSyntax).Identifier.ValueText Return If(plainName IsNot Nothing AndAlso plainName.Length > 0, MakeMethodName("Get", plainName, camelCase:=False), methodName) End If Return methodName End Function Protected Overrides Function GetInitialStatementsForMethodDefinitions() As ImmutableArray(Of StatementSyntax) Contract.ThrowIfFalse(IsExtractMethodOnExpression(VBSelectionResult)) Dim expression = DirectCast(VBSelectionResult.GetContainingScope(), ExpressionSyntax) Dim statement As StatementSyntax If Me.AnalyzerResult.HasReturnType Then statement = SyntaxFactory.ReturnStatement(expression:=expression) Else ' we have expression for void method (Sub). make the expression as call ' statement if possible we can create call statement only from invocation ' and member access expression. otherwise, it is not a valid expression. ' return error code If expression.Kind <> SyntaxKind.InvocationExpression AndAlso expression.Kind <> SyntaxKind.SimpleMemberAccessExpression Then Return ImmutableArray(Of StatementSyntax).Empty End If statement = SyntaxFactory.ExpressionStatement(expression:=expression) End If Return ImmutableArray.Create(statement) End Function Protected Overrides Function GetOutermostCallSiteContainerToProcess(cancellationToken As CancellationToken) As SyntaxNode Dim callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken) Return If(callSiteContainer, (GetCallSiteContainerFromExpression())) End Function Private Function GetCallSiteContainerFromExpression() As SyntaxNode Dim container = VBSelectionResult.InnermostStatementContainer() Contract.ThrowIfNull(container) Contract.ThrowIfFalse(container.IsStatementContainerNode() OrElse TypeOf container Is TypeBlockSyntax OrElse TypeOf container Is CompilationUnitSyntax) Return container End Function Protected Overrides Function GetFirstStatementOrInitializerSelectedAtCallSite() As StatementSyntax Return VBSelectionResult.GetContainingScopeOf(Of StatementSyntax)() End Function Protected Overrides Function GetLastStatementOrInitializerSelectedAtCallSite() As StatementSyntax Return GetFirstStatementOrInitializerSelectedAtCallSite() End Function Protected Overrides Async Function GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken As CancellationToken) As Task(Of StatementSyntax) Dim enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite() Dim callSignature = CreateCallSignature().WithAdditionalAnnotations(CallSiteAnnotation) Dim sourceNode = VBSelectionResult.GetContainingScope() Contract.ThrowIfTrue( sourceNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso DirectCast(sourceNode.Parent, MemberAccessExpressionSyntax).Name Is sourceNode, "invalid scope. scope is not an expression") ' To lower the chances that replacing sourceNode with callSignature will break the user's ' code, we make the enclosing statement semantically explicit. This ends up being a little ' bit more work because we need to annotate the sourceNode so that we can get back to it ' after rewriting the enclosing statement. Dim sourceNodeAnnotation = New SyntaxAnnotation() Dim enclosingStatementAnnotation = New SyntaxAnnotation() Dim newEnclosingStatement = enclosingStatement _ .ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation)) _ .WithAdditionalAnnotations(enclosingStatementAnnotation) Dim updatedDocument = Await Me.SemanticDocument.Document.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(False) Dim updatedRoot = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) newEnclosingStatement = DirectCast(updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode(), StatementSyntax) ' because of the complexification we cannot guarantee that there is only one annotation. ' however complexification of names is prepended, so the last annotation should be the original one. sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode() Return newEnclosingStatement.ReplaceNode(sourceNode, callSignature) End Function End Class End Class 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 Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private Class VisualBasicCodeGenerator Private Class ExpressionCodeGenerator Inherits VisualBasicCodeGenerator Public Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult) MyBase.New(insertionPoint, selectionResult, analyzerResult) End Sub Public Shared Function IsExtractMethodOnExpression(code As SelectionResult) As Boolean Return code.SelectionInExpression End Function Protected Overrides Function CreateMethodName() As SyntaxToken Dim methodName = "NewMethod" Dim containingScope = VBSelectionResult.GetContainingScope() methodName = GetMethodNameBasedOnExpression(methodName, containingScope) Dim semanticModel = SemanticDocument.SemanticModel Dim nameGenerator = New UniqueNameGenerator(semanticModel) Return SyntaxFactory.Identifier( nameGenerator.CreateUniqueMethodName(containingScope, methodName)) End Function Private Shared Function GetMethodNameBasedOnExpression(methodName As String, expression As SyntaxNode) As String If expression.IsParentKind(SyntaxKind.EqualsValue) AndAlso expression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then Dim varDecl = DirectCast(expression.Parent.Parent, VariableDeclaratorSyntax) If varDecl.Names.Count <> 1 Then Return methodName End If Dim identifierNode = varDecl.Names(0) If identifierNode Is Nothing Then Return methodName End If Dim name = identifierNode.Identifier.ValueText Return If(name IsNot Nothing AndAlso name.Length > 0, MakeMethodName("Get", name, camelCase:=False), methodName) End If If TypeOf expression Is MemberAccessExpressionSyntax Then expression = CType(expression, MemberAccessExpressionSyntax).Name End If If TypeOf expression Is NameSyntax Then Dim lastDottedName = CType(expression, NameSyntax).GetLastDottedName() Dim plainName = CType(lastDottedName, SimpleNameSyntax).Identifier.ValueText Return If(plainName IsNot Nothing AndAlso plainName.Length > 0, MakeMethodName("Get", plainName, camelCase:=False), methodName) End If Return methodName End Function Protected Overrides Function GetInitialStatementsForMethodDefinitions() As ImmutableArray(Of StatementSyntax) Contract.ThrowIfFalse(IsExtractMethodOnExpression(VBSelectionResult)) Dim expression = DirectCast(VBSelectionResult.GetContainingScope(), ExpressionSyntax) Dim statement As StatementSyntax If Me.AnalyzerResult.HasReturnType Then statement = SyntaxFactory.ReturnStatement(expression:=expression) Else ' we have expression for void method (Sub). make the expression as call ' statement if possible we can create call statement only from invocation ' and member access expression. otherwise, it is not a valid expression. ' return error code If expression.Kind <> SyntaxKind.InvocationExpression AndAlso expression.Kind <> SyntaxKind.SimpleMemberAccessExpression Then Return ImmutableArray(Of StatementSyntax).Empty End If statement = SyntaxFactory.ExpressionStatement(expression:=expression) End If Return ImmutableArray.Create(statement) End Function Protected Overrides Function GetOutermostCallSiteContainerToProcess(cancellationToken As CancellationToken) As SyntaxNode Dim callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken) Return If(callSiteContainer, (GetCallSiteContainerFromExpression())) End Function Private Function GetCallSiteContainerFromExpression() As SyntaxNode Dim container = VBSelectionResult.InnermostStatementContainer() Contract.ThrowIfNull(container) Contract.ThrowIfFalse(container.IsStatementContainerNode() OrElse TypeOf container Is TypeBlockSyntax OrElse TypeOf container Is CompilationUnitSyntax) Return container End Function Protected Overrides Function GetFirstStatementOrInitializerSelectedAtCallSite() As StatementSyntax Return VBSelectionResult.GetContainingScopeOf(Of StatementSyntax)() End Function Protected Overrides Function GetLastStatementOrInitializerSelectedAtCallSite() As StatementSyntax Return GetFirstStatementOrInitializerSelectedAtCallSite() End Function Protected Overrides Async Function GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken As CancellationToken) As Task(Of StatementSyntax) Dim enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite() Dim callSignature = CreateCallSignature().WithAdditionalAnnotations(CallSiteAnnotation) Dim sourceNode = VBSelectionResult.GetContainingScope() Contract.ThrowIfTrue( sourceNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso DirectCast(sourceNode.Parent, MemberAccessExpressionSyntax).Name Is sourceNode, "invalid scope. scope is not an expression") ' To lower the chances that replacing sourceNode with callSignature will break the user's ' code, we make the enclosing statement semantically explicit. This ends up being a little ' bit more work because we need to annotate the sourceNode so that we can get back to it ' after rewriting the enclosing statement. Dim sourceNodeAnnotation = New SyntaxAnnotation() Dim enclosingStatementAnnotation = New SyntaxAnnotation() Dim newEnclosingStatement = enclosingStatement _ .ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation)) _ .WithAdditionalAnnotations(enclosingStatementAnnotation) Dim updatedDocument = Await Me.SemanticDocument.Document.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(False) Dim updatedRoot = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) newEnclosingStatement = DirectCast(updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode(), StatementSyntax) ' because of the complexification we cannot guarantee that there is only one annotation. ' however complexification of names is prepended, so the last annotation should be the original one. sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode() Return newEnclosingStatement.ReplaceNode(sourceNode, callSignature) End Function End Class End Class End Class End Namespace
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/VisualBasic/Portable/Binding/DefaultParametersInProgressBinder.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This binder keeps track of the set of parameters that are currently being evaluated ''' so that the set can be passed into the next call to ParameterSymbol.DefaultConstantValue (and ''' its callers). ''' </summary> Friend NotInheritable Class DefaultParametersInProgressBinder Inherits SymbolsInProgressBinder(Of ParameterSymbol) Friend Sub New(inProgress As SymbolsInProgress(Of ParameterSymbol), [next] As Binder) MyBase.New(inProgress, [next]) End Sub Friend Overrides ReadOnly Property DefaultParametersInProgress As SymbolsInProgress(Of ParameterSymbol) Get Return inProgress End Get End Property End Class ''' <summary> ''' This binder keeps track of the set of symbols that are currently being evaluated ''' so that the set can be passed to methods to support breaking infinite recursion ''' cycles. ''' </summary> Friend MustInherit Class SymbolsInProgressBinder(Of T As Symbol) Inherits Binder Protected ReadOnly inProgress As SymbolsInProgress(Of T) Protected Sub New(inProgress As SymbolsInProgress(Of T), [next] As Binder) MyBase.New([next]) Me.inProgress = inProgress 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This binder keeps track of the set of parameters that are currently being evaluated ''' so that the set can be passed into the next call to ParameterSymbol.DefaultConstantValue (and ''' its callers). ''' </summary> Friend NotInheritable Class DefaultParametersInProgressBinder Inherits SymbolsInProgressBinder(Of ParameterSymbol) Friend Sub New(inProgress As SymbolsInProgress(Of ParameterSymbol), [next] As Binder) MyBase.New(inProgress, [next]) End Sub Friend Overrides ReadOnly Property DefaultParametersInProgress As SymbolsInProgress(Of ParameterSymbol) Get Return inProgress End Get End Property End Class ''' <summary> ''' This binder keeps track of the set of symbols that are currently being evaluated ''' so that the set can be passed to methods to support breaking infinite recursion ''' cycles. ''' </summary> Friend MustInherit Class SymbolsInProgressBinder(Of T As Symbol) Inherits Binder Protected ReadOnly inProgress As SymbolsInProgress(Of T) Protected Sub New(inProgress As SymbolsInProgress(Of T), [next] As Binder) MyBase.New([next]) Me.inProgress = inProgress End Sub End Class End Namespace
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/TestUtilities/AbstractCommandHandlerTestState.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.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal abstract class AbstractCommandHandlerTestState : IDisposable { public readonly TestWorkspace Workspace; public readonly IEditorOperations EditorOperations; public readonly ITextUndoHistoryRegistry UndoHistoryRegistry; private readonly ITextView _textView; private readonly DisposableTextView? _createdTextView; private readonly ITextBuffer _subjectBuffer; /// <summary> /// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$), /// and use it to create a selected span in the TextView. /// /// For instance, the following will create a TextView that has a multiline selection with the cursor at the end. /// /// Sub Goo /// {|Selection:SomeMethodCall() /// AnotherMethodCall()$$|} /// End Sub /// /// You can use multiple selection spans to create box selections. /// /// Sub Goo /// {|Selection:$$box|}11111 /// {|Selection:sel|}111 /// {|Selection:ect|}1 /// {|Selection:ion|}1111111 /// End Sub /// </summary> public AbstractCommandHandlerTestState( XElement workspaceElement, TestComposition composition, string? workspaceKind = null, bool makeSeparateBufferForCursor = false, ImmutableArray<string> roles = default) { Workspace = TestWorkspace.CreateWorkspace( workspaceElement, composition: composition, workspaceKind: workspaceKind); if (makeSeparateBufferForCursor) { var languageName = Workspace.Projects.First().Language; var contentType = Workspace.Services.GetLanguageServices(languageName).GetRequiredService<IContentTypeLanguageService>().GetDefaultContentType(); _createdTextView = EditorFactory.CreateView(Workspace.ExportProvider, contentType, roles); _textView = _createdTextView.TextView; _subjectBuffer = _textView.TextBuffer; } else { var cursorDocument = Workspace.Documents.First(d => d.CursorPosition.HasValue); _textView = cursorDocument.GetTextView(); _subjectBuffer = cursorDocument.GetTextBuffer(); if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out var selectionSpanList)) { var firstSpan = selectionSpanList.First(); var lastSpan = selectionSpanList.Last(); var cursorPosition = cursorDocument.CursorPosition!.Value; Assert.True(cursorPosition == firstSpan.Start || cursorPosition == firstSpan.End || cursorPosition == lastSpan.Start || cursorPosition == lastSpan.End, "cursorPosition wasn't at an endpoint of the 'Selection' annotated span"); _textView.Selection.Mode = selectionSpanList.Length > 1 ? TextSelectionMode.Box : TextSelectionMode.Stream; SnapshotPoint boxSelectionStart, boxSelectionEnd; bool isReversed; if (cursorPosition == firstSpan.Start || cursorPosition == lastSpan.End) { // Top-left and bottom-right corners used as anchor points. boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.Start); boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.End); isReversed = cursorPosition == firstSpan.Start; } else { // Top-right and bottom-left corners used as anchor points. boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.End); boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.Start); isReversed = cursorPosition == firstSpan.End; } _textView.Selection.Select( new SnapshotSpan(boxSelectionStart, boxSelectionEnd), isReversed: isReversed); } } this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView); this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>(); } public void Dispose() { _createdTextView?.Dispose(); Workspace.Dispose(); } public T GetService<T>() => Workspace.GetService<T>(); public virtual ITextView TextView { get { return _textView; } } public virtual ITextBuffer SubjectBuffer { get { return _subjectBuffer; } } #region MEF public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>() => (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>(); public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>() => Workspace.ExportProvider.GetExports<TExport, TMetadata>(); public T GetExportedValue<T>() => Workspace.ExportProvider.GetExportedValue<T>(); public IEnumerable<T> GetExportedValues<T>() => Workspace.ExportProvider.GetExportedValues<T>(); #endregion #region editor related operation public virtual void SendBackspace() => EditorOperations.Backspace(); public virtual void SendDelete() => EditorOperations.Delete(); public void SendRightKey(bool extendSelection = false) => EditorOperations.MoveToNextCharacter(extendSelection); public void SendLeftKey(bool extendSelection = false) => EditorOperations.MoveToPreviousCharacter(extendSelection); public void SendMoveToPreviousCharacter(bool extendSelection = false) => EditorOperations.MoveToPreviousCharacter(extendSelection); public virtual void SendDeleteWordToLeft() => EditorOperations.DeleteWordToLeft(); public void SendUndo(int count = 1) { var history = UndoHistoryRegistry.GetHistory(SubjectBuffer); history.Undo(count); } public void SelectAndMoveCaret(int offset) { var currentCaret = GetCaretPoint(); EditorOperations.SelectAndMoveCaret( new VirtualSnapshotPoint(SubjectBuffer.CurrentSnapshot, currentCaret.BufferPosition.Position), new VirtualSnapshotPoint(SubjectBuffer.CurrentSnapshot, currentCaret.BufferPosition.Position + offset)); } #endregion #region test/information/verification public ITextSnapshotLine GetLineFromCurrentCaretPosition() { var caretPosition = GetCaretPoint(); return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition); } public string GetLineTextFromCaretPosition() { var caretPosition = GetCaretPoint(); return caretPosition.BufferPosition.GetContainingLine().GetText(); } public (string TextBeforeCaret, string TextAfterCaret) GetLineTextAroundCaretPosition() { int bufferCaretPosition = GetCaretPoint().BufferPosition; var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(bufferCaretPosition); var lineCaretPosition = bufferCaretPosition - line.Start.Position; var text = line.GetText(); var textBeforeCaret = text.Substring(0, lineCaretPosition); var textAfterCaret = text.Substring(lineCaretPosition, text.Length - lineCaretPosition); return (textBeforeCaret, textAfterCaret); } public string GetDocumentText() => SubjectBuffer.CurrentSnapshot.GetText(); public CaretPosition GetCaretPoint() => TextView.Caret.Position; /// <summary> /// Used in synchronous methods to ensure all outstanding <see cref="IAsyncToken"/> work has been /// completed. /// </summary> public void AssertNoAsynchronousOperationsRunning() { var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); Assert.False(provider.HasPendingWaiter(FeatureAttribute.EventHookup, FeatureAttribute.CompletionSet, FeatureAttribute.SignatureHelp), "IAsyncTokens unexpectedly alive. Call WaitForAsynchronousOperationsAsync before this method"); } // This one is not used by the completion but used by SignatureHelp. public async Task WaitForAsynchronousOperationsAsync() { var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); await provider.WaitAllDispatcherOperationAndTasksAsync(Workspace, FeatureAttribute.EventHookup, FeatureAttribute.CompletionSet, FeatureAttribute.SignatureHelp); } public void AssertMatchesTextStartingAtLine(int line, string text) { var lines = text.Split('\r'); foreach (var expectedLine in lines) { Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim()); line += 1; } } #endregion #region command handler public void SendBackspace(Action<BackspaceKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendDelete(Action<DeleteKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendEscape(Action<EscapeKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendEscape(Func<EscapeKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendUpKey(Action<UpKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendDownKey(Action<DownKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendTab(Action<TabKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendTab(Func<TabKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendBackTab(Action<BackTabKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendBackTab(Func<BackTabKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendReturn(Action<ReturnKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendReturn(Func<ReturnKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendPageUp(Action<PageUpKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendPageDown(Action<PageDownKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendCut(Action<CutCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendPaste(Action<PasteCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendInsertSnippetCommand(Func<InsertSnippetCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendSurroundWithCommand(Func<SurroundWithCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler, TestCommandExecutionContext.Create()); public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action, CommandExecutionContext> commandHandler) { foreach (var ch in typeChars) { var localCh = ch; SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString())); } } public void SendSave(Action<SaveCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendSelectAll(Action<SelectAllCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new SelectAllCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendToggleCompletionMode(Action<ToggleCompletionModeCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new ToggleCompletionModeCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); #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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal abstract class AbstractCommandHandlerTestState : IDisposable { public readonly TestWorkspace Workspace; public readonly IEditorOperations EditorOperations; public readonly ITextUndoHistoryRegistry UndoHistoryRegistry; private readonly ITextView _textView; private readonly DisposableTextView? _createdTextView; private readonly ITextBuffer _subjectBuffer; /// <summary> /// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$), /// and use it to create a selected span in the TextView. /// /// For instance, the following will create a TextView that has a multiline selection with the cursor at the end. /// /// Sub Goo /// {|Selection:SomeMethodCall() /// AnotherMethodCall()$$|} /// End Sub /// /// You can use multiple selection spans to create box selections. /// /// Sub Goo /// {|Selection:$$box|}11111 /// {|Selection:sel|}111 /// {|Selection:ect|}1 /// {|Selection:ion|}1111111 /// End Sub /// </summary> public AbstractCommandHandlerTestState( XElement workspaceElement, TestComposition composition, string? workspaceKind = null, bool makeSeparateBufferForCursor = false, ImmutableArray<string> roles = default) { Workspace = TestWorkspace.CreateWorkspace( workspaceElement, composition: composition, workspaceKind: workspaceKind); if (makeSeparateBufferForCursor) { var languageName = Workspace.Projects.First().Language; var contentType = Workspace.Services.GetLanguageServices(languageName).GetRequiredService<IContentTypeLanguageService>().GetDefaultContentType(); _createdTextView = EditorFactory.CreateView(Workspace.ExportProvider, contentType, roles); _textView = _createdTextView.TextView; _subjectBuffer = _textView.TextBuffer; } else { var cursorDocument = Workspace.Documents.First(d => d.CursorPosition.HasValue); _textView = cursorDocument.GetTextView(); _subjectBuffer = cursorDocument.GetTextBuffer(); if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out var selectionSpanList)) { var firstSpan = selectionSpanList.First(); var lastSpan = selectionSpanList.Last(); var cursorPosition = cursorDocument.CursorPosition!.Value; Assert.True(cursorPosition == firstSpan.Start || cursorPosition == firstSpan.End || cursorPosition == lastSpan.Start || cursorPosition == lastSpan.End, "cursorPosition wasn't at an endpoint of the 'Selection' annotated span"); _textView.Selection.Mode = selectionSpanList.Length > 1 ? TextSelectionMode.Box : TextSelectionMode.Stream; SnapshotPoint boxSelectionStart, boxSelectionEnd; bool isReversed; if (cursorPosition == firstSpan.Start || cursorPosition == lastSpan.End) { // Top-left and bottom-right corners used as anchor points. boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.Start); boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.End); isReversed = cursorPosition == firstSpan.Start; } else { // Top-right and bottom-left corners used as anchor points. boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.End); boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.Start); isReversed = cursorPosition == firstSpan.End; } _textView.Selection.Select( new SnapshotSpan(boxSelectionStart, boxSelectionEnd), isReversed: isReversed); } } this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView); this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>(); } public void Dispose() { _createdTextView?.Dispose(); Workspace.Dispose(); } public T GetService<T>() => Workspace.GetService<T>(); public virtual ITextView TextView { get { return _textView; } } public virtual ITextBuffer SubjectBuffer { get { return _subjectBuffer; } } #region MEF public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>() => (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>(); public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>() => Workspace.ExportProvider.GetExports<TExport, TMetadata>(); public T GetExportedValue<T>() => Workspace.ExportProvider.GetExportedValue<T>(); public IEnumerable<T> GetExportedValues<T>() => Workspace.ExportProvider.GetExportedValues<T>(); #endregion #region editor related operation public virtual void SendBackspace() => EditorOperations.Backspace(); public virtual void SendDelete() => EditorOperations.Delete(); public void SendRightKey(bool extendSelection = false) => EditorOperations.MoveToNextCharacter(extendSelection); public void SendLeftKey(bool extendSelection = false) => EditorOperations.MoveToPreviousCharacter(extendSelection); public void SendMoveToPreviousCharacter(bool extendSelection = false) => EditorOperations.MoveToPreviousCharacter(extendSelection); public virtual void SendDeleteWordToLeft() => EditorOperations.DeleteWordToLeft(); public void SendUndo(int count = 1) { var history = UndoHistoryRegistry.GetHistory(SubjectBuffer); history.Undo(count); } public void SelectAndMoveCaret(int offset) { var currentCaret = GetCaretPoint(); EditorOperations.SelectAndMoveCaret( new VirtualSnapshotPoint(SubjectBuffer.CurrentSnapshot, currentCaret.BufferPosition.Position), new VirtualSnapshotPoint(SubjectBuffer.CurrentSnapshot, currentCaret.BufferPosition.Position + offset)); } #endregion #region test/information/verification public ITextSnapshotLine GetLineFromCurrentCaretPosition() { var caretPosition = GetCaretPoint(); return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition); } public string GetLineTextFromCaretPosition() { var caretPosition = GetCaretPoint(); return caretPosition.BufferPosition.GetContainingLine().GetText(); } public (string TextBeforeCaret, string TextAfterCaret) GetLineTextAroundCaretPosition() { int bufferCaretPosition = GetCaretPoint().BufferPosition; var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(bufferCaretPosition); var lineCaretPosition = bufferCaretPosition - line.Start.Position; var text = line.GetText(); var textBeforeCaret = text.Substring(0, lineCaretPosition); var textAfterCaret = text.Substring(lineCaretPosition, text.Length - lineCaretPosition); return (textBeforeCaret, textAfterCaret); } public string GetDocumentText() => SubjectBuffer.CurrentSnapshot.GetText(); public CaretPosition GetCaretPoint() => TextView.Caret.Position; /// <summary> /// Used in synchronous methods to ensure all outstanding <see cref="IAsyncToken"/> work has been /// completed. /// </summary> public void AssertNoAsynchronousOperationsRunning() { var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); Assert.False(provider.HasPendingWaiter(FeatureAttribute.EventHookup, FeatureAttribute.CompletionSet, FeatureAttribute.SignatureHelp), "IAsyncTokens unexpectedly alive. Call WaitForAsynchronousOperationsAsync before this method"); } // This one is not used by the completion but used by SignatureHelp. public async Task WaitForAsynchronousOperationsAsync() { var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); await provider.WaitAllDispatcherOperationAndTasksAsync(Workspace, FeatureAttribute.EventHookup, FeatureAttribute.CompletionSet, FeatureAttribute.SignatureHelp); } public void AssertMatchesTextStartingAtLine(int line, string text) { var lines = text.Split('\r'); foreach (var expectedLine in lines) { Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim()); line += 1; } } #endregion #region command handler public void SendBackspace(Action<BackspaceKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendDelete(Action<DeleteKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendEscape(Action<EscapeKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendEscape(Func<EscapeKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendUpKey(Action<UpKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendDownKey(Action<DownKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendTab(Action<TabKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendTab(Func<TabKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendBackTab(Action<BackTabKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendBackTab(Func<BackTabKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendReturn(Action<ReturnKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendReturn(Func<ReturnKeyCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendPageUp(Action<PageUpKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendPageDown(Action<PageDownKeyCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendCut(Action<CutCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendPaste(Action<PasteCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendInsertSnippetCommand(Func<InsertSnippetCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public bool SendSurroundWithCommand(Func<SurroundWithCommandArgs, CommandExecutionContext, bool> commandHandler) => commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), TestCommandExecutionContext.Create()); public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler, TestCommandExecutionContext.Create()); public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action, CommandExecutionContext> commandHandler) { foreach (var ch in typeChars) { var localCh = ch; SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString())); } } public void SendSave(Action<SaveCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendSelectAll(Action<SelectAllCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new SelectAllCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); public void SendToggleCompletionMode(Action<ToggleCompletionModeCommandArgs, Action, CommandExecutionContext> commandHandler, Action nextHandler) => commandHandler(new ToggleCompletionModeCommandArgs(TextView, SubjectBuffer), nextHandler, TestCommandExecutionContext.Create()); #endregion } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/Core/GoToImplementation/GoToImplementationCommandHandler.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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CommandHandlers; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToImplementation { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.GoToImplementation)] internal class GoToImplementationCommandHandler : AbstractGoToCommandHandler<IFindUsagesService, GoToImplementationCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToImplementationCommandHandler( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) : base(threadingContext, streamingPresenter) { } public override string DisplayName => EditorFeaturesResources.Go_To_Implementation; protected override string ScopeDescription => EditorFeaturesResources.Locating_implementations; protected override FunctionId FunctionId => FunctionId.CommandHandler_GoToImplementation; protected override Task FindActionAsync(IFindUsagesService service, Document document, int caretPosition, IFindUsagesContext context, CancellationToken cancellationToken) => service.FindImplementationsAsync(document, caretPosition, context, cancellationToken); protected override IFindUsagesService? GetService(Document? document) => document?.GetLanguageService<IFindUsagesService>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CommandHandlers; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToImplementation { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.GoToImplementation)] internal class GoToImplementationCommandHandler : AbstractGoToCommandHandler<IFindUsagesService, GoToImplementationCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToImplementationCommandHandler( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) : base(threadingContext, streamingPresenter) { } public override string DisplayName => EditorFeaturesResources.Go_To_Implementation; protected override string ScopeDescription => EditorFeaturesResources.Locating_implementations; protected override FunctionId FunctionId => FunctionId.CommandHandler_GoToImplementation; protected override Task FindActionAsync(IFindUsagesService service, Document document, int caretPosition, IFindUsagesContext context, CancellationToken cancellationToken) => service.FindImplementationsAsync(document, caretPosition, context, cancellationToken); protected override IFindUsagesService? GetService(Document? document) => document?.GetLanguageService<IFindUsagesService>(); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.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="ru" original="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Все методы</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Всегда использовать для ясности</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">Встроенный сеанс переименования активен для идентификатора "{0}". Снова вызовите встроенное переименование, чтобы получить доступ к дополнительным параметрам. Вы можете в любое время продолжить изменение переименованного идентификатора.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">Применение изменений</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Избегайте неиспользуемых параметров.</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">Изменить конфигурацию</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">Очистка кода не настроена</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">Настройте ее сейчас</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">Не предпочитать "this." или "Me".</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">Больше не показывать это сообщение</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">Вы действительно хотите продолжить? Это может привести к появлению нерабочего кода.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">элементы из неимпортированных пространств имен</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">Расширитель</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">При работе метода извлечения возникли следующие ошибки:</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">Фильтр</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Для локальных переменных, параметров и элементов</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Для выражений доступа к элементам</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">При форматировании документа была выполнена дополнительная очистка</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">Получить справку для "{0}"</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Получить справку для "{0}" из системы Bing</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">Сбор предложений — "{0}"</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">Сбор предложений — ожидается полная загрузка решения</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">Перейти к базовому</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">В арифметических операторах</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">В других бинарных операторах</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">В других операторах</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">В реляционных операторах</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">Размер отступа</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">Встроенные подсказки</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">Вставить заключительную новую строку</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Недопустимое имя сборки</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Недопустимые символы в имени сборки</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">Ключевое слово — управление</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">Обнаружение баз…</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Никогда, если не требуется</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">Новая строка</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Нет</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Методы, не являющиеся открытыми</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">Оператор — перегружен</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">Вставить отслеживание</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Предпочитать "System.HashCode" в "GetHashCode"</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Предпочитать объединенное выражение</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Предпочитать инициализатор коллекции</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Предпочитать составные назначения</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Предпочитать условное выражение оператору if в назначениях</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Предпочитать условное выражение оператору if в операторах return</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Предпочитать явное имя кортежа</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Предпочитать тип платформы</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Предпочитать выводимые имена членов анонимного типа</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Предпочитать выводимые имена элементов кортежа</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Использовать "is null" вместо проверки ссылок на равенство.</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Предпочитать распространение значений NULL</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Предпочитать инициализатор объекта</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Предпочитать предопределенный тип</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Предпочитать поля только для чтения</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Предпочитать упрощенные логические выражения</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">Предпочитать "this." или "Me".</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">Текст препроцессора</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">Пунктуация</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к событию с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к полю с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к методу с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к свойству с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">Переименовать фай_л (тип не соответствует имени файла)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">Переименовать фай_л (недопустимо для разделяемых типов)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">Переименовать _файл с символом</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">Разделительный комментарий</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">Строка — escape-символ</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">Символ — статический</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">Размер интервала табуляции</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">У этого символа нет основания.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">Переключить комментарий блока</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">Переключить комментарий строки</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">Переключение комментария блока...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">Переключение комментария строки...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">Использовать вкладки</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">Участники-пользователи — константы</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">Участники-пользователи — элементы перечисления</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">Пользователи-участники — события</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">Участники-пользователи — методы расширения</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">Участники-пользователи — поля</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">Участники-пользователи — метки</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">Участники-пользователи — локальные</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">Участники-пользователи — методы</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">Участники-пользователи — пространства имен</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">Участники-пользователи — параметры</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">Участники-пользователи — свойства</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">Пользовательские типы — классы</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">Пользовательские типы — делегаты</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">Пользовательские типы — перечисления</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">Пользовательские типы — интерфейсы</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="translated">Пользовательские типы — структуры записей</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">Пользовательские типы — записи</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">Пользовательские типы — структуры</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">Пользовательские типы — параметры типа</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">Строка — Verbatim</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">Ожидание завершения фоновой работы…</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">Предупреждение</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">Комментарии XML Doc — имена атрибутов</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">Комментарии XML Doc — раздел CData</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">Комментарии XML-документа — текст</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">Комментарии XML-документа — разделитель</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">Комментарии XML-документа — комментарий</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">Пользовательские типы — модули</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">Литералы VB XML — имена атрибутов</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">Литералы VB XML — кавычки атрибутов</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">Литералы VB XML — значения атрибутов</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">Литералы VB XML — раздел CData</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">Литералы XML VB — комментарий</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">Литералы XML VB — разделитель</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">Литералы VB XML — встроенные выражения</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">Литералы VB XML — ссылки на сущности</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">Литералы XML VB — имя</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">Литералы VB XML — инструкции по обработке</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">Литералы XML VB — текст</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">Комментарии XML Doc — кавычки атрибутов</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">Комментарии XML Doc — значения атрибутов</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">Ненужный код</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">Грубая редакция</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">При переименовании будет обновлена одна ссылка в одном файле.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">При переименовании будут обновлены ссылки в количестве {0} шт. в одном файле.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">При переименовании будут обновлены ссылки в количестве {0} шт. в следующем числе файлов: {1}.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Да</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">Невозможно переименовать этот элемент, так как он содержится в файле, доступном только для чтения.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">Невозможно переименовать этот элемент, так как он находится в расположении, к которому невозможно перейти.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">Основания: "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">Конфликтов будет разрешено: {0}</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">Реализованные члены "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">{0} неразрешимые конфликты</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">Применение "{0}"...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">Добавление "{0}" к "{1}" с содержимым:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">Добавление проекта "{0}"</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">Удаление проекта "{0}"</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">Изменение ссылок проекта для "{0}"</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">Добавление ссылки "{0}" в "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">Удаление ссылки "{0}" из "{1}"</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">Добавление ссылки анализатора "{0}" к "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">Удаление ссылки анализатора "{0}" из "{1}"</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">Завершение конечных тегов XML</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">Завершающий тег</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">Инкапсулировать поле</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">Применение рефакторинга "инкапсулирования поля" ...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">Выберите определение поля, которое нужно инкапсулировать.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">Заданная рабочая область не поддерживает отмену</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">Идет поиск...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">Отменено.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">Информация не найдена.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">Использований не обнаружено.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Реализует</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Реализуется</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Переопределяет</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Переопределяется</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">Прямой вызов</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">Неявный вызов</target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">Вызов</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">Имеются ссылки в</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">Ссылки не найдены.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">Производных типов не найдено.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">Реализаций не найдено.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} — (Строка {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">Части класса</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">Части структуры</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">Части интерфейса</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">Части типа</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Наследует</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Наследуется</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">Документ с идентичным ключом уже отслеживается.</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Предпочитать автосвойства</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">Документ в настоящее время не отслеживается.</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">Вычисление информации переименования...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">Идет обновление файлов...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">Операция переименования была отменена или является недопустимой.</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">Переименовать символ</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">Изменение буфера текста</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">Операция переименования завершена неправильно. Некоторые файлы должны быть обновлены.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Переименовать "{0}" в "{1}"</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">Предварительный просмотр предупреждения</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(внешний)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">Автоматическое окончание строки</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">Автоматическое завершение...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">Автоматическое завершение пары</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">Встроенный сеанс переименования еще активен. Завершите его прежде, чем начинать новый.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">Этот буфер не является частью рабочей области.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">Этот токен не помещен в рабочую область.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">Необходимо переименовать идентификатор.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">Этот элемент переименовать нельзя.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">Устраните ошибки в коде, прежде чем переименовать этот элемент.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">Нельзя переименовать операторы.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">Нельзя переименовать элементы, определенные в метаданных.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">Нельзя переименовать элементы из предыдущих отправок.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">Панели навигации</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">Идет обновление панелей переходов...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">Токен формата</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Интеллектуальные отступы</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">Найти ссылки</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">Поиск ссылок...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">Поиск ссылок на "{0}"...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">Закомментировать выделенный фрагмент</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">Раскомментировать выделенный фрагмент</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">Комментирование выбранного текста...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">Раскомментирование выбранного текста...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Вставить новую строку</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">Комментарий к документации</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">Вставка комментария документации...</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Извлечение метода</target> <note /> </trans-unit> <trans-unit id="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">Применение рефакторинга "метода извлечения"...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">Форматировать документ</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document...</source> <target state="translated">Идет форматирование документа...</target> <note /> </trans-unit> <trans-unit id="Formatting"> <source>Formatting</source> <target state="translated">Форматирование</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">Форматировать выделенный фрагмент</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">Идет форматирование выбранного текста...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">Не удается перейти к символу, на котором находится курсор.</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Перейти к определению</target> <note /> </trans-unit> <trans-unit id="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">Переход к определению...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">Упорядочить документ</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">Идет упорядочивание документа...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">Выделенное определение</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">Новое имя не является допустимым идентификатором.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">Исправление встроенного переименования</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">Разрешенный конфликт встроенного переименования</target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">Встроенное переименование</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">Переименование</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">Начать переименование</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">Отобразить разрешение конфликтов</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">Поиск токена для переименования...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">Конфликт</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">Навигация по тексту</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">Поиск экстента слова...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">Поиск вмещающего диапазона...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">Поиск диапазона следующего одноуровневого элемента...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">Поиск диапазона предыдущего одноуровневого элемента...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">Переименовать: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">Сеанс лампочки уже закрыт.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">Цвет маркера конечной точки автоматического завершения пары.</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">Переименование членов анонимного типа еще не поддерживается.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">Модуль должен быть подключен к Интерактивному окну.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">Изменения текущих настроек командной строки.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">Непредвиденный текст: "{0}"</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">Этот triggerSpan не входит в данную рабочую область.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">Этот сеанс уже закрыт.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">Транзакция уже выполнена.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">Не ошибка источника, строка или столбец недоступны</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">Не удается сравнить позиции из различных снимков текста</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">Комментарии XML Doc — ссылки на сущности</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">Комментарии XML-документа — имя</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">Комментарии XML Doc — инструкции по обработке</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">Активный оператор</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">Загрузка информации обзора...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">Обзор</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">_Применить</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">Включить _перегрузки</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">Включить _комментарии</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">Включить _строки</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">Применить</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Изменить сигнатуру</target> <note /> </trans-unit> <trans-unit id="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">Просмотреть изменения — {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">Просмотр изменений кода:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">Просмотреть изменения</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Форматировать при вставке</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Идет форматирование вставленного текста...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">Определение объекта скрыто.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">Автоматическое форматирование</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">Можно устранить ошибку без создания параметров "out/ref" структуры. Вы хотите продолжить?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">Изменить сигнатуру:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">Переименование "{0}" в "{1}":</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">Инкапсулировать поле:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">Иерархия вызовов</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">Вызовы к "{0}"</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">Вызовы базового члена "{0}"</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">Вызовы реализации интерфейса "{0}"</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">Вычисление сведений об иерархии вызовов</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">Реализует "{0}"</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">Инициализаторы</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">Ссылки на поле "{0}"</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">Вызовы переопределений</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">_Изменения в предварительной версии</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">Применить</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Отмена</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">Изменения</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</source> <target state="translated">Предварительный просмотр изменений</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">Форматирование при фиксации IntelliSense</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">Отслеживание переименования</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">Идет удаление "{0}" из "{1}" с содержимым:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">"{0}" не поддерживает операцию "{1}", но может содержать вложенные "{2}" (см. "{2}.{3}"), которые поддерживают эту операцию.</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">Завершение скобок</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">Невозможно применить операцию при активном сеансе переименования.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">Сеанс отслеживания переименования отменен и больше не доступен.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">Выделенная записанная ссылка</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">Курсор должен находиться на имени элемента.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">Соответствие скобок</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">Поиск реализаций...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">Перейти к реализации</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">Этот символ не имеет реализации.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">Новое имя: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">Измените любое выделенное место, чтобы начать переименование.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Вставить</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">Идет переход...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">Предложение с многоточием (…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'Ссылки "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'Реализации "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'Объявления "{0}"</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">Конфликт встроенного переименования</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">Цвет фона и цвет границы поля "Встроенное переименование"</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">Текст поля "Встроенное переименование"</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">Изменение блочных комментариев</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">Закомментировать/раскомментировать выбранный фрагмент</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">Завершение кода</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">Выполнять в интерактивном режиме</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Извлечь интерфейс</target> <note /> </trans-unit> <trans-unit id="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">Перейти к смежному элементу</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">Интерактивный режим</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">Вставить в интерактивном режиме</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">Перейти к выделенной ссылке</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Структура</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">Отмена отслеживания переименования</target> <note /> </trans-unit> <trans-unit id="Regex_Comment"> <source>Regex - Comment</source> <target state="translated">Регулярные выражения — комментарий</target> <note /> </trans-unit> <trans-unit id="Regex_Character_Class"> <source>Regex - Character Class</source> <target state="translated">Регулярные выражения — класс символов</target> <note /> </trans-unit> <trans-unit id="Regex_Alternation"> <source>Regex - Alternation</source> <target state="translated">Регулярные выражения — чередование</target> <note /> </trans-unit> <trans-unit id="Regex_Anchor"> <source>Regex - Anchor</source> <target state="translated">Регулярные выражения — якорь</target> <note /> </trans-unit> <trans-unit id="Regex_Quantifier"> <source>Regex - Quantifier</source> <target state="translated">Регулярные выражения — квантификатор</target> <note /> </trans-unit> <trans-unit id="Regex_SelfEscapedCharacter"> <source>Regex - Self Escaped Character</source> <target state="translated">Регулярные выражения — символ с самостоятельным экранированием</target> <note /> </trans-unit> <trans-unit id="Regex_Grouping"> <source>Regex - Grouping</source> <target state="translated">Регулярные выражения — группировка</target> <note /> </trans-unit> <trans-unit id="Regex_Text"> <source>Regex - Text</source> <target state="translated">Регулярные выражения — текст</target> <note /> </trans-unit> <trans-unit id="Regex_OtherEscape"> <source>Regex - Other Escape</source> <target state="translated">Регулярные выражения — другая escape-последовательность</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">Справка по сигнатурам</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">Средство форматирования смарт-токена</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="ru" original="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Все методы</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Всегда использовать для ясности</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">Встроенный сеанс переименования активен для идентификатора "{0}". Снова вызовите встроенное переименование, чтобы получить доступ к дополнительным параметрам. Вы можете в любое время продолжить изменение переименованного идентификатора.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">Применение изменений</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Избегайте неиспользуемых параметров.</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">Изменить конфигурацию</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">Очистка кода не настроена</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">Настройте ее сейчас</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">Не предпочитать "this." или "Me".</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">Больше не показывать это сообщение</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">Вы действительно хотите продолжить? Это может привести к появлению нерабочего кода.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">элементы из неимпортированных пространств имен</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">Расширитель</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">При работе метода извлечения возникли следующие ошибки:</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">Фильтр</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Для локальных переменных, параметров и элементов</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Для выражений доступа к элементам</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">При форматировании документа была выполнена дополнительная очистка</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">Получить справку для "{0}"</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Получить справку для "{0}" из системы Bing</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">Сбор предложений — "{0}"</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">Сбор предложений — ожидается полная загрузка решения</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">Перейти к базовому</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">В арифметических операторах</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">В других бинарных операторах</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">В других операторах</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">В реляционных операторах</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">Размер отступа</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">Встроенные подсказки</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">Вставить заключительную новую строку</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Недопустимое имя сборки</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Недопустимые символы в имени сборки</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">Ключевое слово — управление</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">Обнаружение баз…</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Никогда, если не требуется</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">Новая строка</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Нет</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Методы, не являющиеся открытыми</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">Оператор — перегружен</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">Вставить отслеживание</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Предпочитать "System.HashCode" в "GetHashCode"</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Предпочитать объединенное выражение</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Предпочитать инициализатор коллекции</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Предпочитать составные назначения</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Предпочитать условное выражение оператору if в назначениях</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Предпочитать условное выражение оператору if в операторах return</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Предпочитать явное имя кортежа</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Предпочитать тип платформы</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Предпочитать выводимые имена членов анонимного типа</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Предпочитать выводимые имена элементов кортежа</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Использовать "is null" вместо проверки ссылок на равенство.</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Предпочитать распространение значений NULL</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Предпочитать инициализатор объекта</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Предпочитать предопределенный тип</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Предпочитать поля только для чтения</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Предпочитать упрощенные логические выражения</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">Предпочитать "this." или "Me".</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">Текст препроцессора</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">Пунктуация</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к событию с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к полю с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к методу с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">Квалифицировать доступ к свойству с помощью "this" или "Me"</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">Переименовать фай_л (тип не соответствует имени файла)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">Переименовать фай_л (недопустимо для разделяемых типов)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">Переименовать _файл с символом</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">Разделительный комментарий</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">Строка — escape-символ</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">Символ — статический</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">Размер интервала табуляции</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">У этого символа нет основания.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">Переключить комментарий блока</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">Переключить комментарий строки</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">Переключение комментария блока...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">Переключение комментария строки...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">Использовать вкладки</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">Участники-пользователи — константы</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">Участники-пользователи — элементы перечисления</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">Пользователи-участники — события</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">Участники-пользователи — методы расширения</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">Участники-пользователи — поля</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">Участники-пользователи — метки</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">Участники-пользователи — локальные</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">Участники-пользователи — методы</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">Участники-пользователи — пространства имен</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">Участники-пользователи — параметры</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">Участники-пользователи — свойства</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">Пользовательские типы — классы</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">Пользовательские типы — делегаты</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">Пользовательские типы — перечисления</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">Пользовательские типы — интерфейсы</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="translated">Пользовательские типы — структуры записей</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">Пользовательские типы — записи</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">Пользовательские типы — структуры</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">Пользовательские типы — параметры типа</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">Строка — Verbatim</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">Ожидание завершения фоновой работы…</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">Предупреждение</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">Комментарии XML Doc — имена атрибутов</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">Комментарии XML Doc — раздел CData</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">Комментарии XML-документа — текст</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">Комментарии XML-документа — разделитель</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">Комментарии XML-документа — комментарий</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">Пользовательские типы — модули</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">Литералы VB XML — имена атрибутов</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">Литералы VB XML — кавычки атрибутов</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">Литералы VB XML — значения атрибутов</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">Литералы VB XML — раздел CData</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">Литералы XML VB — комментарий</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">Литералы XML VB — разделитель</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">Литералы VB XML — встроенные выражения</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">Литералы VB XML — ссылки на сущности</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">Литералы XML VB — имя</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">Литералы VB XML — инструкции по обработке</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">Литералы XML VB — текст</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">Комментарии XML Doc — кавычки атрибутов</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">Комментарии XML Doc — значения атрибутов</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">Ненужный код</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">Грубая редакция</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">При переименовании будет обновлена одна ссылка в одном файле.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">При переименовании будут обновлены ссылки в количестве {0} шт. в одном файле.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">При переименовании будут обновлены ссылки в количестве {0} шт. в следующем числе файлов: {1}.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Да</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">Невозможно переименовать этот элемент, так как он содержится в файле, доступном только для чтения.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">Невозможно переименовать этот элемент, так как он находится в расположении, к которому невозможно перейти.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">Основания: "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">Конфликтов будет разрешено: {0}</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">Реализованные члены "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">{0} неразрешимые конфликты</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">Применение "{0}"...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">Добавление "{0}" к "{1}" с содержимым:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">Добавление проекта "{0}"</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">Удаление проекта "{0}"</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">Изменение ссылок проекта для "{0}"</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">Добавление ссылки "{0}" в "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">Удаление ссылки "{0}" из "{1}"</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">Добавление ссылки анализатора "{0}" к "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">Удаление ссылки анализатора "{0}" из "{1}"</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">Завершение конечных тегов XML</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">Завершающий тег</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">Инкапсулировать поле</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">Применение рефакторинга "инкапсулирования поля" ...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">Выберите определение поля, которое нужно инкапсулировать.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">Заданная рабочая область не поддерживает отмену</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">Идет поиск...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">Отменено.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">Информация не найдена.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">Использований не обнаружено.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Реализует</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Реализуется</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Переопределяет</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Переопределяется</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">Прямой вызов</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">Неявный вызов</target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">Вызов</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">Имеются ссылки в</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">Ссылки не найдены.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">Производных типов не найдено.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">Реализаций не найдено.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} — (Строка {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">Части класса</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">Части структуры</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">Части интерфейса</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">Части типа</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Наследует</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Наследуется</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">Документ с идентичным ключом уже отслеживается.</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Предпочитать автосвойства</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">Документ в настоящее время не отслеживается.</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">Вычисление информации переименования...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">Идет обновление файлов...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">Операция переименования была отменена или является недопустимой.</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">Переименовать символ</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">Изменение буфера текста</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">Операция переименования завершена неправильно. Некоторые файлы должны быть обновлены.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Переименовать "{0}" в "{1}"</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">Предварительный просмотр предупреждения</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(внешний)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">Автоматическое окончание строки</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">Автоматическое завершение...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">Автоматическое завершение пары</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">Встроенный сеанс переименования еще активен. Завершите его прежде, чем начинать новый.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">Этот буфер не является частью рабочей области.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">Этот токен не помещен в рабочую область.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">Необходимо переименовать идентификатор.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">Этот элемент переименовать нельзя.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">Устраните ошибки в коде, прежде чем переименовать этот элемент.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">Нельзя переименовать операторы.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">Нельзя переименовать элементы, определенные в метаданных.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">Нельзя переименовать элементы из предыдущих отправок.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">Панели навигации</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">Идет обновление панелей переходов...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">Токен формата</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Интеллектуальные отступы</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">Найти ссылки</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">Поиск ссылок...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">Поиск ссылок на "{0}"...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">Закомментировать выделенный фрагмент</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">Раскомментировать выделенный фрагмент</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">Комментирование выбранного текста...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">Раскомментирование выбранного текста...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Вставить новую строку</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">Комментарий к документации</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">Вставка комментария документации...</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Извлечение метода</target> <note /> </trans-unit> <trans-unit id="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">Применение рефакторинга "метода извлечения"...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">Форматировать документ</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document...</source> <target state="translated">Идет форматирование документа...</target> <note /> </trans-unit> <trans-unit id="Formatting"> <source>Formatting</source> <target state="translated">Форматирование</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">Форматировать выделенный фрагмент</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">Идет форматирование выбранного текста...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">Не удается перейти к символу, на котором находится курсор.</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Перейти к определению</target> <note /> </trans-unit> <trans-unit id="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">Переход к определению...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">Упорядочить документ</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">Идет упорядочивание документа...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">Выделенное определение</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">Новое имя не является допустимым идентификатором.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">Исправление встроенного переименования</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">Разрешенный конфликт встроенного переименования</target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">Встроенное переименование</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">Переименование</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">Начать переименование</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">Отобразить разрешение конфликтов</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">Поиск токена для переименования...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">Конфликт</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">Навигация по тексту</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">Поиск экстента слова...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">Поиск вмещающего диапазона...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">Поиск диапазона следующего одноуровневого элемента...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">Поиск диапазона предыдущего одноуровневого элемента...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">Переименовать: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">Сеанс лампочки уже закрыт.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">Цвет маркера конечной точки автоматического завершения пары.</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">Переименование членов анонимного типа еще не поддерживается.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">Модуль должен быть подключен к Интерактивному окну.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">Изменения текущих настроек командной строки.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">Непредвиденный текст: "{0}"</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">Этот triggerSpan не входит в данную рабочую область.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">Этот сеанс уже закрыт.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">Транзакция уже выполнена.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">Не ошибка источника, строка или столбец недоступны</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">Не удается сравнить позиции из различных снимков текста</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">Комментарии XML Doc — ссылки на сущности</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">Комментарии XML-документа — имя</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">Комментарии XML Doc — инструкции по обработке</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">Активный оператор</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">Загрузка информации обзора...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">Обзор</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">_Применить</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">Включить _перегрузки</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">Включить _комментарии</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">Включить _строки</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">Применить</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Изменить сигнатуру</target> <note /> </trans-unit> <trans-unit id="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">Просмотреть изменения — {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">Просмотр изменений кода:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">Просмотреть изменения</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Форматировать при вставке</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Идет форматирование вставленного текста...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">Определение объекта скрыто.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">Автоматическое форматирование</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">Можно устранить ошибку без создания параметров "out/ref" структуры. Вы хотите продолжить?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">Изменить сигнатуру:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">Переименование "{0}" в "{1}":</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">Инкапсулировать поле:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">Иерархия вызовов</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">Вызовы к "{0}"</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">Вызовы базового члена "{0}"</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">Вызовы реализации интерфейса "{0}"</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">Вычисление сведений об иерархии вызовов</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">Реализует "{0}"</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">Инициализаторы</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">Ссылки на поле "{0}"</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">Вызовы переопределений</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">_Изменения в предварительной версии</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">Применить</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Отмена</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">Изменения</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</source> <target state="translated">Предварительный просмотр изменений</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">Форматирование при фиксации IntelliSense</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">Отслеживание переименования</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">Идет удаление "{0}" из "{1}" с содержимым:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">"{0}" не поддерживает операцию "{1}", но может содержать вложенные "{2}" (см. "{2}.{3}"), которые поддерживают эту операцию.</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">Завершение скобок</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">Невозможно применить операцию при активном сеансе переименования.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">Сеанс отслеживания переименования отменен и больше не доступен.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">Выделенная записанная ссылка</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">Курсор должен находиться на имени элемента.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">Соответствие скобок</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">Поиск реализаций...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">Перейти к реализации</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">Этот символ не имеет реализации.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">Новое имя: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">Измените любое выделенное место, чтобы начать переименование.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Вставить</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">Идет переход...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">Предложение с многоточием (…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'Ссылки "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'Реализации "{0}"</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'Объявления "{0}"</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">Конфликт встроенного переименования</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">Цвет фона и цвет границы поля "Встроенное переименование"</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">Текст поля "Встроенное переименование"</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">Изменение блочных комментариев</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">Закомментировать/раскомментировать выбранный фрагмент</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">Завершение кода</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">Выполнять в интерактивном режиме</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Извлечь интерфейс</target> <note /> </trans-unit> <trans-unit id="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">Перейти к смежному элементу</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">Интерактивный режим</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">Вставить в интерактивном режиме</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">Перейти к выделенной ссылке</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Структура</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">Отмена отслеживания переименования</target> <note /> </trans-unit> <trans-unit id="Regex_Comment"> <source>Regex - Comment</source> <target state="translated">Регулярные выражения — комментарий</target> <note /> </trans-unit> <trans-unit id="Regex_Character_Class"> <source>Regex - Character Class</source> <target state="translated">Регулярные выражения — класс символов</target> <note /> </trans-unit> <trans-unit id="Regex_Alternation"> <source>Regex - Alternation</source> <target state="translated">Регулярные выражения — чередование</target> <note /> </trans-unit> <trans-unit id="Regex_Anchor"> <source>Regex - Anchor</source> <target state="translated">Регулярные выражения — якорь</target> <note /> </trans-unit> <trans-unit id="Regex_Quantifier"> <source>Regex - Quantifier</source> <target state="translated">Регулярные выражения — квантификатор</target> <note /> </trans-unit> <trans-unit id="Regex_SelfEscapedCharacter"> <source>Regex - Self Escaped Character</source> <target state="translated">Регулярные выражения — символ с самостоятельным экранированием</target> <note /> </trans-unit> <trans-unit id="Regex_Grouping"> <source>Regex - Grouping</source> <target state="translated">Регулярные выражения — группировка</target> <note /> </trans-unit> <trans-unit id="Regex_Text"> <source>Regex - Text</source> <target state="translated">Регулярные выражения — текст</target> <note /> </trans-unit> <trans-unit id="Regex_OtherEscape"> <source>Regex - Other Escape</source> <target state="translated">Регулярные выражения — другая escape-последовательность</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">Справка по сигнатурам</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">Средство форматирования смарт-токена</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Analyzers/CSharp/CodeFixes/UseSimpleUsingStatement/UseSimpleUsingStatementCodeFixProvider.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.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.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseSimpleUsingStatement { using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseSimpleUsingStatement), Shared] internal class UseSimpleUsingStatementCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseSimpleUsingStatementCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var topmostUsingStatements = diagnostics.Select(d => (UsingStatementSyntax)d.AdditionalLocations[0].FindNode(cancellationToken)).ToSet(); var blocks = topmostUsingStatements.Select(u => (BlockSyntax)u.Parent); // Process blocks in reverse order so we rewrite from inside-to-outside with nested // usings. var root = editor.OriginalRoot; var updatedRoot = root.ReplaceNodes( blocks.OrderByDescending(b => b.SpanStart), (original, current) => RewriteBlock(original, current, topmostUsingStatements)); editor.ReplaceNode(root, updatedRoot); return Task.CompletedTask; } private static SyntaxNode RewriteBlock( BlockSyntax originalBlock, BlockSyntax currentBlock, ISet<UsingStatementSyntax> topmostUsingStatements) { if (originalBlock.Statements.Count == currentBlock.Statements.Count) { var statementToUpdateIndex = originalBlock.Statements.IndexOf(s => topmostUsingStatements.Contains(s)); var statementToUpdate = currentBlock.Statements[statementToUpdateIndex]; if (statementToUpdate is UsingStatementSyntax usingStatement && usingStatement.Declaration != null) { var updatedStatements = currentBlock.Statements.ReplaceRange( statementToUpdate, Expand(usingStatement)); return currentBlock.WithStatements(updatedStatements); } } return currentBlock; } private static IEnumerable<StatementSyntax> Expand(UsingStatementSyntax usingStatement) { var result = new List<StatementSyntax>(); var remainingTrivia = Expand(result, usingStatement); if (remainingTrivia.Any(t => t.IsSingleOrMultiLineComment() || t.IsDirective)) { var lastStatement = result[result.Count - 1]; result[result.Count - 1] = lastStatement.WithAppendedTrailingTrivia( remainingTrivia.Insert(0, CSharpSyntaxFacts.Instance.ElasticCarriageReturnLineFeed)); } for (int i = 0, n = result.Count; i < n; i++) { result[i] = result[i].WithAdditionalAnnotations(Formatter.Annotation); } return result; } private static SyntaxTriviaList Expand(List<StatementSyntax> result, UsingStatementSyntax usingStatement) { // First, convert the using-statement into a using-declaration. result.Add(Convert(usingStatement)); switch (usingStatement.Statement) { case BlockSyntax blockSyntax: var statements = blockSyntax.Statements; if (!statements.Any()) { return blockSyntax.CloseBraceToken.LeadingTrivia; } var openBraceTrailingTrivia = blockSyntax.OpenBraceToken.TrailingTrivia; var usingHasEndOfLineTrivia = usingStatement.CloseParenToken.TrailingTrivia .Any(SyntaxKind.EndOfLineTrivia); if (!usingHasEndOfLineTrivia) { var newFirstStatement = statements.First() .WithPrependedLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed); statements = statements.Replace(statements.First(), newFirstStatement); } if (openBraceTrailingTrivia.Any(t => t.IsSingleOrMultiLineComment())) { var newFirstStatement = statements.First() .WithPrependedLeadingTrivia(openBraceTrailingTrivia); statements = statements.Replace(statements.First(), newFirstStatement); } var closeBraceTrailingTrivia = blockSyntax.CloseBraceToken.TrailingTrivia; if (closeBraceTrailingTrivia.Any(t => t.IsSingleOrMultiLineComment())) { var newLastStatement = statements.Last() .WithAppendedTrailingTrivia(closeBraceTrailingTrivia); statements = statements.Replace(statements.Last(), newLastStatement); } // if we hit a block, then inline all the statements in the block into // the final list of statements. result.AddRange(statements); return blockSyntax.CloseBraceToken.LeadingTrivia; case UsingStatementSyntax childUsing when childUsing.Declaration != null: // If we have a directly nested using-statement, then recurse into that // expanding it and handle its children as well. return Expand(result, childUsing); case StatementSyntax anythingElse: // Any other statement should be untouched and just be placed next in the // final list of statements. result.Add(anythingElse); return default; } return default; } private static LocalDeclarationStatementSyntax Convert(UsingStatementSyntax usingStatement) { return LocalDeclarationStatement( usingStatement.AwaitKeyword, usingStatement.UsingKeyword, modifiers: default, usingStatement.Declaration, Token(SyntaxKind.SemicolonToken)).WithTrailingTrivia(usingStatement.CloseParenToken.TrailingTrivia); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_simple_using_statement, createChangedDocument, CSharpAnalyzersResources.Use_simple_using_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. #nullable disable using System; using System.Collections.Generic; 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.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseSimpleUsingStatement { using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseSimpleUsingStatement), Shared] internal class UseSimpleUsingStatementCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseSimpleUsingStatementCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var topmostUsingStatements = diagnostics.Select(d => (UsingStatementSyntax)d.AdditionalLocations[0].FindNode(cancellationToken)).ToSet(); var blocks = topmostUsingStatements.Select(u => (BlockSyntax)u.Parent); // Process blocks in reverse order so we rewrite from inside-to-outside with nested // usings. var root = editor.OriginalRoot; var updatedRoot = root.ReplaceNodes( blocks.OrderByDescending(b => b.SpanStart), (original, current) => RewriteBlock(original, current, topmostUsingStatements)); editor.ReplaceNode(root, updatedRoot); return Task.CompletedTask; } private static SyntaxNode RewriteBlock( BlockSyntax originalBlock, BlockSyntax currentBlock, ISet<UsingStatementSyntax> topmostUsingStatements) { if (originalBlock.Statements.Count == currentBlock.Statements.Count) { var statementToUpdateIndex = originalBlock.Statements.IndexOf(s => topmostUsingStatements.Contains(s)); var statementToUpdate = currentBlock.Statements[statementToUpdateIndex]; if (statementToUpdate is UsingStatementSyntax usingStatement && usingStatement.Declaration != null) { var updatedStatements = currentBlock.Statements.ReplaceRange( statementToUpdate, Expand(usingStatement)); return currentBlock.WithStatements(updatedStatements); } } return currentBlock; } private static IEnumerable<StatementSyntax> Expand(UsingStatementSyntax usingStatement) { var result = new List<StatementSyntax>(); var remainingTrivia = Expand(result, usingStatement); if (remainingTrivia.Any(t => t.IsSingleOrMultiLineComment() || t.IsDirective)) { var lastStatement = result[result.Count - 1]; result[result.Count - 1] = lastStatement.WithAppendedTrailingTrivia( remainingTrivia.Insert(0, CSharpSyntaxFacts.Instance.ElasticCarriageReturnLineFeed)); } for (int i = 0, n = result.Count; i < n; i++) { result[i] = result[i].WithAdditionalAnnotations(Formatter.Annotation); } return result; } private static SyntaxTriviaList Expand(List<StatementSyntax> result, UsingStatementSyntax usingStatement) { // First, convert the using-statement into a using-declaration. result.Add(Convert(usingStatement)); switch (usingStatement.Statement) { case BlockSyntax blockSyntax: var statements = blockSyntax.Statements; if (!statements.Any()) { return blockSyntax.CloseBraceToken.LeadingTrivia; } var openBraceTrailingTrivia = blockSyntax.OpenBraceToken.TrailingTrivia; var usingHasEndOfLineTrivia = usingStatement.CloseParenToken.TrailingTrivia .Any(SyntaxKind.EndOfLineTrivia); if (!usingHasEndOfLineTrivia) { var newFirstStatement = statements.First() .WithPrependedLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed); statements = statements.Replace(statements.First(), newFirstStatement); } if (openBraceTrailingTrivia.Any(t => t.IsSingleOrMultiLineComment())) { var newFirstStatement = statements.First() .WithPrependedLeadingTrivia(openBraceTrailingTrivia); statements = statements.Replace(statements.First(), newFirstStatement); } var closeBraceTrailingTrivia = blockSyntax.CloseBraceToken.TrailingTrivia; if (closeBraceTrailingTrivia.Any(t => t.IsSingleOrMultiLineComment())) { var newLastStatement = statements.Last() .WithAppendedTrailingTrivia(closeBraceTrailingTrivia); statements = statements.Replace(statements.Last(), newLastStatement); } // if we hit a block, then inline all the statements in the block into // the final list of statements. result.AddRange(statements); return blockSyntax.CloseBraceToken.LeadingTrivia; case UsingStatementSyntax childUsing when childUsing.Declaration != null: // If we have a directly nested using-statement, then recurse into that // expanding it and handle its children as well. return Expand(result, childUsing); case StatementSyntax anythingElse: // Any other statement should be untouched and just be placed next in the // final list of statements. result.Add(anythingElse); return default; } return default; } private static LocalDeclarationStatementSyntax Convert(UsingStatementSyntax usingStatement) { return LocalDeclarationStatement( usingStatement.AwaitKeyword, usingStatement.UsingKeyword, modifiers: default, usingStatement.Declaration, Token(SyntaxKind.SemicolonToken)).WithTrailingTrivia(usingStatement.CloseParenToken.TrailingTrivia); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_simple_using_statement, createChangedDocument, CSharpAnalyzersResources.Use_simple_using_statement) { } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.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.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsDocumentationComment(SyntaxNode node); bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetObjectCreationInitializer(SyntaxNode node); SyntaxNode GetObjectCreationType(SyntaxNode node); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); bool IsExpressionOfInvocationExpression(SyntaxNode? node); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node); SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode? node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList); [return: NotNullIfNotNull("node")] SyntaxNode? GetExpressionOfArgument(SyntaxNode? node); SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node); SyntaxNode GetNameOfAttribute(SyntaxNode node); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode? node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node); SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node); SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node); bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsThrowExpression(SyntaxNode node); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node); List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit); SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit); bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> SyntaxNode? TryGetBindableParent(SyntaxToken token); IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); /// <summary> /// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see /// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/> /// then the span through the base-list will be considered. /// </summary> bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration); bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter); bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method); bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction); bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration); bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement); bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement); bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement); bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); SyntaxNode? GetNextExecutableStatement(SyntaxNode statement); ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node); TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode; ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root); ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken); bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken); bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken); string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); Location GetDeconstructionReferenceLocation(SyntaxNode node); SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); bool CanHaveAccessibility(SyntaxNode declaration); /// <summary> /// Gets the accessibility of the declaration. /// </summary> Accessibility GetAccessibility(SyntaxNode declaration); void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault); SyntaxTokenList GetModifierTokens(SyntaxNode? declaration); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> DeclarationKind GetDeclarationKind(SyntaxNode declaration); bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression); bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node); bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node); } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
// 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.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsDocumentationComment(SyntaxNode node); bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetObjectCreationInitializer(SyntaxNode node); SyntaxNode GetObjectCreationType(SyntaxNode node); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); bool IsExpressionOfInvocationExpression(SyntaxNode? node); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node); SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode? node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList); [return: NotNullIfNotNull("node")] SyntaxNode? GetExpressionOfArgument(SyntaxNode? node); SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node); SyntaxNode GetNameOfAttribute(SyntaxNode node); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode? node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node); SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node); SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node); bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsThrowExpression(SyntaxNode node); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node); List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit); SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit); bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> SyntaxNode? TryGetBindableParent(SyntaxToken token); IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); /// <summary> /// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see /// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/> /// then the span through the base-list will be considered. /// </summary> bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration); bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter); bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method); bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction); bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration); bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement); bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement); bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement); bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); SyntaxNode? GetNextExecutableStatement(SyntaxNode statement); ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node); TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode; ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root); ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken); bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken); bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken); string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); Location GetDeconstructionReferenceLocation(SyntaxNode node); SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); bool CanHaveAccessibility(SyntaxNode declaration); /// <summary> /// Gets the accessibility of the declaration. /// </summary> Accessibility GetAccessibility(SyntaxNode declaration); void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault); SyntaxTokenList GetModifierTokens(SyntaxNode? declaration); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> DeclarationKind GetDeclarationKind(SyntaxNode declaration); bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression); bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node); bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node); } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceVariableService_IntroduceQueryLocal.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.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable Partial Friend Class VisualBasicIntroduceVariableService Protected Overrides Function IntroduceQueryLocalAsync( document As SemanticDocument, expression As ExpressionSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Task(Of Document) Dim oldOutermostQuery = expression.GetAncestorsOrThis(Of QueryExpressionSyntax)().LastOrDefault() Dim newLocalNameToken = GenerateUniqueLocalName( document, expression, isConstant:=False, containerOpt:=oldOutermostQuery, cancellationToken:=cancellationToken) Dim newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken) Dim letClause = SyntaxFactory.LetClause( SyntaxFactory.ExpressionRangeVariable( SyntaxFactory.VariableNameEquals( SyntaxFactory.ModifiedIdentifier(newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()))), expression)).WithAdditionalAnnotations(Formatter.Annotation) Dim matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken) Dim innermostClauses = New HashSet(Of QueryClauseSyntax)( matches.Select(Function(expr) expr.GetAncestor(Of QueryClauseSyntax)())) If innermostClauses.Count = 1 Then ' If there was only one match, or all the matches came from the same ' statement, then we want to place the declaration right above that ' statement. Note: we special case this because the statement we are going ' to go above might not be in a block and we may have to generate it Return Task.FromResult(IntroduceQueryLocalForSingleOccurrence( document, expression, newLocalName, letClause, allOccurrences, cancellationToken)) End If Dim oldInnerMostCommonQuery = matches.FindInnermostCommonNode(Of QueryExpressionSyntax)() Dim newInnerMostQuery = Rewrite(document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken) Dim allAffectedClauses = New HashSet(Of QueryClauseSyntax)( matches.SelectMany(Function(expr) expr.GetAncestorsOrThis(Of QueryClauseSyntax)())) Dim oldClauses = oldInnerMostCommonQuery.Clauses Dim newClauses = newInnerMostQuery.Clauses Dim firstClauseAffectedInQuery = oldClauses.First(AddressOf allAffectedClauses.Contains) Dim firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery) Dim finalClauses = newClauses.Take(firstClauseAffectedIndex). Concat(letClause). Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList() Dim finalQuery = newInnerMostQuery.WithClauses(SyntaxFactory.List(finalClauses)) Dim newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery) Return Task.FromResult(document.Document.WithSyntaxRoot(newRoot)) End Function Private Function IntroduceQueryLocalForSingleOccurrence( document As SemanticDocument, expression As ExpressionSyntax, newLocalName As NameSyntax, letClause As LetClauseSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Document Dim oldClause = expression.GetAncestor(Of QueryClauseSyntax)() Dim newClause = Rewrite(document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken) Dim oldQuery = DirectCast(oldClause.Parent, QueryExpressionSyntax) Dim newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause) Dim newRoot = document.Root.ReplaceNode(oldQuery, newQuery) Return document.Document.WithSyntaxRoot(newRoot) End Function Private Shared Function GetNewQuery( oldQuery As QueryExpressionSyntax, oldClause As QueryClauseSyntax, newClause As QueryClauseSyntax, letClause As LetClauseSyntax) As QueryExpressionSyntax Dim oldClauses = oldQuery.Clauses Dim oldClauseIndex = oldClauses.IndexOf(oldClause) Dim newClauses = oldClauses.Take(oldClauseIndex). Concat(letClause). Concat(newClause). Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList() Return oldQuery.WithClauses(SyntaxFactory.List(newClauses)) 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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable Partial Friend Class VisualBasicIntroduceVariableService Protected Overrides Function IntroduceQueryLocalAsync( document As SemanticDocument, expression As ExpressionSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Task(Of Document) Dim oldOutermostQuery = expression.GetAncestorsOrThis(Of QueryExpressionSyntax)().LastOrDefault() Dim newLocalNameToken = GenerateUniqueLocalName( document, expression, isConstant:=False, containerOpt:=oldOutermostQuery, cancellationToken:=cancellationToken) Dim newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken) Dim letClause = SyntaxFactory.LetClause( SyntaxFactory.ExpressionRangeVariable( SyntaxFactory.VariableNameEquals( SyntaxFactory.ModifiedIdentifier(newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()))), expression)).WithAdditionalAnnotations(Formatter.Annotation) Dim matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken) Dim innermostClauses = New HashSet(Of QueryClauseSyntax)( matches.Select(Function(expr) expr.GetAncestor(Of QueryClauseSyntax)())) If innermostClauses.Count = 1 Then ' If there was only one match, or all the matches came from the same ' statement, then we want to place the declaration right above that ' statement. Note: we special case this because the statement we are going ' to go above might not be in a block and we may have to generate it Return Task.FromResult(IntroduceQueryLocalForSingleOccurrence( document, expression, newLocalName, letClause, allOccurrences, cancellationToken)) End If Dim oldInnerMostCommonQuery = matches.FindInnermostCommonNode(Of QueryExpressionSyntax)() Dim newInnerMostQuery = Rewrite(document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken) Dim allAffectedClauses = New HashSet(Of QueryClauseSyntax)( matches.SelectMany(Function(expr) expr.GetAncestorsOrThis(Of QueryClauseSyntax)())) Dim oldClauses = oldInnerMostCommonQuery.Clauses Dim newClauses = newInnerMostQuery.Clauses Dim firstClauseAffectedInQuery = oldClauses.First(AddressOf allAffectedClauses.Contains) Dim firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery) Dim finalClauses = newClauses.Take(firstClauseAffectedIndex). Concat(letClause). Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList() Dim finalQuery = newInnerMostQuery.WithClauses(SyntaxFactory.List(finalClauses)) Dim newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery) Return Task.FromResult(document.Document.WithSyntaxRoot(newRoot)) End Function Private Function IntroduceQueryLocalForSingleOccurrence( document As SemanticDocument, expression As ExpressionSyntax, newLocalName As NameSyntax, letClause As LetClauseSyntax, allOccurrences As Boolean, cancellationToken As CancellationToken) As Document Dim oldClause = expression.GetAncestor(Of QueryClauseSyntax)() Dim newClause = Rewrite(document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken) Dim oldQuery = DirectCast(oldClause.Parent, QueryExpressionSyntax) Dim newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause) Dim newRoot = document.Root.ReplaceNode(oldQuery, newQuery) Return document.Document.WithSyntaxRoot(newRoot) End Function Private Shared Function GetNewQuery( oldQuery As QueryExpressionSyntax, oldClause As QueryClauseSyntax, newClause As QueryClauseSyntax, letClause As LetClauseSyntax) As QueryExpressionSyntax Dim oldClauses = oldQuery.Clauses Dim oldClauseIndex = oldClauses.IndexOf(oldClause) Dim newClauses = oldClauses.Take(oldClauseIndex). Concat(letClause). Concat(newClause). Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList() Return oldQuery.WithClauses(SyntaxFactory.List(newClauses)) End Function End Class End Namespace
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_OptionHelpers.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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionOrUserDiagnosticTest { internal static (OptionKey2, object?) SingleOption<T>(Option2<T> option, T enabled) => (new OptionKey2(option), enabled); internal (OptionKey2, object?) SingleOption<T>(PerLanguageOption2<T> option, T value) => (new OptionKey2(option, this.GetLanguage()), value); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option), new CodeStyleOption2<T>(enabled, notification)); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option), codeStyle); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option, this.GetLanguage()), new CodeStyleOption2<T>(enabled, notification)); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option, this.GetLanguage()), codeStyle); internal static (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle, string language) => (new OptionKey2(option, language), codeStyle); internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; } }
// 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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionOrUserDiagnosticTest { internal static (OptionKey2, object?) SingleOption<T>(Option2<T> option, T enabled) => (new OptionKey2(option), enabled); internal (OptionKey2, object?) SingleOption<T>(PerLanguageOption2<T> option, T value) => (new OptionKey2(option, this.GetLanguage()), value); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option), new CodeStyleOption2<T>(enabled, notification)); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option), codeStyle); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option, this.GetLanguage()), new CodeStyleOption2<T>(enabled, notification)); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option, this.GetLanguage()), codeStyle); internal static (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle, string language) => (new OptionKey2(option, language), codeStyle); internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Core/Def/Implementation/KeybindingReset/KeybindingResetOptions.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.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.VisualStudio.LanguageServices.KeybindingReset { [ExportOptionProvider, Shared] internal sealed class KeybindingResetOptions : IOptionProvider { private const string LocalRegistryPath = @"Roslyn\Internal\KeybindingsStatus\"; public static readonly Option<ReSharperStatus> ReSharperStatus = new(nameof(KeybindingResetOptions), nameof(ReSharperStatus), defaultValue: KeybindingReset.ReSharperStatus.NotInstalledOrDisabled, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(ReSharperStatus))); public static readonly Option<bool> NeedsReset = new(nameof(KeybindingResetOptions), nameof(NeedsReset), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeedsReset))); public static readonly Option<bool> NeverShowAgain = new(nameof(KeybindingResetOptions), nameof(NeverShowAgain), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeverShowAgain))); public static readonly Option<bool> EnabledFeatureFlag = new(nameof(KeybindingResetOptions), nameof(EnabledFeatureFlag), defaultValue: false, storageLocations: new FeatureFlagStorageLocation("Roslyn.KeybindingResetEnabled")); ImmutableArray<IOption> IOptionProvider.Options { get; } = ImmutableArray.Create<IOption>( ReSharperStatus, NeedsReset, NeverShowAgain, EnabledFeatureFlag); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public KeybindingResetOptions() { } } }
// 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.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.VisualStudio.LanguageServices.KeybindingReset { [ExportOptionProvider, Shared] internal sealed class KeybindingResetOptions : IOptionProvider { private const string LocalRegistryPath = @"Roslyn\Internal\KeybindingsStatus\"; public static readonly Option<ReSharperStatus> ReSharperStatus = new(nameof(KeybindingResetOptions), nameof(ReSharperStatus), defaultValue: KeybindingReset.ReSharperStatus.NotInstalledOrDisabled, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(ReSharperStatus))); public static readonly Option<bool> NeedsReset = new(nameof(KeybindingResetOptions), nameof(NeedsReset), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeedsReset))); public static readonly Option<bool> NeverShowAgain = new(nameof(KeybindingResetOptions), nameof(NeverShowAgain), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeverShowAgain))); public static readonly Option<bool> EnabledFeatureFlag = new(nameof(KeybindingResetOptions), nameof(EnabledFeatureFlag), defaultValue: false, storageLocations: new FeatureFlagStorageLocation("Roslyn.KeybindingResetEnabled")); ImmutableArray<IOption> IOptionProvider.Options { get; } = ImmutableArray.Create<IOption>( ReSharperStatus, NeedsReset, NeverShowAgain, EnabledFeatureFlag); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public KeybindingResetOptions() { } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/MSBuildTest/Resources/SourceFiles/CSharp/CSharpConsole.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. extern alias ProjAlias; using System; namespace CSharpProject_ProjectReference { class Program { static ProjAlias::CSharpProject.CSharpClass field; static void Main() { field = new ProjAlias.CSharpProject.CSharpClass(); } } }
// 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. extern alias ProjAlias; using System; namespace CSharpProject_ProjectReference { class Program { static ProjAlias::CSharpProject.CSharpClass field; static void Main() { field = new ProjAlias.CSharpProject.CSharpClass(); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/Core.Wpf/Peek/IPeekableItemFactory.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.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Peek { public interface IPeekableItemFactory { Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync(ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken 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.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Peek { public interface IPeekableItemFactory { Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync(ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Core/Portable/StrongName/DesktopStrongNameProvider.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.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Security.Cryptography; using Microsoft.Cci; using Microsoft.CodeAnalysis.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides strong name and signs source assemblies. /// </summary> public class DesktopStrongNameProvider : StrongNameProvider { // This exception is only used to detect when the acquisition of IClrStrongName fails // and the likely reason is that we're running on CoreCLR on a non-Windows platform. // The place where the acquisition fails does not have access to localization, // so we can't throw some generic exception with a localized message. // So this is sort of a token for the eventual message to be generated. // The path from where this is thrown to where it is caught is all internal, // so there's no chance of an API consumer seeing it. internal sealed class ClrStrongNameMissingException : Exception { } private readonly ImmutableArray<string> _keyFileSearchPaths; internal override StrongNameFileSystem FileSystem { get; } public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths) : this(keyFileSearchPaths, StrongNameFileSystem.Instance) { } /// <summary> /// Creates an instance of <see cref="DesktopStrongNameProvider"/>. /// </summary> /// <param name="tempPath">Path to use for any temporary file generation.</param> /// <param name="keyFileSearchPaths">An ordered set of fully qualified paths which are searched when locating a cryptographic key file.</param> public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths = default, string? tempPath = null) : this(keyFileSearchPaths, tempPath == null ? StrongNameFileSystem.Instance : new StrongNameFileSystem(tempPath)) { } internal DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths, StrongNameFileSystem strongNameFileSystem) { if (!keyFileSearchPaths.IsDefault && keyFileSearchPaths.Any(path => !PathUtilities.IsAbsolute(path))) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(keyFileSearchPaths)); } FileSystem = strongNameFileSystem ?? StrongNameFileSystem.Instance; _keyFileSearchPaths = keyFileSearchPaths.NullToEmpty(); } internal override StrongNameKeys CreateKeys(string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) { var keyPair = default(ImmutableArray<byte>); var publicKey = default(ImmutableArray<byte>); string? container = null; if (!string.IsNullOrEmpty(keyFilePath)) { try { string? resolvedKeyFile = ResolveStrongNameKeyFile(keyFilePath, FileSystem, _keyFileSearchPaths); if (resolvedKeyFile == null) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, CodeAnalysisResources.FileNotFound)); } Debug.Assert(PathUtilities.IsAbsolute(resolvedKeyFile)); var fileContent = ImmutableArray.Create(FileSystem.ReadAllBytes(resolvedKeyFile)); return StrongNameKeys.CreateHelper(fileContent, keyFilePath, hasCounterSignature); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, ex.Message)); } } else if (!string.IsNullOrEmpty(keyContainerName)) { try { ReadKeysFromContainer(keyContainerName, out publicKey); container = keyContainerName; } catch (ClrStrongNameMissingException) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)))); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, ex.Message)); } } return new StrongNameKeys(keyPair, publicKey, privateKey: null, container, keyFilePath, hasCounterSignature); } /// <summary> /// Resolves assembly strong name key file path. /// </summary> /// <returns>Normalized key file path or null if not found.</returns> internal static string? ResolveStrongNameKeyFile(string path, StrongNameFileSystem fileSystem, ImmutableArray<string> keyFileSearchPaths) { // Dev11: key path is simply appended to the search paths, even if it starts with the current (parent) directory ("." or ".."). // This is different from PathUtilities.ResolveRelativePath. if (PathUtilities.IsAbsolute(path)) { if (fileSystem.FileExists(path)) { return FileUtilities.TryNormalizeAbsolutePath(path); } return path; } foreach (var searchPath in keyFileSearchPaths) { string? combinedPath = PathUtilities.CombineAbsoluteAndRelativePaths(searchPath, path); Debug.Assert(combinedPath == null || PathUtilities.IsAbsolute(combinedPath)); if (fileSystem.FileExists(combinedPath)) { return FileUtilities.TryNormalizeAbsolutePath(combinedPath!); } } return null; } internal virtual void ReadKeysFromContainer(string keyContainer, out ImmutableArray<byte> publicKey) { try { publicKey = GetPublicKey(keyContainer); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message); } } internal override void SignFile(StrongNameKeys keys, string filePath) { Debug.Assert(string.IsNullOrEmpty(keys.KeyFilePath) != string.IsNullOrEmpty(keys.KeyContainer)); if (!string.IsNullOrEmpty(keys.KeyFilePath)) { Sign(filePath, keys.KeyPair); } else { Sign(filePath, keys.KeyContainer!); } } internal override void SignBuilder(ExtendedPEBuilder peBuilder, BlobBuilder peBlob, RSAParameters privateKey) { peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKey)); } // EDMAURER in the event that the key is supplied as a file, // this type could get an instance member that caches the file // contents to avoid reading the file twice - once to get the // public key to establish the assembly name and another to do // the actual signing internal virtual IClrStrongName GetStrongNameInterface() { try { return ClrStrongName.GetInstance(); } catch (MarshalDirectiveException) when (PathUtilities.IsUnixLikePlatform) { // CoreCLR, when not on Windows, doesn't support IClrStrongName (or COM in general). // This is really hard to detect/predict without false positives/negatives. // It turns out that CoreCLR throws a MarshalDirectiveException when attempting // to get the interface (Message "Cannot marshal 'return value': Unknown error."), // so just catch that and state that it's not supported. // We're deep in a try block that reports the exception's Message as part of a diagnostic. // This exception will skip through the IOException wrapping by `Sign` (in this class), // then caught by Compilation.SerializeToPeStream or DesktopStringNameProvider.CreateKeys throw new ClrStrongNameMissingException(); } } internal ImmutableArray<byte> GetPublicKey(string keyContainer) { IClrStrongName strongName = GetStrongNameInterface(); IntPtr keyBlob; int keyBlobByteCount; strongName.StrongNameGetPublicKey(keyContainer, pbKeyBlob: default, 0, out keyBlob, out keyBlobByteCount); byte[] pubKey = new byte[keyBlobByteCount]; Marshal.Copy(keyBlob, pubKey, 0, keyBlobByteCount); strongName.StrongNameFreeBuffer(keyBlob); return pubKey.AsImmutableOrNull(); } /// <exception cref="IOException"/> private void Sign(string filePath, string keyName) { try { IClrStrongName strongName = GetStrongNameInterface(); strongName.StrongNameSignatureGeneration(filePath, keyName, IntPtr.Zero, 0, null, pcbSignatureBlob: out _); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } private unsafe void Sign(string filePath, ImmutableArray<byte> keyPair) { try { IClrStrongName strongName = GetStrongNameInterface(); fixed (byte* pinned = keyPair.ToArray()) { strongName.StrongNameSignatureGeneration(filePath, null, (IntPtr)pinned, keyPair.Length, null, pcbSignatureBlob: out _); } } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } public override int GetHashCode() { return Hash.CombineValues(_keyFileSearchPaths, StringComparer.Ordinal); } public override bool Equals(object? obj) { if (obj is null || GetType() != obj.GetType()) { return false; } var other = (DesktopStrongNameProvider)obj; if (FileSystem != other.FileSystem) { return false; } if (!_keyFileSearchPaths.SequenceEqual(other._keyFileSearchPaths, StringComparer.Ordinal)) { return false; } return 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; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Security.Cryptography; using Microsoft.Cci; using Microsoft.CodeAnalysis.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides strong name and signs source assemblies. /// </summary> public class DesktopStrongNameProvider : StrongNameProvider { // This exception is only used to detect when the acquisition of IClrStrongName fails // and the likely reason is that we're running on CoreCLR on a non-Windows platform. // The place where the acquisition fails does not have access to localization, // so we can't throw some generic exception with a localized message. // So this is sort of a token for the eventual message to be generated. // The path from where this is thrown to where it is caught is all internal, // so there's no chance of an API consumer seeing it. internal sealed class ClrStrongNameMissingException : Exception { } private readonly ImmutableArray<string> _keyFileSearchPaths; internal override StrongNameFileSystem FileSystem { get; } public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths) : this(keyFileSearchPaths, StrongNameFileSystem.Instance) { } /// <summary> /// Creates an instance of <see cref="DesktopStrongNameProvider"/>. /// </summary> /// <param name="tempPath">Path to use for any temporary file generation.</param> /// <param name="keyFileSearchPaths">An ordered set of fully qualified paths which are searched when locating a cryptographic key file.</param> public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths = default, string? tempPath = null) : this(keyFileSearchPaths, tempPath == null ? StrongNameFileSystem.Instance : new StrongNameFileSystem(tempPath)) { } internal DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths, StrongNameFileSystem strongNameFileSystem) { if (!keyFileSearchPaths.IsDefault && keyFileSearchPaths.Any(path => !PathUtilities.IsAbsolute(path))) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(keyFileSearchPaths)); } FileSystem = strongNameFileSystem ?? StrongNameFileSystem.Instance; _keyFileSearchPaths = keyFileSearchPaths.NullToEmpty(); } internal override StrongNameKeys CreateKeys(string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) { var keyPair = default(ImmutableArray<byte>); var publicKey = default(ImmutableArray<byte>); string? container = null; if (!string.IsNullOrEmpty(keyFilePath)) { try { string? resolvedKeyFile = ResolveStrongNameKeyFile(keyFilePath, FileSystem, _keyFileSearchPaths); if (resolvedKeyFile == null) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, CodeAnalysisResources.FileNotFound)); } Debug.Assert(PathUtilities.IsAbsolute(resolvedKeyFile)); var fileContent = ImmutableArray.Create(FileSystem.ReadAllBytes(resolvedKeyFile)); return StrongNameKeys.CreateHelper(fileContent, keyFilePath, hasCounterSignature); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, ex.Message)); } } else if (!string.IsNullOrEmpty(keyContainerName)) { try { ReadKeysFromContainer(keyContainerName, out publicKey); container = keyContainerName; } catch (ClrStrongNameMissingException) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)))); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, ex.Message)); } } return new StrongNameKeys(keyPair, publicKey, privateKey: null, container, keyFilePath, hasCounterSignature); } /// <summary> /// Resolves assembly strong name key file path. /// </summary> /// <returns>Normalized key file path or null if not found.</returns> internal static string? ResolveStrongNameKeyFile(string path, StrongNameFileSystem fileSystem, ImmutableArray<string> keyFileSearchPaths) { // Dev11: key path is simply appended to the search paths, even if it starts with the current (parent) directory ("." or ".."). // This is different from PathUtilities.ResolveRelativePath. if (PathUtilities.IsAbsolute(path)) { if (fileSystem.FileExists(path)) { return FileUtilities.TryNormalizeAbsolutePath(path); } return path; } foreach (var searchPath in keyFileSearchPaths) { string? combinedPath = PathUtilities.CombineAbsoluteAndRelativePaths(searchPath, path); Debug.Assert(combinedPath == null || PathUtilities.IsAbsolute(combinedPath)); if (fileSystem.FileExists(combinedPath)) { return FileUtilities.TryNormalizeAbsolutePath(combinedPath!); } } return null; } internal virtual void ReadKeysFromContainer(string keyContainer, out ImmutableArray<byte> publicKey) { try { publicKey = GetPublicKey(keyContainer); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message); } } internal override void SignFile(StrongNameKeys keys, string filePath) { Debug.Assert(string.IsNullOrEmpty(keys.KeyFilePath) != string.IsNullOrEmpty(keys.KeyContainer)); if (!string.IsNullOrEmpty(keys.KeyFilePath)) { Sign(filePath, keys.KeyPair); } else { Sign(filePath, keys.KeyContainer!); } } internal override void SignBuilder(ExtendedPEBuilder peBuilder, BlobBuilder peBlob, RSAParameters privateKey) { peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKey)); } // EDMAURER in the event that the key is supplied as a file, // this type could get an instance member that caches the file // contents to avoid reading the file twice - once to get the // public key to establish the assembly name and another to do // the actual signing internal virtual IClrStrongName GetStrongNameInterface() { try { return ClrStrongName.GetInstance(); } catch (MarshalDirectiveException) when (PathUtilities.IsUnixLikePlatform) { // CoreCLR, when not on Windows, doesn't support IClrStrongName (or COM in general). // This is really hard to detect/predict without false positives/negatives. // It turns out that CoreCLR throws a MarshalDirectiveException when attempting // to get the interface (Message "Cannot marshal 'return value': Unknown error."), // so just catch that and state that it's not supported. // We're deep in a try block that reports the exception's Message as part of a diagnostic. // This exception will skip through the IOException wrapping by `Sign` (in this class), // then caught by Compilation.SerializeToPeStream or DesktopStringNameProvider.CreateKeys throw new ClrStrongNameMissingException(); } } internal ImmutableArray<byte> GetPublicKey(string keyContainer) { IClrStrongName strongName = GetStrongNameInterface(); IntPtr keyBlob; int keyBlobByteCount; strongName.StrongNameGetPublicKey(keyContainer, pbKeyBlob: default, 0, out keyBlob, out keyBlobByteCount); byte[] pubKey = new byte[keyBlobByteCount]; Marshal.Copy(keyBlob, pubKey, 0, keyBlobByteCount); strongName.StrongNameFreeBuffer(keyBlob); return pubKey.AsImmutableOrNull(); } /// <exception cref="IOException"/> private void Sign(string filePath, string keyName) { try { IClrStrongName strongName = GetStrongNameInterface(); strongName.StrongNameSignatureGeneration(filePath, keyName, IntPtr.Zero, 0, null, pcbSignatureBlob: out _); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } private unsafe void Sign(string filePath, ImmutableArray<byte> keyPair) { try { IClrStrongName strongName = GetStrongNameInterface(); fixed (byte* pinned = keyPair.ToArray()) { strongName.StrongNameSignatureGeneration(filePath, null, (IntPtr)pinned, keyPair.Length, null, pcbSignatureBlob: out _); } } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } public override int GetHashCode() { return Hash.CombineValues(_keyFileSearchPaths, StringComparer.Ordinal); } public override bool Equals(object? obj) { if (obj is null || GetType() != obj.GetType()) { return false; } var other = (DesktopStrongNameProvider)obj; if (FileSystem != other.FileSystem) { return false; } if (!_keyFileSearchPaths.SequenceEqual(other._keyFileSearchPaths, StringComparer.Ordinal)) { return false; } return true; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Remote/ServiceHub/PublicAPI.Shipped.txt
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Core/Def/Implementation/UnusedReferences/Dialog/UnusedReferencesTableProvider.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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.UnusedReferences; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog { [Export(typeof(UnusedReferencesTableProvider))] internal partial class UnusedReferencesTableProvider { private readonly ITableManager _tableManager; private readonly IWpfTableControlProvider _tableControlProvider; private readonly UnusedReferencesDataSource _dataSource; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnusedReferencesTableProvider( ITableManagerProvider tableMangerProvider, IWpfTableControlProvider tableControlProvider) { _tableManager = tableMangerProvider.GetTableManager(UnusedReferencesDataSource.Name); _tableControlProvider = tableControlProvider; _dataSource = new UnusedReferencesDataSource(); _tableManager.AddSource(_dataSource, UnusedReferencesColumnDefinitions.ColumnNames); } public IWpfTableControl4 CreateTableControl() { var tableControl = (IWpfTableControl4)_tableControlProvider.CreateControl( _tableManager, autoSubscribe: true, BuildColumnStates(), UnusedReferencesColumnDefinitions.ColumnNames.ToArray()); tableControl.ShowGroupingLine = true; tableControl.DoColumnsAutoAdjust = true; tableControl.DoSortingAndGroupingWhileUnstable = true; return tableControl; static ImmutableArray<ColumnState> BuildColumnStates() { return ImmutableArray.Create( new ColumnState2(UnusedReferencesColumnDefinitions.SolutionName, isVisible: false, width: 200, sortPriority: 0, descendingSort: false, groupingPriority: 1), new ColumnState2(UnusedReferencesColumnDefinitions.ProjectName, isVisible: false, width: 200, sortPriority: 1, descendingSort: false, groupingPriority: 2), new ColumnState2(UnusedReferencesColumnDefinitions.ReferenceType, isVisible: false, width: 200, sortPriority: 2, descendingSort: false, groupingPriority: 3), new ColumnState(UnusedReferencesColumnDefinitions.ReferenceName, isVisible: true, width: 300, sortPriority: 3, descendingSort: false), new ColumnState(UnusedReferencesColumnDefinitions.UpdateAction, isVisible: true, width: 100, sortPriority: 4, descendingSort: false)); } } public void AddTableData(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates) { _dataSource.AddTableData(solution, projectFilePath, referenceUpdates); } public void ClearTableData() { _dataSource.RemoveAllTableData(); } } }
// 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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.UnusedReferences; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog { [Export(typeof(UnusedReferencesTableProvider))] internal partial class UnusedReferencesTableProvider { private readonly ITableManager _tableManager; private readonly IWpfTableControlProvider _tableControlProvider; private readonly UnusedReferencesDataSource _dataSource; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnusedReferencesTableProvider( ITableManagerProvider tableMangerProvider, IWpfTableControlProvider tableControlProvider) { _tableManager = tableMangerProvider.GetTableManager(UnusedReferencesDataSource.Name); _tableControlProvider = tableControlProvider; _dataSource = new UnusedReferencesDataSource(); _tableManager.AddSource(_dataSource, UnusedReferencesColumnDefinitions.ColumnNames); } public IWpfTableControl4 CreateTableControl() { var tableControl = (IWpfTableControl4)_tableControlProvider.CreateControl( _tableManager, autoSubscribe: true, BuildColumnStates(), UnusedReferencesColumnDefinitions.ColumnNames.ToArray()); tableControl.ShowGroupingLine = true; tableControl.DoColumnsAutoAdjust = true; tableControl.DoSortingAndGroupingWhileUnstable = true; return tableControl; static ImmutableArray<ColumnState> BuildColumnStates() { return ImmutableArray.Create( new ColumnState2(UnusedReferencesColumnDefinitions.SolutionName, isVisible: false, width: 200, sortPriority: 0, descendingSort: false, groupingPriority: 1), new ColumnState2(UnusedReferencesColumnDefinitions.ProjectName, isVisible: false, width: 200, sortPriority: 1, descendingSort: false, groupingPriority: 2), new ColumnState2(UnusedReferencesColumnDefinitions.ReferenceType, isVisible: false, width: 200, sortPriority: 2, descendingSort: false, groupingPriority: 3), new ColumnState(UnusedReferencesColumnDefinitions.ReferenceName, isVisible: true, width: 300, sortPriority: 3, descendingSort: false), new ColumnState(UnusedReferencesColumnDefinitions.UpdateAction, isVisible: true, width: 100, sortPriority: 4, descendingSort: false)); } } public void AddTableData(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates) { _dataSource.AddTableData(solution, projectFilePath, referenceUpdates); } public void ClearTableData() { _dataSource.RemoveAllTableData(); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryParentheses/VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider.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 System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]> Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper( current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing) 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 System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]> Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper( current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing) End Function End Class End Namespace
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/Workspace/Host/IWorkspaceService.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.Host { /// <summary> /// Empty interface just to mark workspace services. /// </summary> public interface IWorkspaceService { } }
// 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.Host { /// <summary> /// Empty interface just to mark workspace services. /// </summary> public interface IWorkspaceService { } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/CSharp/Impl/Interactive/CSharpVsResetInteractiveCommand.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.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Roslyn.VisualStudio.Services.Interactive; using System; using System.ComponentModel.Composition; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [ExportInteractive(typeof(IResetInteractiveCommand), ContentTypeNames.CSharpContentType)] internal sealed class CSharpVsResetInteractiveCommand : AbstractResetInteractiveCommand { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsResetInteractiveCommand( VisualStudioWorkspace workspace, CSharpVsInteractiveWindowProvider interactiveWindowProvider, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) : base(workspace, interactiveWindowProvider, serviceProvider) { } protected override string LanguageName { get { return "C#"; } } protected override string CreateReference(string referenceName) => string.Format("#r \"{0}\"", referenceName); protected override string CreateImport(string namespaceName) => string.Format("using {0};", namespaceName); } }
// 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.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Roslyn.VisualStudio.Services.Interactive; using System; using System.ComponentModel.Composition; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [ExportInteractive(typeof(IResetInteractiveCommand), ContentTypeNames.CSharpContentType)] internal sealed class CSharpVsResetInteractiveCommand : AbstractResetInteractiveCommand { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsResetInteractiveCommand( VisualStudioWorkspace workspace, CSharpVsInteractiveWindowProvider interactiveWindowProvider, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) : base(workspace, interactiveWindowProvider, serviceProvider) { } protected override string LanguageName { get { return "C#"; } } protected override string CreateReference(string referenceName) => string.Format("#r \"{0}\"", referenceName); protected override string CreateImport(string namespaceName) => string.Format("using {0};", namespaceName); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Analyzers/Core/CodeFixes/UseConditionalExpression/UseConditionalExpressionHelpers.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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionCodeFixHelpers { public static readonly SyntaxAnnotation SpecializedFormattingAnnotation = new(); public static SyntaxRemoveOptions GetRemoveOptions( ISyntaxFactsService syntaxFacts, SyntaxNode syntax) { var removeOptions = SyntaxGenerator.DefaultRemoveOptions; if (HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } if (HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepTrailingTrivia; } return removeOptions; } } }
// 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionCodeFixHelpers { public static readonly SyntaxAnnotation SpecializedFormattingAnnotation = new(); public static SyntaxRemoveOptions GetRemoveOptions( ISyntaxFactsService syntaxFacts, SyntaxNode syntax) { var removeOptions = SyntaxGenerator.DefaultRemoveOptions; if (HasRegularCommentTrivia(syntaxFacts, syntax.GetLeadingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } if (HasRegularCommentTrivia(syntaxFacts, syntax.GetTrailingTrivia())) { removeOptions |= SyntaxRemoveOptions.KeepTrailingTrivia; } return removeOptions; } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.tr.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="tr" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Küme ayracı ekle</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' deyimine küme ayracı ekleyin.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Oluşturucu başlatıcı iki noktadan sonra boş satıra izin verilmiyor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Ardışık ayraçlar arasında boş çizgi olmamalıdır</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Switch deyimini ifadeye dönüştür</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Değişken bildirimini ayrıştır</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Temsilci çağrısı basitleştirilebilir.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Atma işlemi kaldırılabilir</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Katıştırılmış deyimler kendi satırına yerleştirilmelidir</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Dizin oluşturma basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Satır içi değişken bildirimi</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Yanlış yerleştirilmiş using yönergesi</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Yanlış yerleştirilmiş using yönergelerini taşı</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly alanları yazılabilir yap</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Yerel işlev statik yapılabilir</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Yerel işlevi 'static' yap</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">İfadeyi tersine çevir (semantiği değiştirir)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">İşleci kaldır (semantiği korur)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Gizleme işleçlerini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Gereksiz gizleme işlecini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Gereksiz atmayı kaldır</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Default' ifadesini basitleştir</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct, oluşturucu dışında 'this' öğesine yönelik atama içeriyor. Salt okunur alanları yazılabilir yapın.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Gizleme işleci hiçbir etkiye sahip değil ve yanlış yorumlanabilir</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Ulaşılamayan kod algılandı</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Erişimciler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Dizin oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Yerel işlevler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Metotlar için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">İşleçler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Özellikler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Açık tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Var' yerine açık tür kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Erişimciler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Dizin oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Yerel işlevler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Metotlar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">İşleçler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Özellikler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Örtük tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Dizin işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' denetimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Yerel işlev kullan</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' kullanın</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Desen eşleştirme kullan</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Aralık işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Basit 'using' deyimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'Switch' ifadesini kullan</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin içine yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin dışına yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Değişken bildirimi ayrıştırılabilir</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Değişken bildirimi satır içine alınabilir</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Uyarı: using yönergelerini taşımak, kodun anlamını değiştirebilir.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'If' deyimi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' metodu 'nameof' metoduna dönüştürülebilir</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">açık tür yerine 'var' kullan</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using yönergesi gerekli değildir.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' deyimi basitleştirilebilir</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="tr" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Küme ayracı ekle</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' deyimine küme ayracı ekleyin.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Oluşturucu başlatıcı iki noktadan sonra boş satıra izin verilmiyor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Ardışık ayraçlar arasında boş çizgi olmamalıdır</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Switch deyimini ifadeye dönüştür</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Değişken bildirimini ayrıştır</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Temsilci çağrısı basitleştirilebilir.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Atma işlemi kaldırılabilir</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Katıştırılmış deyimler kendi satırına yerleştirilmelidir</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Dizin oluşturma basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Satır içi değişken bildirimi</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Yanlış yerleştirilmiş using yönergesi</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Yanlış yerleştirilmiş using yönergelerini taşı</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly alanları yazılabilir yap</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Yerel işlev statik yapılabilir</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Yerel işlevi 'static' yap</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">İfadeyi tersine çevir (semantiği değiştirir)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">İşleci kaldır (semantiği korur)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Gizleme işleçlerini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Gereksiz gizleme işlecini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Gereksiz atmayı kaldır</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Default' ifadesini basitleştir</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct, oluşturucu dışında 'this' öğesine yönelik atama içeriyor. Salt okunur alanları yazılabilir yapın.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Gizleme işleci hiçbir etkiye sahip değil ve yanlış yorumlanabilir</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Ulaşılamayan kod algılandı</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Erişimciler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Dizin oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Yerel işlevler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Metotlar için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">İşleçler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Özellikler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Açık tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Var' yerine açık tür kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Erişimciler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Dizin oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Yerel işlevler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Metotlar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">İşleçler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Özellikler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Örtük tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Dizin işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' denetimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Yerel işlev kullan</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' kullanın</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Desen eşleştirme kullan</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Aralık işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Basit 'using' deyimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'Switch' ifadesini kullan</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin içine yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin dışına yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Değişken bildirimi ayrıştırılabilir</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Değişken bildirimi satır içine alınabilir</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Uyarı: using yönergelerini taşımak, kodun anlamını değiştirebilir.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'If' deyimi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' metodu 'nameof' metoduna dönüştürülebilir</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">açık tür yerine 'var' kullan</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using yönergesi gerekli değildir.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' deyimi basitleştirilebilir</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ValuesSources/ValueSource.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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// A class that abstracts the accessing of a value that is guaranteed to be available at some point. /// </summary> internal abstract class ValueSource<T> { public abstract bool TryGetValue([MaybeNullWhen(false)] out T value); public abstract T GetValue(CancellationToken cancellationToken = default); public abstract Task<T> GetValueAsync(CancellationToken cancellationToken = default); } internal static class ValueSourceExtensions { internal static T? GetValueOrNull<T>(this Optional<T> optional) where T : class => optional.Value; internal static T GetValueOrDefault<T>(this Optional<T> optional) where T : struct => optional.Value; internal static T? GetValueOrNull<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : class => optional.GetValue(cancellationToken).GetValueOrNull(); internal static T GetValueOrDefault<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : struct => optional.GetValue(cancellationToken).GetValueOrDefault(); } }
// 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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// A class that abstracts the accessing of a value that is guaranteed to be available at some point. /// </summary> internal abstract class ValueSource<T> { public abstract bool TryGetValue([MaybeNullWhen(false)] out T value); public abstract T GetValue(CancellationToken cancellationToken = default); public abstract Task<T> GetValueAsync(CancellationToken cancellationToken = default); } internal static class ValueSourceExtensions { internal static T? GetValueOrNull<T>(this Optional<T> optional) where T : class => optional.Value; internal static T GetValueOrDefault<T>(this Optional<T> optional) where T : struct => optional.Value; internal static T? GetValueOrNull<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : class => optional.GetValue(cancellationToken).GetValueOrNull(); internal static T GetValueOrDefault<T>(this ValueSource<Optional<T>> optional, CancellationToken cancellationToken = default) where T : struct => optional.GetValue(cancellationToken).GetValueOrDefault(); } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ProtectedKeywordRecommender.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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ProtectedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ProtectedKeywordRecommender() : base(SyntaxKind.ProtectedKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidContextForAccessor(context) || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken); } private static bool IsValidContextForAccessor(CSharpSyntaxContext context) { if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { // protected things can't be in namespaces. var typeDecl = context.ContainingTypeDeclaration; if (typeDecl == null) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context) { // We can show up after 'internal' and 'private'. var precedingModifiers = context.PrecedingModifiers; return !precedingModifiers.Contains(SyntaxKind.PublicKeyword) && !precedingModifiers.Contains(SyntaxKind.ProtectedKeyword); } } }
// 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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ProtectedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ProtectedKeywordRecommender() : base(SyntaxKind.ProtectedKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidContextForAccessor(context) || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken); } private static bool IsValidContextForAccessor(CSharpSyntaxContext context) { if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { // protected things can't be in namespaces. var typeDecl = context.ContainingTypeDeclaration; if (typeDecl == null) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context) { // We can show up after 'internal' and 'private'. var precedingModifiers = context.PrecedingModifiers; return !precedingModifiers.Contains(SyntaxKind.PublicKeyword) && !precedingModifiers.Contains(SyntaxKind.ProtectedKeyword); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Features/Core/Portable/ConvertToInterpolatedString/ConvertRegularStringToInterpolatedStringRefactoringProvider.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ConvertToInterpolatedString { /// <summary> /// Code refactoring that converts a regular string containing braces to an interpolated string /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString), Shared] internal sealed class ConvertRegularStringToInterpolatedStringRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertRegularStringToInterpolatedStringRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) return; var token = root.FindToken(context.Span.Start); if (!context.Span.IntersectsWith(token.Span)) return; var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); if (token.RawKind != syntaxKinds.StringLiteralToken) return; var literalExpression = token.GetRequiredParent(); // Check the string literal for errors. This will ensure that we do not try to fixup an incomplete string. if (literalExpression.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return; if (!token.Text.Contains("{") && !token.Text.Contains("}")) return; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // If there is a const keyword, do not offer the refactoring (an interpolated string is not const) var declarator = literalExpression.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsVariableDeclarator); if (declarator != null) { var generator = SyntaxGenerator.GetGenerator(document); if (generator.GetModifiers(declarator).IsConst) return; } // Attributes also only allow constant values. var attribute = literalExpression.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsAttribute); if (attribute != null) return; context.RegisterRefactoring( new MyCodeAction(_ => UpdateDocumentAsync(document, root, token)), literalExpression.Span); } private static string GetTextWithoutQuotes(string text, bool isVerbatim) { // Trim off an extra character (@ symbol) for verbatim strings var startIndex = isVerbatim ? 2 : 1; return text[startIndex..^1]; } private static SyntaxNode CreateInterpolatedString(Document document, SyntaxNode literalExpression, bool isVerbatim) { var generator = SyntaxGenerator.GetGenerator(document); var text = literalExpression.GetFirstToken().Text; var valueText = literalExpression.GetFirstToken().ValueText; var newNode = generator.InterpolatedStringText( generator.InterpolatedStringTextToken( GetTextWithoutQuotes(text.Replace("{", "{{").Replace("}", "}}"), isVerbatim), valueText)); return generator.InterpolatedStringExpression( generator.CreateInterpolatedStringStartToken(isVerbatim), new[] { newNode }, generator.CreateInterpolatedStringEndToken()).WithTriviaFrom(literalExpression); } private static Task<Document> UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxToken token) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var literalExpression = token.GetRequiredParent(); return Task.FromResult(document.WithSyntaxRoot( root.ReplaceNode( literalExpression, CreateInterpolatedString(document, literalExpression, syntaxFacts.IsVerbatimStringLiteral(token))))); } private class MyCodeAction : CodeAction.DocumentChangeAction { internal override CodeActionPriority Priority => CodeActionPriority.Low; public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Convert_to_interpolated_string, createChangedDocument, nameof(FeaturesResources.Convert_to_interpolated_string)) { } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ConvertToInterpolatedString { /// <summary> /// Code refactoring that converts a regular string containing braces to an interpolated string /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString), Shared] internal sealed class ConvertRegularStringToInterpolatedStringRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertRegularStringToInterpolatedStringRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) return; var token = root.FindToken(context.Span.Start); if (!context.Span.IntersectsWith(token.Span)) return; var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); if (token.RawKind != syntaxKinds.StringLiteralToken) return; var literalExpression = token.GetRequiredParent(); // Check the string literal for errors. This will ensure that we do not try to fixup an incomplete string. if (literalExpression.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return; if (!token.Text.Contains("{") && !token.Text.Contains("}")) return; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // If there is a const keyword, do not offer the refactoring (an interpolated string is not const) var declarator = literalExpression.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsVariableDeclarator); if (declarator != null) { var generator = SyntaxGenerator.GetGenerator(document); if (generator.GetModifiers(declarator).IsConst) return; } // Attributes also only allow constant values. var attribute = literalExpression.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsAttribute); if (attribute != null) return; context.RegisterRefactoring( new MyCodeAction(_ => UpdateDocumentAsync(document, root, token)), literalExpression.Span); } private static string GetTextWithoutQuotes(string text, bool isVerbatim) { // Trim off an extra character (@ symbol) for verbatim strings var startIndex = isVerbatim ? 2 : 1; return text[startIndex..^1]; } private static SyntaxNode CreateInterpolatedString(Document document, SyntaxNode literalExpression, bool isVerbatim) { var generator = SyntaxGenerator.GetGenerator(document); var text = literalExpression.GetFirstToken().Text; var valueText = literalExpression.GetFirstToken().ValueText; var newNode = generator.InterpolatedStringText( generator.InterpolatedStringTextToken( GetTextWithoutQuotes(text.Replace("{", "{{").Replace("}", "}}"), isVerbatim), valueText)); return generator.InterpolatedStringExpression( generator.CreateInterpolatedStringStartToken(isVerbatim), new[] { newNode }, generator.CreateInterpolatedStringEndToken()).WithTriviaFrom(literalExpression); } private static Task<Document> UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxToken token) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var literalExpression = token.GetRequiredParent(); return Task.FromResult(document.WithSyntaxRoot( root.ReplaceNode( literalExpression, CreateInterpolatedString(document, literalExpression, syntaxFacts.IsVerbatimStringLiteral(token))))); } private class MyCodeAction : CodeAction.DocumentChangeAction { internal override CodeActionPriority Priority => CodeActionPriority.Low; public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Convert_to_interpolated_string, createChangedDocument, nameof(FeaturesResources.Convert_to_interpolated_string)) { } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/VisualBasic/xlf/VBEditorResources.es.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="es" original="../VBEditorResources.resx"> <body> <trans-unit id="Add_Missing_Imports_on_Paste"> <source>Add Missing Imports on Paste</source> <target state="translated">Agregar las importaciones que faltan al pegar</target> <note>"imports" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_imports"> <source>Adding missing imports...</source> <target state="translated">Agregando las importaciones que faltan...</target> <note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Case_Correction"> <source>Case Correction</source> <target state="translated">Corrección de mayúsculas/minúsculas</target> <note /> </trans-unit> <trans-unit id="Correcting_word_casing"> <source>Correcting word casing...</source> <target state="translated">Corrigiendo uso de mayúsculas/minúsculas...</target> <note /> </trans-unit> <trans-unit id="This_call_is_required_by_the_designer"> <source>This call is required by the designer.</source> <target state="translated">Esta llamada es exigida por el diseñador.</target> <note /> </trans-unit> <trans-unit id="Add_any_initialization_after_the_InitializeComponent_call"> <source>Add any initialization after the InitializeComponent() call.</source> <target state="translated">Agregue cualquier inicialización después de la llamada a InitializeComponent().</target> <note /> </trans-unit> <trans-unit id="End_Construct"> <source>End Construct</source> <target state="translated">Terminar construcción</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Sangría inteligente</target> <note /> </trans-unit> <trans-unit id="Formatting_Document"> <source>Formatting Document...</source> <target state="translated">Dando formato al documento...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Insertar nueva línea</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Pegado de formato</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Dando formato al texto pegado...</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Pegar</target> <note /> </trans-unit> <trans-unit id="Format_on_Save"> <source>Format on Save</source> <target state="translated">Aplicar formato al guardar</target> <note /> </trans-unit> <trans-unit id="Committing_line"> <source>Committing line</source> <target state="translated">Confirmando línea</target> <note /> </trans-unit> <trans-unit id="Visual_Basic_Pretty_List"> <source>Visual Basic Pretty List</source> <target state="translated">Lista descriptiva de Visual Basic</target> <note /> </trans-unit> <trans-unit id="not_supported"> <source>not supported</source> <target state="translated">no compatible</target> <note /> </trans-unit> <trans-unit id="Generate_Member"> <source>Generate Member</source> <target state="translated">Generar miembro</target> <note /> </trans-unit> <trans-unit id="Line_commit"> <source>Line commit</source> <target state="translated">Confirmación de línea</target> <note /> </trans-unit> <trans-unit id="Implement_Abstract_Class_Or_Interface"> <source>Implement Abstract Class Or Interface</source> <target state="translated">Implementar interfaz o clase abstracta</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="es" original="../VBEditorResources.resx"> <body> <trans-unit id="Add_Missing_Imports_on_Paste"> <source>Add Missing Imports on Paste</source> <target state="translated">Agregar las importaciones que faltan al pegar</target> <note>"imports" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_imports"> <source>Adding missing imports...</source> <target state="translated">Agregando las importaciones que faltan...</target> <note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Case_Correction"> <source>Case Correction</source> <target state="translated">Corrección de mayúsculas/minúsculas</target> <note /> </trans-unit> <trans-unit id="Correcting_word_casing"> <source>Correcting word casing...</source> <target state="translated">Corrigiendo uso de mayúsculas/minúsculas...</target> <note /> </trans-unit> <trans-unit id="This_call_is_required_by_the_designer"> <source>This call is required by the designer.</source> <target state="translated">Esta llamada es exigida por el diseñador.</target> <note /> </trans-unit> <trans-unit id="Add_any_initialization_after_the_InitializeComponent_call"> <source>Add any initialization after the InitializeComponent() call.</source> <target state="translated">Agregue cualquier inicialización después de la llamada a InitializeComponent().</target> <note /> </trans-unit> <trans-unit id="End_Construct"> <source>End Construct</source> <target state="translated">Terminar construcción</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Sangría inteligente</target> <note /> </trans-unit> <trans-unit id="Formatting_Document"> <source>Formatting Document...</source> <target state="translated">Dando formato al documento...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Insertar nueva línea</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Pegado de formato</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Dando formato al texto pegado...</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Pegar</target> <note /> </trans-unit> <trans-unit id="Format_on_Save"> <source>Format on Save</source> <target state="translated">Aplicar formato al guardar</target> <note /> </trans-unit> <trans-unit id="Committing_line"> <source>Committing line</source> <target state="translated">Confirmando línea</target> <note /> </trans-unit> <trans-unit id="Visual_Basic_Pretty_List"> <source>Visual Basic Pretty List</source> <target state="translated">Lista descriptiva de Visual Basic</target> <note /> </trans-unit> <trans-unit id="not_supported"> <source>not supported</source> <target state="translated">no compatible</target> <note /> </trans-unit> <trans-unit id="Generate_Member"> <source>Generate Member</source> <target state="translated">Generar miembro</target> <note /> </trans-unit> <trans-unit id="Line_commit"> <source>Line commit</source> <target state="translated">Confirmación de línea</target> <note /> </trans-unit> <trans-unit id="Implement_Abstract_Class_Or_Interface"> <source>Implement Abstract Class Or Interface</source> <target state="translated">Implementar interfaz o clase abstracta</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Core/Def/ValueTracking/TreeItemViewModel.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.Collections.ObjectModel; using System.Windows.Documents; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class TreeItemViewModel : TreeViewItemBase { private readonly SourceText _sourceText; private readonly Glyph _glyph; private readonly IGlyphService _glyphService; protected ValueTrackingTreeViewModel TreeViewModel { get; } protected TextSpan TextSpan { get; } protected LineSpan LineSpan { get; } protected IThreadingContext ThreadingContext { get; } protected DocumentId DocumentId { get; } protected Workspace Workspace { get; } public int LineNumber => LineSpan.Start + 1; // LineSpan is 0 indexed, editors are not public string FileName { get; } public ImageSource GlyphImage => _glyph.GetImageSource(_glyphService); public bool ShowGlyph => !IsLoading; public ImmutableArray<ClassifiedSpan> ClassifiedSpans { get; } public ImmutableArray<Inline> Inlines => CalculateInlines(); public TreeItemViewModel( TextSpan textSpan, SourceText sourceText, DocumentId documentId, string fileName, Glyph glyph, ImmutableArray<ClassifiedSpan> classifiedSpans, ValueTrackingTreeViewModel treeViewModel, IGlyphService glyphService, IThreadingContext threadingContext, Workspace workspace, ImmutableArray<TreeItemViewModel> children = default) : base() { FileName = fileName; TextSpan = textSpan; _sourceText = sourceText; ClassifiedSpans = classifiedSpans; TreeViewModel = treeViewModel; ThreadingContext = threadingContext; _glyph = glyph; _glyphService = glyphService; Workspace = workspace; DocumentId = documentId; if (!children.IsDefaultOrEmpty) { foreach (var child in children) { ChildItems.Add(child); } } sourceText.GetLineAndOffset(textSpan.Start, out var lineStart, out var _); sourceText.GetLineAndOffset(textSpan.End, out var lineEnd, out var _); LineSpan = LineSpan.FromBounds(lineStart, lineEnd); PropertyChanged += (s, e) => { if (e.PropertyName == nameof(IsLoading)) { NotifyPropertyChanged(nameof(ShowGlyph)); } }; TreeViewModel.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(TreeViewModel.HighlightBrush)) { // If the highlight changes we need to recalculate the inlines so the // highlighting is correct NotifyPropertyChanged(nameof(Inlines)); } }; } public virtual void NavigateTo() { var navigationService = Workspace.Services.GetService<IDocumentNavigationService>(); if (navigationService is null) { return; } // While navigating do not activate the tab, which will change focus from the tool window var options = Workspace.CurrentSolution.Options .WithChangedOption(new OptionKey(NavigationOptions.PreferProvisionalTab), true) .WithChangedOption(new OptionKey(NavigationOptions.ActivateTab), false); navigationService.TryNavigateToLineAndOffset(Workspace, DocumentId, LineSpan.Start, 0, options, ThreadingContext.DisposalToken); } private ImmutableArray<Inline> CalculateInlines() { if (ClassifiedSpans.IsDefaultOrEmpty) { return ImmutableArray<Inline>.Empty; } var classifiedTexts = ClassifiedSpans.SelectAsArray( cs => { return new ClassifiedText(cs.ClassificationType, _sourceText.ToString(cs.TextSpan)); }); var spanStartPosition = TextSpan.Start - ClassifiedSpans[0].TextSpan.Start; var highlightSpan = new TextSpan(spanStartPosition, TextSpan.Length); return classifiedTexts.ToInlines( TreeViewModel.ClassificationFormatMap, TreeViewModel.ClassificationTypeMap, (run, classifiedText, position) => { if (TreeViewModel.HighlightBrush is not null) { // Check the span start first because we always want to highlight a run that // is at the start, even if the TextSpan length is 0. If it's not the start, // highlighting should still happen if the run position is contained within // the span. if (position == highlightSpan.Start || highlightSpan.Contains(position)) { run.SetValue( TextElement.BackgroundProperty, TreeViewModel.HighlightBrush); } } }).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; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Windows.Documents; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class TreeItemViewModel : TreeViewItemBase { private readonly SourceText _sourceText; private readonly Glyph _glyph; private readonly IGlyphService _glyphService; protected ValueTrackingTreeViewModel TreeViewModel { get; } protected TextSpan TextSpan { get; } protected LineSpan LineSpan { get; } protected IThreadingContext ThreadingContext { get; } protected DocumentId DocumentId { get; } protected Workspace Workspace { get; } public int LineNumber => LineSpan.Start + 1; // LineSpan is 0 indexed, editors are not public string FileName { get; } public ImageSource GlyphImage => _glyph.GetImageSource(_glyphService); public bool ShowGlyph => !IsLoading; public ImmutableArray<ClassifiedSpan> ClassifiedSpans { get; } public ImmutableArray<Inline> Inlines => CalculateInlines(); public TreeItemViewModel( TextSpan textSpan, SourceText sourceText, DocumentId documentId, string fileName, Glyph glyph, ImmutableArray<ClassifiedSpan> classifiedSpans, ValueTrackingTreeViewModel treeViewModel, IGlyphService glyphService, IThreadingContext threadingContext, Workspace workspace, ImmutableArray<TreeItemViewModel> children = default) : base() { FileName = fileName; TextSpan = textSpan; _sourceText = sourceText; ClassifiedSpans = classifiedSpans; TreeViewModel = treeViewModel; ThreadingContext = threadingContext; _glyph = glyph; _glyphService = glyphService; Workspace = workspace; DocumentId = documentId; if (!children.IsDefaultOrEmpty) { foreach (var child in children) { ChildItems.Add(child); } } sourceText.GetLineAndOffset(textSpan.Start, out var lineStart, out var _); sourceText.GetLineAndOffset(textSpan.End, out var lineEnd, out var _); LineSpan = LineSpan.FromBounds(lineStart, lineEnd); PropertyChanged += (s, e) => { if (e.PropertyName == nameof(IsLoading)) { NotifyPropertyChanged(nameof(ShowGlyph)); } }; TreeViewModel.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(TreeViewModel.HighlightBrush)) { // If the highlight changes we need to recalculate the inlines so the // highlighting is correct NotifyPropertyChanged(nameof(Inlines)); } }; } public virtual void NavigateTo() { var navigationService = Workspace.Services.GetService<IDocumentNavigationService>(); if (navigationService is null) { return; } // While navigating do not activate the tab, which will change focus from the tool window var options = Workspace.CurrentSolution.Options .WithChangedOption(new OptionKey(NavigationOptions.PreferProvisionalTab), true) .WithChangedOption(new OptionKey(NavigationOptions.ActivateTab), false); navigationService.TryNavigateToLineAndOffset(Workspace, DocumentId, LineSpan.Start, 0, options, ThreadingContext.DisposalToken); } private ImmutableArray<Inline> CalculateInlines() { if (ClassifiedSpans.IsDefaultOrEmpty) { return ImmutableArray<Inline>.Empty; } var classifiedTexts = ClassifiedSpans.SelectAsArray( cs => { return new ClassifiedText(cs.ClassificationType, _sourceText.ToString(cs.TextSpan)); }); var spanStartPosition = TextSpan.Start - ClassifiedSpans[0].TextSpan.Start; var highlightSpan = new TextSpan(spanStartPosition, TextSpan.Length); return classifiedTexts.ToInlines( TreeViewModel.ClassificationFormatMap, TreeViewModel.ClassificationTypeMap, (run, classifiedText, position) => { if (TreeViewModel.HighlightBrush is not null) { // Check the span start first because we always want to highlight a run that // is at the start, even if the TextSpan length is 0. If it's not the start, // highlighting should still happen if the run position is contained within // the span. if (position == highlightSpan.Start || highlightSpan.Contains(position)) { run.SetValue( TextElement.BackgroundProperty, TreeViewModel.HighlightBrush); } } }).ToImmutableArray(); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/SyntaxDifferences.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.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Friend Module SyntaxDifferences Public Function GetRebuiltNodes(oldTree As SyntaxTree, newTree As SyntaxTree) As ImmutableArray(Of SyntaxNodeOrToken) Dim hashSet = New HashSet(Of GreenNode) GatherNodes(oldTree.GetRoot(), hashSet) Dim nodes = ArrayBuilder(Of SyntaxNodeOrToken).GetInstance() GetRebuiltNodes(newTree.GetRoot(), hashSet, nodes) Return nodes.ToImmutableAndFree() End Function Private Sub GetRebuiltNodes(newNode As SyntaxNodeOrToken, hashSet As HashSet(Of GreenNode), nodes As ArrayBuilder(Of SyntaxNodeOrToken)) If hashSet.Contains(newNode.UnderlyingNode) Then Return End If nodes.Add(newNode) For Each child In newNode.ChildNodesAndTokens() GetRebuiltNodes(child, hashSet, nodes) Next End Sub Private Sub GatherNodes(node As SyntaxNodeOrToken, hashSet As HashSet(Of GreenNode)) hashSet.Add(node.UnderlyingNode) For Each child In node.ChildNodesAndTokens() GatherNodes(child, hashSet) Next End Sub End Module
' 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.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Friend Module SyntaxDifferences Public Function GetRebuiltNodes(oldTree As SyntaxTree, newTree As SyntaxTree) As ImmutableArray(Of SyntaxNodeOrToken) Dim hashSet = New HashSet(Of GreenNode) GatherNodes(oldTree.GetRoot(), hashSet) Dim nodes = ArrayBuilder(Of SyntaxNodeOrToken).GetInstance() GetRebuiltNodes(newTree.GetRoot(), hashSet, nodes) Return nodes.ToImmutableAndFree() End Function Private Sub GetRebuiltNodes(newNode As SyntaxNodeOrToken, hashSet As HashSet(Of GreenNode), nodes As ArrayBuilder(Of SyntaxNodeOrToken)) If hashSet.Contains(newNode.UnderlyingNode) Then Return End If nodes.Add(newNode) For Each child In newNode.ChildNodesAndTokens() GetRebuiltNodes(child, hashSet, nodes) Next End Sub Private Sub GatherNodes(node As SyntaxNodeOrToken, hashSet As HashSet(Of GreenNode)) hashSet.Add(node.UnderlyingNode) For Each child In node.ChildNodesAndTokens() GatherNodes(child, hashSet) Next End Sub End Module
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.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="zh-Hant" original="../VSPackage.resx"> <body> <trans-unit id="101"> <source>C#</source> <target state="translated">C#</target> <note>Used many places.</note> </trans-unit> <trans-unit id="102"> <source>Advanced</source> <target state="translated">進階</target> <note>"Advanced" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="103"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note>"IntelliSense" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="104"> <source>C# Editor</source> <target state="translated">C# 編輯器</target> <note>"C# Editor" node in profile Import/Export.</note> </trans-unit> <trans-unit id="105"> <source>Settings for the C# editor found under the Advanced, Formatting, and IntelliSense nodes in the Tools/Options dialog box.</source> <target state="translated">在 [工具]/[選項] 對話方塊中的 [進階]、[格式化] 和 [IntelliSense] 節點下,所找到的 C# 編輯器設定。</target> <note>"C# Editor" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="106"> <source>Settings for general C# options found under the General and Tabs nodes in the Tools/Options dialog box.</source> <target state="translated">在 [工具]/[選項] 對話方塊中的 [一般] 及 [定位點] 節點下,所找到的一般 C# 選項設定。</target> <note>"C#" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="306"> <source>Underline reassigned variables; Display inline hints; Show diagnostics for closed files; Colorize regular expression; Highlight related components under cursor; Report invalid regular expressions; Enable full solution analysis; Perform editor feature analysis in external process; Enable navigation to decompiled sources; Using directives; Place system directives first when sorting usings; Separate using directive groups; Suggest usings for types in reference assemblies; Suggest usings for types in NuGet packages; Highlighting; Highlight references to symbol under cursor; Highlight related keywords under cursor; Outlining; Enter outlining mode when files open; Show procedure line separators; Show outlining for declaration level constructs; Show outlining for code level constructs; Show outlining for comments and preprocessor regions; Collapse regions when collapsing to definitions; Fading; Fade out unused usings; Fade out unreachable code; Block Structure Guides; Show guides for declaration level constructs; Show guides for code level constructs; Editor Help; Generate XML documentation comments for ///; Insert * at the start of new lines when writing /* */ comments; Show preview for rename tracking; Split string literals on Enter; Report invalid placeholders in string.Format calls; Extract Method; Don't put ref or out on custom struct; Implement Interface or Abstract Class; When inserting properties, events and methods, place them; with other members of the same kind; at the end; When generating property; prefer throwing properties; prefer auto properties; regex; regular expression; Use enhanced colors; Editor Color Scheme; Inheritance Margin;</source> <target state="needs-review-translation">顯示內嵌提示; 顯示已關閉檔案的診斷; 為規則運算式著色; 醒目提示游標下的相關元件; 回報無效的規則運算式; 啟用完整解決方案分析; 在外部處理序中執行編輯器功能分析; 啟用瀏覽至反向組譯的來源; using 指示詞; 排序 using 時先放置系統指示詞; 分隔 using 指示詞群組; 為參考組件中的類型建議 using; 為 NuGet 套件中的類型建議 using; 醒目提示; 醒目提示游標下的符號參考; 醒目提示游標下的相關關鍵字; 大綱; 在檔案開啟時進入大綱模式; 顯示程序行分隔符號; 顯示宣告層級建構的大綱; 顯示程式碼層級建構的大綱; 顯示註解與前置處理器區域的大綱; 在摺疊到定義時摺疊區域; 漸層; 淡出未使用的 using; 淡出無法執行到的程式碼; 區塊結構輔助線; 顯示宣告層級建構的輔助線; 顯示程式碼層級建構的輔助線; 編輯器說明; 產生 /// 的 XML 文件註解; 在撰寫 /* */ 註解時,於新行開頭插入 *; 顯示重新命名追蹤的預覽; 在按 Enter 鍵時分割字串常值; 回報 string.Format 呼叫中無效的預留位置; 擷取方法; 不要在自訂結構上放置 ref 或 out; 實作介面或抽象類別; 在插入屬性、事件和方法時,予以放置; 隨同其他同種類的成員; 結尾處; 產生屬性時; 建議使用擲回屬性; 建議使用自動屬性; regex; 規則運算式; 使用進階色彩; 編輯器色彩配置;</target> <note>C# Advanced options page keywords</note> </trans-unit> <trans-unit id="307"> <source>Automatically format when typing; Automatically format statement on semicolon ; Automatically format block on end brace; Automatically format on return; Automatically format on paste;</source> <target state="translated">在鍵入時自動格式化; 在分號處自動將陳述式格式化; 在右大括號處自動將區塊格式化; 在換行時自動格式化; 在貼上時自動格式化;</target> <note>C# Formatting &gt; General options page keywords</note> </trans-unit> <trans-unit id="308"> <source>Indent block contents; indent open and close braces; indent case contents; indent case contents (when block); indent case labels; label indentation; place goto labels in leftmost column; indent labels normally; place goto labels one indent less than current;</source> <target state="translated">將區塊內容縮排; 將左右大括號縮排; 將 case 內容縮排; 將 case 內容 (若為區塊) 縮排; 將 case 標籤縮排; 標籤縮排; 將 goto 標籤放入最左方欄位; 將標籤正常縮排; 將 goto 標籤在目前的位置凸出一排;</target> <note>C# Formatting &gt; Indentation options page keywords</note> </trans-unit> <trans-unit id="309"> <source>New line formatting option for braces;New line formatting options for keywords;New line options for braces; Place open brace on new line for types; Place open brace on new line for methods and local functions; Place open brace on new line for properties, indexers, and events; Place open brace on new line for property, indexer, and event accessors; Place open brace on new line for anonymous methods; Place open brace on new line for control blocks; Place open brace on new line for anonymous types; Place open brace on new line for object, collection and array initializers; New line options for keywords; Place else on new line; Place catch on new line; Place finally on new line; New line options for expression; Place members in object initializers on new line; Place members in anonymous types on new line; Place query expression clauses on new line;</source> <target state="translated">大括號的新行格式化選項;關鍵字的新行格式化選項;大括號的新行選項; 針對類型將左大括號換到新行; 針對方法和區域函式將左大括號換到新行; 針對屬性、索引子和事件將左大括號換到新行; 針對屬性、索引子和事件存取子將左大括號換到新行; 針對匿名方法將左大括號換到新行; 針對控制區塊將左大括號換到新行; 針對匿名類型將左大括號換到新行; 針對物件、集合和陣列初始設定式將左大括號換到新行; 關鍵字的新行選項; 將 else 換到新行; 將 catch 換到新行; 將 finally 換到新行; 運算式的新行選項; 將物件初始設定式中的成員換到新行; 將匿名類型中的成員換到新行; 將查詢運算式子句換到新行;</target> <note>C# Formatting &gt; New Lines options page keywords</note> </trans-unit> <trans-unit id="310"> <source>Set spacing for method declarations; Insert space between method name and its opening parenthesis; Insert space within parameter list parentheses; Insert space within empty parameter list parentheses; Set spacing for method calls; Insert space within argument list parentheses; Insert space within empty argument list parentheses; Set other spacing options; Insert space after keywords in control flow statements; Insert space within parentheses of expressions; Insert space within parentheses of type casts; Insert spaces within parentheses of control flow statements; Insert space after cast; Ignore spaces in declaration statements; Set spacing for brackets; Insert space before open square bracket; Insert space within empty square brackets; Insert spaces within square brackets; Set spacing for delimiters; Insert space after colon for base or interface in type declaration; Insert space after comma; Insert space after dot; Insert space after semicolon in for statement; Insert space before colon for base or interface in type declaration; Insert space before comma; Insert space before dot; Insert space before semicolon in for statement; Set spacing for operators; Ignore spaces around binary operators; Remove spaces before and after binary operators; Insert space before and after binary operators;</source> <target state="translated">設定方法宣告的間距; 在方法名稱及其左括號間插入空格; 在參數清單括號內插入空格; 在空白參數清單括號內插入空格; 設定方法呼叫的間距; 在引數清單括號內插入空格; 在空白引數清單括號內插入空格; 設定其他間距選項; 在控制流程陳述式中的關鍵字後插入空格; 在運算式的括號內插入空格; 在類型轉換的括號內插入空格; 在控制流程陳述式的括號內插入空格; 在轉換後插入空格; 略過宣告陳述式中的空格; 設定中括號的空格; 在左方括號前插入空格; 在空白方括號內插入空格; 在方括號內插入空格; 設定分隔符號的空格; 針對類型宣告中的基底或介面在冒號後插入空格; 在逗號後插入空格; 在點號後插入空格; 在 for 陳述式內的分號後插入空格; 針對類型宣告中的基底或介面在冒號前插入空格; 在逗號前插入空格; 在點號前插入空格; 在 for 陳述式內的分號前插入空格; 設定運算子的間距; 略過二元運算子周圍的空格; 移除二元運算子前後的空格; 在二元運算子前後插入空格;</target> <note>C# Formatting &gt; Spacing options page keywords</note> </trans-unit> <trans-unit id="311"> <source>Change formatting options for wrapping;leave block on single line;leave statements and member declarations on the same line</source> <target state="translated">變更換行的格式化選項;將區塊保留在同一行;將陳述式與成員宣告保留在同一行</target> <note>C# Formatting &gt; Wrapping options page keywords</note> </trans-unit> <trans-unit id="312"> <source>Change completion list settings;Pre-select most recently used member; Completion Lists; Show completion list after a character is typed; Show completion list after a character is deleted; Automatically show completion list in argument lists (experimental); Highlight matching portions of completion list items; Show completion item filters; Automatically complete statement on semicolon; Snippets behavior; Never include snippets; Always include snippets; Include snippets when ?-Tab is typed after an identifier; Enter key behavior; Never add new line on enter; Only add new line on enter after end of fully typed word; Always add new line on enter; Show name suggestions; Show items from unimported namespaces (experimental);</source> <target state="translated">變更自動完成清單設定;預先選取最近使用的成員; 自動完成清單; 在鍵入字元後顯示自動完成清單; 在刪除字元後顯示自動完成清單; 自動在引數清單中顯示自動完成清單 (實驗性); 醒目提示自動完成清單項目的相符部分; 顯示完成項目篩選; 在遇到分號時自動完成陳述式; 程式碼片段行為; 一律不包含程式碼片段; 一律包含程式碼片段; 在識別碼後鍵入 ?-Tab 時包含程式碼片段; Enter 鍵行為; 一律不在按下 Enter 鍵時新增一行程式碼; 只在按下 Enter 鍵時,於完整鍵入的文字結尾後新增一行程式碼; 一律在按下 Enter 鍵時新增一行程式碼; 顯示名稱建議; 顯示未匯入命名空間中的項目 (實驗性);</target> <note>C# IntelliSense options page keywords</note> </trans-unit> <trans-unit id="107"> <source>Formatting</source> <target state="translated">格式化</target> <note>"Formatting" category node under Tools &gt; Options, Text Editor, C#, Code Style (no corresponding keywords)</note> </trans-unit> <trans-unit id="108"> <source>General</source> <target state="translated">一般</target> <note>"General" node under Tools &gt; Options, Text Editor, C# (used for Code Style and Formatting)</note> </trans-unit> <trans-unit id="109"> <source>Indentation</source> <target state="translated">縮排</target> <note>"Indentation" node under Tools &gt; Options, Text Editor, C#, Formatting.</note> </trans-unit> <trans-unit id="110"> <source>Wrapping</source> <target state="translated">換行</target> <note /> </trans-unit> <trans-unit id="111"> <source>New Lines</source> <target state="translated">新行</target> <note /> </trans-unit> <trans-unit id="112"> <source>Spacing</source> <target state="translated">間距</target> <note /> </trans-unit> <trans-unit id="2358"> <source>C# Editor</source> <target state="translated">C# 編輯器</target> <note /> </trans-unit> <trans-unit id="2359"> <source>C# Editor with Encoding</source> <target state="translated">具備編碼功能的 C# 編輯器</target> <note /> </trans-unit> <trans-unit id="113"> <source>Microsoft Visual C#</source> <target state="translated">Microsoft Visual C#</target> <note>Used for String in Tools &gt; Options, Text Editor, File Extensions</note> </trans-unit> <trans-unit id="114"> <source>Code Style</source> <target state="translated">程式碼樣式</target> <note>"Code Style" category node under Tools &gt; Options, Text Editor, C# (no corresponding keywords)</note> </trans-unit> <trans-unit id="313"> <source>Style;Qualify;This;Code Style;var;member access;locals;parameters;var preferences;predefined type;framework type;built-in types;when variable type is apparent;elsewhere;qualify field access;qualify property access; qualify method access;qualify event access;</source> <target state="translated">樣式;限定;此;程式碼樣式;var;成員存取權;本機;參數;var 偏好;預先定義的類型;架構類型;內建類型;當變數類型明顯時;其他地方;限定欄位存取權;限定屬性存取權;限定方法存取權;限定事件存取權;</target> <note>C# Code Style options page keywords</note> </trans-unit> <trans-unit id="115"> <source>Naming</source> <target state="translated">命名</target> <note /> </trans-unit> <trans-unit id="314"> <source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source> <target state="translated">命名樣式;命名樣式;命名規則;命名慣例</target> <note>C# Naming Style options page keywords</note> </trans-unit> <trans-unit id="116"> <source>C# Tools</source> <target state="translated">C# 工具</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="117"> <source>C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source> <target state="translated">在 IDE 中使用的 C# 元件。根據您的專案類型與設定,可能會使用其他版本的編譯器。</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="An_empty_CSharp_script_file"> <source>An empty C# script file.</source> <target state="translated">空白的 C# 指令碼檔。</target> <note /> </trans-unit> <trans-unit id="Visual_CSharp_Script"> <source>Visual C# Script</source> <target state="translated">Visual C# 指令碼</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="zh-Hant" original="../VSPackage.resx"> <body> <trans-unit id="101"> <source>C#</source> <target state="translated">C#</target> <note>Used many places.</note> </trans-unit> <trans-unit id="102"> <source>Advanced</source> <target state="translated">進階</target> <note>"Advanced" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="103"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note>"IntelliSense" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="104"> <source>C# Editor</source> <target state="translated">C# 編輯器</target> <note>"C# Editor" node in profile Import/Export.</note> </trans-unit> <trans-unit id="105"> <source>Settings for the C# editor found under the Advanced, Formatting, and IntelliSense nodes in the Tools/Options dialog box.</source> <target state="translated">在 [工具]/[選項] 對話方塊中的 [進階]、[格式化] 和 [IntelliSense] 節點下,所找到的 C# 編輯器設定。</target> <note>"C# Editor" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="106"> <source>Settings for general C# options found under the General and Tabs nodes in the Tools/Options dialog box.</source> <target state="translated">在 [工具]/[選項] 對話方塊中的 [一般] 及 [定位點] 節點下,所找到的一般 C# 選項設定。</target> <note>"C#" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="306"> <source>Underline reassigned variables; Display inline hints; Show diagnostics for closed files; Colorize regular expression; Highlight related components under cursor; Report invalid regular expressions; Enable full solution analysis; Perform editor feature analysis in external process; Enable navigation to decompiled sources; Using directives; Place system directives first when sorting usings; Separate using directive groups; Suggest usings for types in reference assemblies; Suggest usings for types in NuGet packages; Highlighting; Highlight references to symbol under cursor; Highlight related keywords under cursor; Outlining; Enter outlining mode when files open; Show procedure line separators; Show outlining for declaration level constructs; Show outlining for code level constructs; Show outlining for comments and preprocessor regions; Collapse regions when collapsing to definitions; Fading; Fade out unused usings; Fade out unreachable code; Block Structure Guides; Show guides for declaration level constructs; Show guides for code level constructs; Editor Help; Generate XML documentation comments for ///; Insert * at the start of new lines when writing /* */ comments; Show preview for rename tracking; Split string literals on Enter; Report invalid placeholders in string.Format calls; Extract Method; Don't put ref or out on custom struct; Implement Interface or Abstract Class; When inserting properties, events and methods, place them; with other members of the same kind; at the end; When generating property; prefer throwing properties; prefer auto properties; regex; regular expression; Use enhanced colors; Editor Color Scheme; Inheritance Margin;</source> <target state="needs-review-translation">顯示內嵌提示; 顯示已關閉檔案的診斷; 為規則運算式著色; 醒目提示游標下的相關元件; 回報無效的規則運算式; 啟用完整解決方案分析; 在外部處理序中執行編輯器功能分析; 啟用瀏覽至反向組譯的來源; using 指示詞; 排序 using 時先放置系統指示詞; 分隔 using 指示詞群組; 為參考組件中的類型建議 using; 為 NuGet 套件中的類型建議 using; 醒目提示; 醒目提示游標下的符號參考; 醒目提示游標下的相關關鍵字; 大綱; 在檔案開啟時進入大綱模式; 顯示程序行分隔符號; 顯示宣告層級建構的大綱; 顯示程式碼層級建構的大綱; 顯示註解與前置處理器區域的大綱; 在摺疊到定義時摺疊區域; 漸層; 淡出未使用的 using; 淡出無法執行到的程式碼; 區塊結構輔助線; 顯示宣告層級建構的輔助線; 顯示程式碼層級建構的輔助線; 編輯器說明; 產生 /// 的 XML 文件註解; 在撰寫 /* */ 註解時,於新行開頭插入 *; 顯示重新命名追蹤的預覽; 在按 Enter 鍵時分割字串常值; 回報 string.Format 呼叫中無效的預留位置; 擷取方法; 不要在自訂結構上放置 ref 或 out; 實作介面或抽象類別; 在插入屬性、事件和方法時,予以放置; 隨同其他同種類的成員; 結尾處; 產生屬性時; 建議使用擲回屬性; 建議使用自動屬性; regex; 規則運算式; 使用進階色彩; 編輯器色彩配置;</target> <note>C# Advanced options page keywords</note> </trans-unit> <trans-unit id="307"> <source>Automatically format when typing; Automatically format statement on semicolon ; Automatically format block on end brace; Automatically format on return; Automatically format on paste;</source> <target state="translated">在鍵入時自動格式化; 在分號處自動將陳述式格式化; 在右大括號處自動將區塊格式化; 在換行時自動格式化; 在貼上時自動格式化;</target> <note>C# Formatting &gt; General options page keywords</note> </trans-unit> <trans-unit id="308"> <source>Indent block contents; indent open and close braces; indent case contents; indent case contents (when block); indent case labels; label indentation; place goto labels in leftmost column; indent labels normally; place goto labels one indent less than current;</source> <target state="translated">將區塊內容縮排; 將左右大括號縮排; 將 case 內容縮排; 將 case 內容 (若為區塊) 縮排; 將 case 標籤縮排; 標籤縮排; 將 goto 標籤放入最左方欄位; 將標籤正常縮排; 將 goto 標籤在目前的位置凸出一排;</target> <note>C# Formatting &gt; Indentation options page keywords</note> </trans-unit> <trans-unit id="309"> <source>New line formatting option for braces;New line formatting options for keywords;New line options for braces; Place open brace on new line for types; Place open brace on new line for methods and local functions; Place open brace on new line for properties, indexers, and events; Place open brace on new line for property, indexer, and event accessors; Place open brace on new line for anonymous methods; Place open brace on new line for control blocks; Place open brace on new line for anonymous types; Place open brace on new line for object, collection and array initializers; New line options for keywords; Place else on new line; Place catch on new line; Place finally on new line; New line options for expression; Place members in object initializers on new line; Place members in anonymous types on new line; Place query expression clauses on new line;</source> <target state="translated">大括號的新行格式化選項;關鍵字的新行格式化選項;大括號的新行選項; 針對類型將左大括號換到新行; 針對方法和區域函式將左大括號換到新行; 針對屬性、索引子和事件將左大括號換到新行; 針對屬性、索引子和事件存取子將左大括號換到新行; 針對匿名方法將左大括號換到新行; 針對控制區塊將左大括號換到新行; 針對匿名類型將左大括號換到新行; 針對物件、集合和陣列初始設定式將左大括號換到新行; 關鍵字的新行選項; 將 else 換到新行; 將 catch 換到新行; 將 finally 換到新行; 運算式的新行選項; 將物件初始設定式中的成員換到新行; 將匿名類型中的成員換到新行; 將查詢運算式子句換到新行;</target> <note>C# Formatting &gt; New Lines options page keywords</note> </trans-unit> <trans-unit id="310"> <source>Set spacing for method declarations; Insert space between method name and its opening parenthesis; Insert space within parameter list parentheses; Insert space within empty parameter list parentheses; Set spacing for method calls; Insert space within argument list parentheses; Insert space within empty argument list parentheses; Set other spacing options; Insert space after keywords in control flow statements; Insert space within parentheses of expressions; Insert space within parentheses of type casts; Insert spaces within parentheses of control flow statements; Insert space after cast; Ignore spaces in declaration statements; Set spacing for brackets; Insert space before open square bracket; Insert space within empty square brackets; Insert spaces within square brackets; Set spacing for delimiters; Insert space after colon for base or interface in type declaration; Insert space after comma; Insert space after dot; Insert space after semicolon in for statement; Insert space before colon for base or interface in type declaration; Insert space before comma; Insert space before dot; Insert space before semicolon in for statement; Set spacing for operators; Ignore spaces around binary operators; Remove spaces before and after binary operators; Insert space before and after binary operators;</source> <target state="translated">設定方法宣告的間距; 在方法名稱及其左括號間插入空格; 在參數清單括號內插入空格; 在空白參數清單括號內插入空格; 設定方法呼叫的間距; 在引數清單括號內插入空格; 在空白引數清單括號內插入空格; 設定其他間距選項; 在控制流程陳述式中的關鍵字後插入空格; 在運算式的括號內插入空格; 在類型轉換的括號內插入空格; 在控制流程陳述式的括號內插入空格; 在轉換後插入空格; 略過宣告陳述式中的空格; 設定中括號的空格; 在左方括號前插入空格; 在空白方括號內插入空格; 在方括號內插入空格; 設定分隔符號的空格; 針對類型宣告中的基底或介面在冒號後插入空格; 在逗號後插入空格; 在點號後插入空格; 在 for 陳述式內的分號後插入空格; 針對類型宣告中的基底或介面在冒號前插入空格; 在逗號前插入空格; 在點號前插入空格; 在 for 陳述式內的分號前插入空格; 設定運算子的間距; 略過二元運算子周圍的空格; 移除二元運算子前後的空格; 在二元運算子前後插入空格;</target> <note>C# Formatting &gt; Spacing options page keywords</note> </trans-unit> <trans-unit id="311"> <source>Change formatting options for wrapping;leave block on single line;leave statements and member declarations on the same line</source> <target state="translated">變更換行的格式化選項;將區塊保留在同一行;將陳述式與成員宣告保留在同一行</target> <note>C# Formatting &gt; Wrapping options page keywords</note> </trans-unit> <trans-unit id="312"> <source>Change completion list settings;Pre-select most recently used member; Completion Lists; Show completion list after a character is typed; Show completion list after a character is deleted; Automatically show completion list in argument lists (experimental); Highlight matching portions of completion list items; Show completion item filters; Automatically complete statement on semicolon; Snippets behavior; Never include snippets; Always include snippets; Include snippets when ?-Tab is typed after an identifier; Enter key behavior; Never add new line on enter; Only add new line on enter after end of fully typed word; Always add new line on enter; Show name suggestions; Show items from unimported namespaces (experimental);</source> <target state="translated">變更自動完成清單設定;預先選取最近使用的成員; 自動完成清單; 在鍵入字元後顯示自動完成清單; 在刪除字元後顯示自動完成清單; 自動在引數清單中顯示自動完成清單 (實驗性); 醒目提示自動完成清單項目的相符部分; 顯示完成項目篩選; 在遇到分號時自動完成陳述式; 程式碼片段行為; 一律不包含程式碼片段; 一律包含程式碼片段; 在識別碼後鍵入 ?-Tab 時包含程式碼片段; Enter 鍵行為; 一律不在按下 Enter 鍵時新增一行程式碼; 只在按下 Enter 鍵時,於完整鍵入的文字結尾後新增一行程式碼; 一律在按下 Enter 鍵時新增一行程式碼; 顯示名稱建議; 顯示未匯入命名空間中的項目 (實驗性);</target> <note>C# IntelliSense options page keywords</note> </trans-unit> <trans-unit id="107"> <source>Formatting</source> <target state="translated">格式化</target> <note>"Formatting" category node under Tools &gt; Options, Text Editor, C#, Code Style (no corresponding keywords)</note> </trans-unit> <trans-unit id="108"> <source>General</source> <target state="translated">一般</target> <note>"General" node under Tools &gt; Options, Text Editor, C# (used for Code Style and Formatting)</note> </trans-unit> <trans-unit id="109"> <source>Indentation</source> <target state="translated">縮排</target> <note>"Indentation" node under Tools &gt; Options, Text Editor, C#, Formatting.</note> </trans-unit> <trans-unit id="110"> <source>Wrapping</source> <target state="translated">換行</target> <note /> </trans-unit> <trans-unit id="111"> <source>New Lines</source> <target state="translated">新行</target> <note /> </trans-unit> <trans-unit id="112"> <source>Spacing</source> <target state="translated">間距</target> <note /> </trans-unit> <trans-unit id="2358"> <source>C# Editor</source> <target state="translated">C# 編輯器</target> <note /> </trans-unit> <trans-unit id="2359"> <source>C# Editor with Encoding</source> <target state="translated">具備編碼功能的 C# 編輯器</target> <note /> </trans-unit> <trans-unit id="113"> <source>Microsoft Visual C#</source> <target state="translated">Microsoft Visual C#</target> <note>Used for String in Tools &gt; Options, Text Editor, File Extensions</note> </trans-unit> <trans-unit id="114"> <source>Code Style</source> <target state="translated">程式碼樣式</target> <note>"Code Style" category node under Tools &gt; Options, Text Editor, C# (no corresponding keywords)</note> </trans-unit> <trans-unit id="313"> <source>Style;Qualify;This;Code Style;var;member access;locals;parameters;var preferences;predefined type;framework type;built-in types;when variable type is apparent;elsewhere;qualify field access;qualify property access; qualify method access;qualify event access;</source> <target state="translated">樣式;限定;此;程式碼樣式;var;成員存取權;本機;參數;var 偏好;預先定義的類型;架構類型;內建類型;當變數類型明顯時;其他地方;限定欄位存取權;限定屬性存取權;限定方法存取權;限定事件存取權;</target> <note>C# Code Style options page keywords</note> </trans-unit> <trans-unit id="115"> <source>Naming</source> <target state="translated">命名</target> <note /> </trans-unit> <trans-unit id="314"> <source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source> <target state="translated">命名樣式;命名樣式;命名規則;命名慣例</target> <note>C# Naming Style options page keywords</note> </trans-unit> <trans-unit id="116"> <source>C# Tools</source> <target state="translated">C# 工具</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="117"> <source>C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source> <target state="translated">在 IDE 中使用的 C# 元件。根據您的專案類型與設定,可能會使用其他版本的編譯器。</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="An_empty_CSharp_script_file"> <source>An empty C# script file.</source> <target state="translated">空白的 C# 指令碼檔。</target> <note /> </trans-unit> <trans-unit id="Visual_CSharp_Script"> <source>Visual C# Script</source> <target state="translated">Visual C# 指令碼</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.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 System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected sealed override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected sealed override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, 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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected sealed override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected sealed override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
-1