repo_name
string
pr_number
int64
pr_title
string
pr_description
string
author
string
date_created
unknown
date_merged
unknown
previous_commit
string
pr_commit
string
query
string
filepath
string
before_content
string
after_content
string
label
int64
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Analyzers/VisualBasic/Analyzers/SimplifyInterpolation/VisualBasicSimplifyInterpolationDiagnosticAnalyzer.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.Diagnostics Imports Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.SimplifyInterpolation Imports Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.VirtualChars Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyInterpolation <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicSimplifyInterpolationDiagnosticAnalyzer Inherits AbstractSimplifyInterpolationDiagnosticAnalyzer(Of InterpolationSyntax, ExpressionSyntax) Protected Overrides Function GetHelpers() As AbstractSimplifyInterpolationHelpers Return VisualBasicSimplifyInterpolationHelpers.Instance End Function Protected Overrides Function GetVirtualCharService() As IVirtualCharService Return VisualBasicVirtualCharService.Instance End Function Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts Return VisualBasicSyntaxFacts.Instance End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.SimplifyInterpolation Imports Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.VirtualChars Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyInterpolation <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicSimplifyInterpolationDiagnosticAnalyzer Inherits AbstractSimplifyInterpolationDiagnosticAnalyzer(Of InterpolationSyntax, ExpressionSyntax) Protected Overrides Function GetHelpers() As AbstractSimplifyInterpolationHelpers Return VisualBasicSimplifyInterpolationHelpers.Instance End Function Protected Overrides Function GetVirtualCharService() As IVirtualCharService Return VisualBasicVirtualCharService.Instance End Function Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts Return VisualBasicSyntaxFacts.Instance End Function End Class End Namespace
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { /// <summary> /// Base type for legacy C# and VB project system shim implementations. /// These legacy shims are based on legacy project system interfaces defined in csproj/msvbprj. /// </summary> internal abstract partial class AbstractLegacyProject : ForegroundThreadAffinitizedObject { public IVsHierarchy Hierarchy { get; } protected VisualStudioProject VisualStudioProject { get; } internal VisualStudioProjectOptionsProcessor VisualStudioProjectOptionsProcessor { get; set; } protected IProjectCodeModel ProjectCodeModel { get; set; } protected VisualStudioWorkspace Workspace { get; } internal VisualStudioProject Test_VisualStudioProject => VisualStudioProject; /// <summary> /// The path to the directory of the project. Read-only, since although you can rename /// a project in Visual Studio you can't change the folder of a project without an /// unload/reload. /// </summary> private readonly string _projectDirectory = null; /// <summary> /// Whether we should ignore the output path for this project because it's a special project. /// </summary> private readonly bool _ignoreOutputPath; private static readonly char[] PathSeparatorCharacters = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; #region Mutable fields that should only be used from the UI thread private readonly SolutionEventsBatchScopeCreator _batchScopeCreator; #endregion public AbstractLegacyProject( string projectSystemName, IVsHierarchy hierarchy, string language, bool isVsIntellisenseProject, IServiceProvider serviceProvider, IThreadingContext threadingContext, string externalErrorReportingPrefix) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(hierarchy); var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); Workspace = componentModel.GetService<VisualStudioWorkspace>(); var workspaceImpl = (VisualStudioWorkspaceImpl)Workspace; var projectFilePath = hierarchy.TryGetProjectFilePath(); if (projectFilePath != null && !File.Exists(projectFilePath)) { projectFilePath = null; } if (projectFilePath != null) { _projectDirectory = Path.GetDirectoryName(projectFilePath); } if (isVsIntellisenseProject) { // IVsIntellisenseProjects are usually used for contained language cases, which means these projects don't have any real // output path that we should consider. Since those point to the same IVsHierarchy as another project, we end up with two projects // with the same output path, which potentially breaks conversion of metadata references to project references. However they're // also used for database projects and a few other cases where there there isn't a "primary" IVsHierarchy. // As a heuristic here we'll ignore the output path if we already have another project tied to the IVsHierarchy. foreach (var projectId in Workspace.CurrentSolution.ProjectIds) { if (Workspace.GetHierarchy(projectId) == hierarchy) { _ignoreOutputPath = true; break; } } } var projectFactory = componentModel.GetService<VisualStudioProjectFactory>(); VisualStudioProject = threadingContext.JoinableTaskFactory.Run(() => projectFactory.CreateAndAddToWorkspaceAsync( projectSystemName, language, new VisualStudioProjectCreationInfo { // The workspace requires an assembly name so we can make compilations. We'll use // projectSystemName because they'll have a better one eventually. AssemblyName = projectSystemName, FilePath = projectFilePath, Hierarchy = hierarchy, ProjectGuid = GetProjectIDGuid(hierarchy), }, CancellationToken.None)); workspaceImpl.AddProjectRuleSetFileToInternalMaps( VisualStudioProject, () => VisualStudioProjectOptionsProcessor.EffectiveRuleSetFilePath); // Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace // by assigning the value of the project's root namespace to it. So various feature can choose to // use it for their own purpose. // In the future, we might consider officially exposing "default namespace" for VB project // (e.g. through a <defaultnamespace> msbuild property) VisualStudioProject.DefaultNamespace = GetRootNamespacePropertyValue(hierarchy); if (TryGetPropertyValue(hierarchy, AdditionalPropertyNames.MaxSupportedLangVersion, out var maxLangVer)) { VisualStudioProject.MaxLangVersion = maxLangVer; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzers, out var runAnayzers)) { VisualStudioProject.RunAnalyzers = runAnayzers; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, out var runAnayzersDuringLiveAnalysis)) { VisualStudioProject.RunAnalyzersDuringLiveAnalysis = runAnayzersDuringLiveAnalysis; } Hierarchy = hierarchy; ConnectHierarchyEvents(); RefreshBinOutputPath(); workspaceImpl.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); _externalErrorReporter = new ProjectExternalErrorReporter(VisualStudioProject.Id, externalErrorReportingPrefix, language, workspaceImpl); _batchScopeCreator = componentModel.GetService<SolutionEventsBatchScopeCreator>(); _batchScopeCreator.StartTrackingProject(VisualStudioProject, Hierarchy); } public string AssemblyName => VisualStudioProject.AssemblyName; public string GetOutputFileName() => VisualStudioProject.CompilationOutputAssemblyFilePath; public virtual void Disconnect() { _batchScopeCreator.StopTrackingProject(VisualStudioProject); VisualStudioProjectOptionsProcessor?.Dispose(); ProjectCodeModel.OnProjectClosed(); VisualStudioProject.RemoveFromWorkspace(); // Unsubscribe IVsHierarchyEvents DisconnectHierarchyEvents(); } protected void AddFile( string filename, SourceCodeKind sourceCodeKind) { AssertIsForeground(); // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } ImmutableArray<string> folders = default; var itemid = Hierarchy.TryGetItemId(filename); if (itemid != VSConstants.VSITEMID_NIL) { folders = GetFolderNamesForDocument(itemid); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void AddFile( string filename, string linkMetadata, SourceCodeKind sourceCodeKind) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } var folders = ImmutableArray<string>.Empty; if (!string.IsNullOrEmpty(linkMetadata)) { var linkFolderPath = Path.GetDirectoryName(linkMetadata); folders = linkFolderPath.Split(PathSeparatorCharacters, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray(); } else if (!string.IsNullOrEmpty(VisualStudioProject.FilePath)) { var relativePath = PathUtilities.GetRelativePath(_projectDirectory, filename); var relativePathParts = relativePath.Split(PathSeparatorCharacters); folders = ImmutableArray.Create(relativePathParts, start: 0, length: relativePathParts.Length - 1); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void RemoveFile(string filename) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } VisualStudioProject.RemoveSourceFile(filename); ProjectCodeModel.OnSourceFileRemoved(filename); } protected void RefreshBinOutputPath() { // These projects are created against the same hierarchy as the "main" project that // hosts the rest of the code; if we query the IVsHierarchy for the output path // we'll end up with duplicate output paths which can break P2P referencing. Since the output // path doesn't make sense for these, we'll ignore them. if (_ignoreOutputPath) { return; } if (Hierarchy is not IVsBuildPropertyStorage storage) { return; } if (ErrorHandler.Failed(storage.GetPropertyValue("OutDir", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var outputDirectory)) || ErrorHandler.Failed(storage.GetPropertyValue("TargetFileName", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetFileName))) { return; } if (targetFileName == null) { return; } // web app case if (!PathUtilities.IsAbsolute(outputDirectory)) { if (VisualStudioProject.FilePath == null) { return; } outputDirectory = FileUtilities.ResolveRelativePath(outputDirectory, Path.GetDirectoryName(VisualStudioProject.FilePath)); } if (outputDirectory == null) { return; } VisualStudioProject.OutputFilePath = FileUtilities.NormalizeAbsolutePath(Path.Combine(outputDirectory, targetFileName)); if (ErrorHandler.Succeeded(storage.GetPropertyValue("TargetRefPath", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetRefPath)) && !string.IsNullOrEmpty(targetRefPath)) { VisualStudioProject.OutputRefFilePath = targetRefPath; } else { VisualStudioProject.OutputRefFilePath = null; } } private static Guid GetProjectIDGuid(IVsHierarchy hierarchy) { if (hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_ProjectIDGuid, out var guid)) { return guid; } return Guid.Empty; } /// <summary> /// Map of folder item IDs in the workspace to the string version of their path. /// </summary> /// <remarks>Using item IDs as a key like this in a long-lived way is considered unsupported by CPS and other /// IVsHierarchy providers, but this code (which is fairly old) still makes the assumptions anyways.</remarks> private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new(); private ImmutableArray<string> GetFolderNamesForDocument(uint documentItemID) { AssertIsForeground(); if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { return GetFolderNamesForFolder(parentID); } } return ImmutableArray<string>.Empty; } private ImmutableArray<string> GetFolderNamesForFolder(uint folderItemID) { AssertIsForeground(); using var pooledObject = SharedPools.Default<List<string>>().GetPooledObject(); var newFolderNames = pooledObject.Object; if (!_folderNameMap.TryGetValue(folderItemID, out var folderNames)) { ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); folderNames = newFolderNames.ToImmutableArray(); _folderNameMap.Add(folderItemID, folderNames); } else { // verify names, and change map if we get a different set. // this is necessary because we only get document adds/removes from the project system // when a document name or folder name changes. ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); if (!Enumerable.SequenceEqual(folderNames, newFolderNames)) { folderNames = newFolderNames.ToImmutableArray(); _folderNameMap[folderItemID] = folderNames; } } return folderNames; } // Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds. // Technically it should be a uint. However, there's no enforcement of this, and marshalling // from native to managed can end up resulting in boxed ints instead. Handle both here so // we're resilient to however the IVsHierarchy was actually implemented. private static uint UnboxVSItemId(object id) => id is uint ? (uint)id : unchecked((uint)(int)id); private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy) { if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out var nameObj) == VSConstants.S_OK) { // For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>) // as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder // is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders. // Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to // worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for // VSITEMID.Root below already takes care of that. var name = (string)nameObj; if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase)) { names.Insert(0, name); } } if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { ComputeFolderNames(parentID, names, hierarchy); } } } /// <summary> /// Get the value of "rootnamespace" property of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// This property has different meaning between C# and VB, each project type can decide how to interpret the value. /// </remarks>> private static string GetRootNamespacePropertyValue(IVsHierarchy hierarchy) { // While both csproj and vbproj might define <rootnamespace> property in the project file, // they are very different things. // // In C#, it's called default namespace (even though we got the value from rootnamespace property), // and it doesn't affect the semantic of the code in anyway, just something used by VS. // For example, when you create a new class, the namespace for the new class is based on it. // Therefore, we can't get this info from compiler. // // However, in VB, it's actually called root namespace, and that info is part of the VB compilation // (parsed from arguments), because VB compiler needs it to determine the root of all the namespace // declared in the compilation. // // Unfortunately, although being different concepts, default namespace and root namespace are almost // used interchangeably in VS. For example, (1) the value is define in "rootnamespace" property in project // files and, (2) the property name we use to call into hierarchy below to retrieve the value is // called "DefaultNamespace". if (hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_DefaultNamespace, out string value)) { return value; } return null; } private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, out string propertyValue) { if (hierarchy is not IVsBuildPropertyStorage storage) { propertyValue = null; return false; } return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue)); } private static bool TryGetBoolPropertyValue(IVsHierarchy hierarchy, string propertyName, out bool? propertyValue) { if (!TryGetPropertyValue(hierarchy, propertyName, out var stringPropertyValue)) { propertyValue = null; return false; } propertyValue = bool.TryParse(stringPropertyValue, out var parsedBoolValue) ? parsedBoolValue : (bool?)null; 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.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { /// <summary> /// Base type for legacy C# and VB project system shim implementations. /// These legacy shims are based on legacy project system interfaces defined in csproj/msvbprj. /// </summary> internal abstract partial class AbstractLegacyProject : ForegroundThreadAffinitizedObject { public IVsHierarchy Hierarchy { get; } protected VisualStudioProject VisualStudioProject { get; } internal VisualStudioProjectOptionsProcessor VisualStudioProjectOptionsProcessor { get; set; } protected IProjectCodeModel ProjectCodeModel { get; set; } protected VisualStudioWorkspace Workspace { get; } internal VisualStudioProject Test_VisualStudioProject => VisualStudioProject; /// <summary> /// The path to the directory of the project. Read-only, since although you can rename /// a project in Visual Studio you can't change the folder of a project without an /// unload/reload. /// </summary> private readonly string _projectDirectory = null; /// <summary> /// Whether we should ignore the output path for this project because it's a special project. /// </summary> private readonly bool _ignoreOutputPath; private static readonly char[] PathSeparatorCharacters = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; #region Mutable fields that should only be used from the UI thread private readonly SolutionEventsBatchScopeCreator _batchScopeCreator; #endregion public AbstractLegacyProject( string projectSystemName, IVsHierarchy hierarchy, string language, bool isVsIntellisenseProject, IServiceProvider serviceProvider, IThreadingContext threadingContext, string externalErrorReportingPrefix) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(hierarchy); var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); Workspace = componentModel.GetService<VisualStudioWorkspace>(); var workspaceImpl = (VisualStudioWorkspaceImpl)Workspace; var projectFilePath = hierarchy.TryGetProjectFilePath(); if (projectFilePath != null && !File.Exists(projectFilePath)) { projectFilePath = null; } if (projectFilePath != null) { _projectDirectory = Path.GetDirectoryName(projectFilePath); } if (isVsIntellisenseProject) { // IVsIntellisenseProjects are usually used for contained language cases, which means these projects don't have any real // output path that we should consider. Since those point to the same IVsHierarchy as another project, we end up with two projects // with the same output path, which potentially breaks conversion of metadata references to project references. However they're // also used for database projects and a few other cases where there there isn't a "primary" IVsHierarchy. // As a heuristic here we'll ignore the output path if we already have another project tied to the IVsHierarchy. foreach (var projectId in Workspace.CurrentSolution.ProjectIds) { if (Workspace.GetHierarchy(projectId) == hierarchy) { _ignoreOutputPath = true; break; } } } var projectFactory = componentModel.GetService<VisualStudioProjectFactory>(); VisualStudioProject = threadingContext.JoinableTaskFactory.Run(() => projectFactory.CreateAndAddToWorkspaceAsync( projectSystemName, language, new VisualStudioProjectCreationInfo { // The workspace requires an assembly name so we can make compilations. We'll use // projectSystemName because they'll have a better one eventually. AssemblyName = projectSystemName, FilePath = projectFilePath, Hierarchy = hierarchy, ProjectGuid = GetProjectIDGuid(hierarchy), }, CancellationToken.None)); workspaceImpl.AddProjectRuleSetFileToInternalMaps( VisualStudioProject, () => VisualStudioProjectOptionsProcessor.EffectiveRuleSetFilePath); // Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace // by assigning the value of the project's root namespace to it. So various feature can choose to // use it for their own purpose. // In the future, we might consider officially exposing "default namespace" for VB project // (e.g. through a <defaultnamespace> msbuild property) VisualStudioProject.DefaultNamespace = GetRootNamespacePropertyValue(hierarchy); if (TryGetPropertyValue(hierarchy, AdditionalPropertyNames.MaxSupportedLangVersion, out var maxLangVer)) { VisualStudioProject.MaxLangVersion = maxLangVer; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzers, out var runAnayzers)) { VisualStudioProject.RunAnalyzers = runAnayzers; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, out var runAnayzersDuringLiveAnalysis)) { VisualStudioProject.RunAnalyzersDuringLiveAnalysis = runAnayzersDuringLiveAnalysis; } Hierarchy = hierarchy; ConnectHierarchyEvents(); RefreshBinOutputPath(); workspaceImpl.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); _externalErrorReporter = new ProjectExternalErrorReporter(VisualStudioProject.Id, externalErrorReportingPrefix, language, workspaceImpl); _batchScopeCreator = componentModel.GetService<SolutionEventsBatchScopeCreator>(); _batchScopeCreator.StartTrackingProject(VisualStudioProject, Hierarchy); } public string AssemblyName => VisualStudioProject.AssemblyName; public string GetOutputFileName() => VisualStudioProject.CompilationOutputAssemblyFilePath; public virtual void Disconnect() { _batchScopeCreator.StopTrackingProject(VisualStudioProject); VisualStudioProjectOptionsProcessor?.Dispose(); ProjectCodeModel.OnProjectClosed(); VisualStudioProject.RemoveFromWorkspace(); // Unsubscribe IVsHierarchyEvents DisconnectHierarchyEvents(); } protected void AddFile( string filename, SourceCodeKind sourceCodeKind) { AssertIsForeground(); // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } ImmutableArray<string> folders = default; var itemid = Hierarchy.TryGetItemId(filename); if (itemid != VSConstants.VSITEMID_NIL) { folders = GetFolderNamesForDocument(itemid); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void AddFile( string filename, string linkMetadata, SourceCodeKind sourceCodeKind) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } var folders = ImmutableArray<string>.Empty; if (!string.IsNullOrEmpty(linkMetadata)) { var linkFolderPath = Path.GetDirectoryName(linkMetadata); folders = linkFolderPath.Split(PathSeparatorCharacters, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray(); } else if (!string.IsNullOrEmpty(VisualStudioProject.FilePath)) { var relativePath = PathUtilities.GetRelativePath(_projectDirectory, filename); var relativePathParts = relativePath.Split(PathSeparatorCharacters); folders = ImmutableArray.Create(relativePathParts, start: 0, length: relativePathParts.Length - 1); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void RemoveFile(string filename) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } VisualStudioProject.RemoveSourceFile(filename); ProjectCodeModel.OnSourceFileRemoved(filename); } protected void RefreshBinOutputPath() { // These projects are created against the same hierarchy as the "main" project that // hosts the rest of the code; if we query the IVsHierarchy for the output path // we'll end up with duplicate output paths which can break P2P referencing. Since the output // path doesn't make sense for these, we'll ignore them. if (_ignoreOutputPath) { return; } if (Hierarchy is not IVsBuildPropertyStorage storage) { return; } if (ErrorHandler.Failed(storage.GetPropertyValue("OutDir", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var outputDirectory)) || ErrorHandler.Failed(storage.GetPropertyValue("TargetFileName", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetFileName))) { return; } if (targetFileName == null) { return; } // web app case if (!PathUtilities.IsAbsolute(outputDirectory)) { if (VisualStudioProject.FilePath == null) { return; } outputDirectory = FileUtilities.ResolveRelativePath(outputDirectory, Path.GetDirectoryName(VisualStudioProject.FilePath)); } if (outputDirectory == null) { return; } VisualStudioProject.OutputFilePath = FileUtilities.NormalizeAbsolutePath(Path.Combine(outputDirectory, targetFileName)); if (ErrorHandler.Succeeded(storage.GetPropertyValue("TargetRefPath", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetRefPath)) && !string.IsNullOrEmpty(targetRefPath)) { VisualStudioProject.OutputRefFilePath = targetRefPath; } else { VisualStudioProject.OutputRefFilePath = null; } } private static Guid GetProjectIDGuid(IVsHierarchy hierarchy) { if (hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_ProjectIDGuid, out var guid)) { return guid; } return Guid.Empty; } /// <summary> /// Map of folder item IDs in the workspace to the string version of their path. /// </summary> /// <remarks>Using item IDs as a key like this in a long-lived way is considered unsupported by CPS and other /// IVsHierarchy providers, but this code (which is fairly old) still makes the assumptions anyways.</remarks> private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new(); private ImmutableArray<string> GetFolderNamesForDocument(uint documentItemID) { AssertIsForeground(); if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { return GetFolderNamesForFolder(parentID); } } return ImmutableArray<string>.Empty; } private ImmutableArray<string> GetFolderNamesForFolder(uint folderItemID) { AssertIsForeground(); using var pooledObject = SharedPools.Default<List<string>>().GetPooledObject(); var newFolderNames = pooledObject.Object; if (!_folderNameMap.TryGetValue(folderItemID, out var folderNames)) { ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); folderNames = newFolderNames.ToImmutableArray(); _folderNameMap.Add(folderItemID, folderNames); } else { // verify names, and change map if we get a different set. // this is necessary because we only get document adds/removes from the project system // when a document name or folder name changes. ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); if (!Enumerable.SequenceEqual(folderNames, newFolderNames)) { folderNames = newFolderNames.ToImmutableArray(); _folderNameMap[folderItemID] = folderNames; } } return folderNames; } // Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds. // Technically it should be a uint. However, there's no enforcement of this, and marshalling // from native to managed can end up resulting in boxed ints instead. Handle both here so // we're resilient to however the IVsHierarchy was actually implemented. private static uint UnboxVSItemId(object id) => id is uint ? (uint)id : unchecked((uint)(int)id); private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy) { if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out var nameObj) == VSConstants.S_OK) { // For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>) // as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder // is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders. // Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to // worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for // VSITEMID.Root below already takes care of that. var name = (string)nameObj; if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase)) { names.Insert(0, name); } } if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { ComputeFolderNames(parentID, names, hierarchy); } } } /// <summary> /// Get the value of "rootnamespace" property of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// This property has different meaning between C# and VB, each project type can decide how to interpret the value. /// </remarks>> private static string GetRootNamespacePropertyValue(IVsHierarchy hierarchy) { // While both csproj and vbproj might define <rootnamespace> property in the project file, // they are very different things. // // In C#, it's called default namespace (even though we got the value from rootnamespace property), // and it doesn't affect the semantic of the code in anyway, just something used by VS. // For example, when you create a new class, the namespace for the new class is based on it. // Therefore, we can't get this info from compiler. // // However, in VB, it's actually called root namespace, and that info is part of the VB compilation // (parsed from arguments), because VB compiler needs it to determine the root of all the namespace // declared in the compilation. // // Unfortunately, although being different concepts, default namespace and root namespace are almost // used interchangeably in VS. For example, (1) the value is define in "rootnamespace" property in project // files and, (2) the property name we use to call into hierarchy below to retrieve the value is // called "DefaultNamespace". if (hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_DefaultNamespace, out string value)) { return value; } return null; } private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, out string propertyValue) { if (hierarchy is not IVsBuildPropertyStorage storage) { propertyValue = null; return false; } return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue)); } private static bool TryGetBoolPropertyValue(IVsHierarchy hierarchy, string propertyName, out bool? propertyValue) { if (!TryGetPropertyValue(hierarchy, propertyName, out var stringPropertyValue)) { propertyValue = null; return false; } propertyValue = bool.TryParse(stringPropertyValue, out var parsedBoolValue) ? parsedBoolValue : (bool?)null; return true; } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Features/Core/Portable/NavigateTo/INavigateToSearchResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchResult { string AdditionalInformation { get; } string Kind { get; } NavigateToMatchKind MatchKind { get; } bool IsCaseSensitive { get; } string Name { get; } ImmutableArray<TextSpan> NameMatchSpans { get; } string SecondarySort { get; } string Summary { get; } INavigableItem NavigableItem { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchResult { string AdditionalInformation { get; } string Kind { get; } NavigateToMatchKind MatchKind { get; } bool IsCaseSensitive { get; } string Name { get; } ImmutableArray<TextSpan> NameMatchSpans { get; } string SecondarySort { get; } string Summary { get; } INavigableItem NavigableItem { get; } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/EditorFeatures/VisualBasicTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.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. Option Strict On Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.PreferFrameworkType Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.PreferFrameworkTypeTests Partial Public Class PreferFrameworkTypeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Private ReadOnly onWithInfo As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion) Private ReadOnly offWithInfo As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Suggestion) Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicPreferFrameworkTypeDiagnosticAnalyzer(), New PreferFrameworkTypeCodeFixProvider()) End Function Private ReadOnly Property NoFrameworkType As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo} } End Get End Property Private ReadOnly Property FrameworkTypeEverywhere As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo} } End Get End Property Private ReadOnly Property FrameworkTypeInDeclaration As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo} } End Get End Property Private ReadOnly Property FrameworkTypeInMemberAccess As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo} } End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotWhenOptionsAreNotSet() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|Integer|] End Class ", New TestParameters(options:=NoFrameworkType)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnUserdefinedType() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|C|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnFrameworkType() As Task Await TestMissingInRegularAndScriptAsync(" Imports System Class C Protected i As [|Int32|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnQualifiedTypeSyntax() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|System.Int32|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|List|](Of Integer) End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnIdentifierThatIsNotTypeSyntax() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected [|i|] As Integer End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnBoolean_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Boolean|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnByte_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Byte|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnChar_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Char|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnObject_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Object|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnSByte_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|SByte|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnString_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|String|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnSingle_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Single|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnDecimal_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Decimal|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnDouble_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Double|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FieldDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Protected i As [|Integer|] End Class ", "Imports System Class C Protected i As Int32 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FieldDeclarationWithInitializer() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Protected i As [|Integer|] = 5 End Class ", "Imports System Class C Protected i As Int32 = 5 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function DelegateDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Delegate Function PerformCalculation(x As Integer, y As Integer) As [|Integer|] End Class ", "Imports System Class C Public Delegate Function PerformCalculation(x As Integer, y As Integer) As Int32 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function PropertyDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Property X As [|Long|] End Class ", "Imports System Class C Public Property X As Int64 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function GenericPropertyDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Class C Public Property X As List(Of [|Long|]) End Class ", "Imports System Imports System.Collections.Generic Class C Public Property X As List(Of Int64) End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FunctionDeclarationReturnType() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Function F() As [|Integer|] End Function End Class ", "Imports System Class C Public Function F() As Int32 End Function End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MethodDeclarationParameters() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub F(x As [|Integer|]) End Sub End Class ", "Imports System Class C Public Sub F(x As Int32) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function GenericMethodInvocation() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Method(Of T)() End Sub Public Sub Test() Method(Of [|Integer|])() End Sub End Class ", "Imports System Class C Public Sub Method(Of T)() End Sub Public Sub Test() Method(Of Int32)() End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function LocalDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x As [|Integer|] = 5 End Sub End Class ", "Imports System Class C Public Sub Test() Dim x As Int32 = 5 End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MemberAccess() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x = [|Integer|].MaxValue End Sub End Class ", "Imports System Class C Public Sub Test() Dim x = Int32.MaxValue End Sub End Class ", options:=FrameworkTypeInMemberAccess) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MemberAccess2() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x = [|Integer|].Parse(""1"") End Sub End Class ", "Imports System Class C Public Sub Test() Dim x = Int32.Parse(""1"") End Sub End Class ", options:=FrameworkTypeInMemberAccess) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function DocCommentTriviaCrefExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C ''' <see cref=""[|Integer|].MaxValue""/> Public Sub Test() End Sub End Class ", "Imports System Class C ''' <see cref=""Integer.MaxValue""/> Public Sub Test() End Sub End Class ", options:=FrameworkTypeInMemberAccess) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function GetTypeExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x = GetType([|Integer|]) End Sub End Class ", "Imports System Class C Public Sub Test() Dim x = GetType(Int32) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FormalParametersWithinLambdaExression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim func3 As Func(Of Integer, Integer) = Function(z As [|Integer|]) z + 1 End Sub End Class ", "Imports System Class C Public Sub Test() Dim func3 As Func(Of Integer, Integer) = Function(z As Int32) z + 1 End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ObjectCreationExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim z = New [|Date|](2016, 8, 23) End Sub End Class ", "Imports System Class C Public Sub Test() Dim z = New DateTime(2016, 8, 23) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ArrayDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim k As [|Integer|]() = New Integer(3) {} End Sub End Class ", "Imports System Class C Public Sub Test() Dim k As Int32() = New Integer(3) {} End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ArrayInitializer() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim k As Integer() = New [|Integer|](3) {0, 1, 2, 3} End Sub End Class ", "Imports System Class C Public Sub Test() Dim k As Integer() = New Int32(3) {0, 1, 2, 3} End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MultiDimentionalArrayAsGenericTypeParameter() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Class C Public Sub Test() Dim a As List(Of [|Integer|]()(,)(,,,)) End Sub End Class ", "Imports System Imports System.Collections.Generic Class C Public Sub Test() Dim a As List(Of Int32()(,)(,,,)) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ForStatement() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() For j As [|Integer|] = 0 To 3 Next End Sub End Class ", "Imports System Class C Public Sub Test() For j As Int32 = 0 To 3 Next End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ForeachStatement() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() For Each item As [|Integer|] In New Integer() {1, 2, 3} Next End Sub End Class ", "Imports System Class C Public Sub Test() For Each item As Int32 In New Integer() {1, 2, 3} Next End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function LeadingTrivia() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() ' This is a comment Dim x As [|Integer|] End Sub End Class", "Imports System Class C Public Sub Test() ' This is a comment Dim x As Int32 End Sub End Class", options:=FrameworkTypeInDeclaration) 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. Option Strict On Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.PreferFrameworkType Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.PreferFrameworkTypeTests Partial Public Class PreferFrameworkTypeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Private ReadOnly onWithInfo As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion) Private ReadOnly offWithInfo As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Suggestion) Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicPreferFrameworkTypeDiagnosticAnalyzer(), New PreferFrameworkTypeCodeFixProvider()) End Function Private ReadOnly Property NoFrameworkType As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo} } End Get End Property Private ReadOnly Property FrameworkTypeEverywhere As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo} } End Get End Property Private ReadOnly Property FrameworkTypeInDeclaration As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo} } End Get End Property Private ReadOnly Property FrameworkTypeInMemberAccess As OptionsCollection Get Return New OptionsCollection(GetLanguage()) From { {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Suggestion}, {CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo} } End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotWhenOptionsAreNotSet() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|Integer|] End Class ", New TestParameters(options:=NoFrameworkType)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnUserdefinedType() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|C|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnFrameworkType() As Task Await TestMissingInRegularAndScriptAsync(" Imports System Class C Protected i As [|Int32|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnQualifiedTypeSyntax() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|System.Int32|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected i As [|List|](Of Integer) End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnIdentifierThatIsNotTypeSyntax() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected [|i|] As Integer End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnBoolean_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Boolean|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnByte_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Byte|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnChar_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Char|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnObject_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Object|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnSByte_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|SByte|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnString_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|String|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnSingle_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Single|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnDecimal_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Decimal|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function NotOnDouble_KeywordMatchesTypeName() As Task Await TestMissingInRegularAndScriptAsync(" Class C Protected x As [|Double|] End Class ", New TestParameters(options:=FrameworkTypeEverywhere)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FieldDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Protected i As [|Integer|] End Class ", "Imports System Class C Protected i As Int32 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FieldDeclarationWithInitializer() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Protected i As [|Integer|] = 5 End Class ", "Imports System Class C Protected i As Int32 = 5 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function DelegateDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Delegate Function PerformCalculation(x As Integer, y As Integer) As [|Integer|] End Class ", "Imports System Class C Public Delegate Function PerformCalculation(x As Integer, y As Integer) As Int32 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function PropertyDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Property X As [|Long|] End Class ", "Imports System Class C Public Property X As Int64 End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function GenericPropertyDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Class C Public Property X As List(Of [|Long|]) End Class ", "Imports System Imports System.Collections.Generic Class C Public Property X As List(Of Int64) End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FunctionDeclarationReturnType() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Function F() As [|Integer|] End Function End Class ", "Imports System Class C Public Function F() As Int32 End Function End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MethodDeclarationParameters() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub F(x As [|Integer|]) End Sub End Class ", "Imports System Class C Public Sub F(x As Int32) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function GenericMethodInvocation() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Method(Of T)() End Sub Public Sub Test() Method(Of [|Integer|])() End Sub End Class ", "Imports System Class C Public Sub Method(Of T)() End Sub Public Sub Test() Method(Of Int32)() End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function LocalDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x As [|Integer|] = 5 End Sub End Class ", "Imports System Class C Public Sub Test() Dim x As Int32 = 5 End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MemberAccess() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x = [|Integer|].MaxValue End Sub End Class ", "Imports System Class C Public Sub Test() Dim x = Int32.MaxValue End Sub End Class ", options:=FrameworkTypeInMemberAccess) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MemberAccess2() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x = [|Integer|].Parse(""1"") End Sub End Class ", "Imports System Class C Public Sub Test() Dim x = Int32.Parse(""1"") End Sub End Class ", options:=FrameworkTypeInMemberAccess) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function DocCommentTriviaCrefExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C ''' <see cref=""[|Integer|].MaxValue""/> Public Sub Test() End Sub End Class ", "Imports System Class C ''' <see cref=""Integer.MaxValue""/> Public Sub Test() End Sub End Class ", options:=FrameworkTypeInMemberAccess) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function GetTypeExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim x = GetType([|Integer|]) End Sub End Class ", "Imports System Class C Public Sub Test() Dim x = GetType(Int32) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function FormalParametersWithinLambdaExression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim func3 As Func(Of Integer, Integer) = Function(z As [|Integer|]) z + 1 End Sub End Class ", "Imports System Class C Public Sub Test() Dim func3 As Func(Of Integer, Integer) = Function(z As Int32) z + 1 End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ObjectCreationExpression() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim z = New [|Date|](2016, 8, 23) End Sub End Class ", "Imports System Class C Public Sub Test() Dim z = New DateTime(2016, 8, 23) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ArrayDeclaration() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim k As [|Integer|]() = New Integer(3) {} End Sub End Class ", "Imports System Class C Public Sub Test() Dim k As Int32() = New Integer(3) {} End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ArrayInitializer() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() Dim k As Integer() = New [|Integer|](3) {0, 1, 2, 3} End Sub End Class ", "Imports System Class C Public Sub Test() Dim k As Integer() = New Int32(3) {0, 1, 2, 3} End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function MultiDimentionalArrayAsGenericTypeParameter() As Task Await TestInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Class C Public Sub Test() Dim a As List(Of [|Integer|]()(,)(,,,)) End Sub End Class ", "Imports System Imports System.Collections.Generic Class C Public Sub Test() Dim a As List(Of Int32()(,)(,,,)) End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ForStatement() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() For j As [|Integer|] = 0 To 3 Next End Sub End Class ", "Imports System Class C Public Sub Test() For j As Int32 = 0 To 3 Next End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function ForeachStatement() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() For Each item As [|Integer|] In New Integer() {1, 2, 3} Next End Sub End Class ", "Imports System Class C Public Sub Test() For Each item As Int32 In New Integer() {1, 2, 3} Next End Sub End Class ", options:=FrameworkTypeInDeclaration) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)> Public Async Function LeadingTrivia() As Task Await TestInRegularAndScriptAsync( "Imports System Class C Public Sub Test() ' This is a comment Dim x As [|Integer|] End Sub End Class", "Imports System Class C Public Sub Test() ' This is a comment Dim x As Int32 End Sub End Class", options:=FrameworkTypeInDeclaration) End Function End Class End Namespace
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/IAnonymousTypeDisplayExtensions.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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class IAnonymousTypeDisplayExtensions { public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes( this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position) { var result = parts; while (true) { var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType()); if (delegateAnonymousType == null) { break; } result = result == parts ? new List<SymbolDisplayPart>(parts) : result; ReplaceAnonymousType(result, delegateAnonymousType, service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position)); } return result; } private static void ReplaceAnonymousType( IList<SymbolDisplayPart> list, INamedTypeSymbol anonymousType, IEnumerable<SymbolDisplayPart> parts) { var index = list.IndexOf(p => anonymousType.Equals(p.Symbol)); if (index >= 0) { var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList(); list.Clear(); list.AddRange(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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class IAnonymousTypeDisplayExtensions { public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes( this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position) { var result = parts; while (true) { var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType()); if (delegateAnonymousType == null) { break; } result = result == parts ? new List<SymbolDisplayPart>(parts) : result; ReplaceAnonymousType(result, delegateAnonymousType, service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position)); } return result; } private static void ReplaceAnonymousType( IList<SymbolDisplayPart> list, INamedTypeSymbol anonymousType, IEnumerable<SymbolDisplayPart> parts) { var index = list.IndexOf(p => anonymousType.Equals(p.Symbol)); if (index >= 0) { var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList(); list.Clear(); list.AddRange(result); } } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/PropertyAccessorSymbolReferenceFinder.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal sealed class PropertyAccessorSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol> { protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind.IsPropertyAccessor(); protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // If we've been asked to search for specific accessors, then do not cascade. // We don't want to produce results for the associated property. return options.AssociatePropertyReferencesWithSpecificAccessor || symbol.AssociatedSymbol == null ? SpecializedTasks.EmptyImmutableArray<ISymbol>() : Task.FromResult(ImmutableArray.Create(symbol.AssociatedSymbol)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // First, find any documents with the full name of the accessor (i.e. get_Goo). // This will find explicit calls to the method (which can happen when C# references // a VB parameterized property). var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var propertyDocuments = ImmutableArray<Document>.Empty; if (symbol.AssociatedSymbol is IPropertySymbol property && options.AssociatePropertyReferencesWithSpecificAccessor) { // we want to associate normal property references with the specific accessor being // referenced. So we also need to include documents with our property's name. Just // defer to the Property finder to find these docs and combine them with the result. propertyDocuments = await ReferenceFinders.Property.DetermineDocumentsToSearchAsync( property, globalAliases, project, documents, options.With(associatePropertyReferencesWithSpecificAccessor: false), cancellationToken).ConfigureAwait(false); } var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(propertyDocuments, documentsWithGlobalAttributes); } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol symbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var references = await FindReferencesInDocumentUsingSymbolNameAsync( symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); if (symbol.AssociatedSymbol is IPropertySymbol property && options.AssociatePropertyReferencesWithSpecificAccessor) { var propertyReferences = await ReferenceFinders.Property.FindReferencesInDocumentAsync( property, globalAliases, document, semanticModel, options.With(associatePropertyReferencesWithSpecificAccessor: false), cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var accessorReferences = propertyReferences.WhereAsArray( loc => { var accessors = GetReferencedAccessorSymbols( syntaxFacts, semanticFacts, semanticModel, property, loc.Node, cancellationToken); return accessors.Contains(symbol); }); references = references.AddRange(accessorReferences); } return references; } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal sealed class PropertyAccessorSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol> { protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind.IsPropertyAccessor(); protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IMethodSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // If we've been asked to search for specific accessors, then do not cascade. // We don't want to produce results for the associated property. return options.AssociatePropertyReferencesWithSpecificAccessor || symbol.AssociatedSymbol == null ? SpecializedTasks.EmptyImmutableArray<ISymbol>() : Task.FromResult(ImmutableArray.Create(symbol.AssociatedSymbol)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // First, find any documents with the full name of the accessor (i.e. get_Goo). // This will find explicit calls to the method (which can happen when C# references // a VB parameterized property). var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var propertyDocuments = ImmutableArray<Document>.Empty; if (symbol.AssociatedSymbol is IPropertySymbol property && options.AssociatePropertyReferencesWithSpecificAccessor) { // we want to associate normal property references with the specific accessor being // referenced. So we also need to include documents with our property's name. Just // defer to the Property finder to find these docs and combine them with the result. propertyDocuments = await ReferenceFinders.Property.DetermineDocumentsToSearchAsync( property, globalAliases, project, documents, options.With(associatePropertyReferencesWithSpecificAccessor: false), cancellationToken).ConfigureAwait(false); } var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(propertyDocuments, documentsWithGlobalAttributes); } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol symbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var references = await FindReferencesInDocumentUsingSymbolNameAsync( symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); if (symbol.AssociatedSymbol is IPropertySymbol property && options.AssociatePropertyReferencesWithSpecificAccessor) { var propertyReferences = await ReferenceFinders.Property.FindReferencesInDocumentAsync( property, globalAliases, document, semanticModel, options.With(associatePropertyReferencesWithSpecificAccessor: false), cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var accessorReferences = propertyReferences.WhereAsArray( loc => { var accessors = GetReferencedAccessorSymbols( syntaxFacts, semanticFacts, semanticModel, property, loc.Node, cancellationToken); return accessors.Contains(symbol); }); references = references.AddRange(accessorReferences); } return references; } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Compilers/VisualBasic/Test/Symbol/StaticLocalDeclarationTests.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 Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class StaticLocalDeclarationTests Inherits BasicTestBase <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static Dim x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithoutDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarations_InSameScopes() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InSameScopes() StaticLocal_DuplicationDeclarations_InSameScopes() End Sub Sub StaticLocal_DuplicationDeclarations_InSameScopes() Static x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31401: Static local variable 'x' is already declared. Static x As Integer = 2 'Err ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal1() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Static x As Integer = 1 'Err Console.WriteLine(x) Dim x As Integer = 2 Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Dim x As Integer = 2 ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal2() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Dim x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Static x As Integer = 2 'Err ~ </expected>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Try Dim y As Integer = 1 Static x As Integer = 1 Catch ex As Exception Dim y As Integer = 2 Static x As Integer = 2 'Error End Try End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(1) StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(2) End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(a As Integer) Select Case a Case 1 Dim y As Integer = 1 Static x As Integer = 1 Case 2 Dim y As Integer = 1 Static x As Integer = 1 'Error End Select End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_If() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_If() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_If() If True Then Dim y As Integer = 1 Static x As Integer = 1 Else Dim y As Integer = 2 Static x As Integer = 2 'Error End If End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_For() 'Show differences between static local and normal local Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_For() Dim y As Integer = 1 Static x As Integer = 1 'Warning Hide in enclosing block For i = 1 To 2 Dim y As Integer = 2 'Warning Hide in enclosing block Static x As Integer = 3 'Error Next End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "y").WithArguments("y"), Diagnostic(ERRID.ERR_BlockLocalShadowing1, "x").WithArguments("x"), Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InGeneric() 'Cannot declare in generic method Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x as new UDTest() x.Goo(of Integer)() x.Goo(of Integer)() End Sub End Module Public Class UDTest Public Sub Goo(of t) Static SLItem as integer = 1 SLItem +=1 End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInGenericMethod, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InStructure() 'Cannot declare in Structure Type Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x As New UDTest() x.Goo() x.Goo() End Sub End Module Public Structure UDTest Public Sub Goo() Static SLItem As Integer = 1 SLItem += 1 End Sub End Structure </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInStruct, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_WithModifiers() 'Errors in conjunction with access modifiers Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() End Sub Sub AccessModifiers() 'These are prettylisted with Access Modified beforehand Public Static SLItem1 As String = "" Private Static SLItem2 As String = "" Protected Static SLItem3 As String = "" Friend Static SLItem4 As String = "" Protected Friend Static SLItem5 As String = "" Static Shared SLItem6 Static Dim SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Public").WithArguments("Public"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Private").WithArguments("Private"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem6").WithArguments("SLItem6")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_OutsideOfMethod() 'Static Locals outside of method bodies Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() AccessModifiers() End Sub Static SLItem_Valid1 As String = "" 'Invalid Sub AccessModifiers() Static SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadDimFlags1, "Static").WithArguments("Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_TryingToAccessStaticLocalFromOutsideMethod() 'trying to access SL from oUtside method not possible Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() 'trying to access SL from oUtside method not possible StaticLocalInSub() StaticLocalInSub.slItem = 2 'ERROR StaticLocalInSub2() StaticLocalInSub2.slItem = 2 'ERROR End Sub Sub StaticLocalInSub() Static SLItem1 = 1 SLItem1 += 1 End Sub Public Sub StaticLocalInSub2() 'With Method Accessibility set to Public Static SLItem1 = 1 SLItem1 += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub"), Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_HideLocalInCatchBlock() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() 'trying to access SL from oUtside method not possible Test4_Err() End Sub Public Sub Test4_Err() Static sl1 As String = "" Try Throw New Exception("Test") Catch sl1 As Exception 'Err sl1 &amp;= "InCatch" 'Err - this is the exception instance not the static local Finally End Try End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "sl1").WithArguments("sl1"), Diagnostic(ERRID.ERR_BinaryOperands3, "sl1 &= ""InCatch""").WithArguments("&", "System.Exception", "String")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameClashInIdentifier() 'declare UnEscaped identifier called static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts1() End Sub Sub AvoidingNameConflicts1() Static Static as double = 1 'Error End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "as"), Diagnostic(ERRID.ERR_DuplicateSpecifier, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameTypeClash() 'declare escaped identifier and type called static along with static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As New [Static] End Sub End Module Class Static 'Error Clash With Keyword End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_SingleLine() 'Single Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InSingleLineLambda() End Sub Sub InSingleLineLambda() Static sl1 As Integer = 0 'Declaring Static in Single Line Lambda Dim l1 = Sub() static x1 As Integer = 0 'Error Dim l2 = Function() static x2 As Integer = 0 'Error 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 Dim l4 = Function() (sl1 + 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_SubDisallowsStatement, "static x1 As Integer = 0")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_MultiLine() 'Multi-Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InMultiLineLambda() End Sub Sub InMultiLineLambda() Static sl1 As Integer = 0 'Declaring Static in MultiLine Dim l1 = Sub() static x1 As Integer = 0 'Error End Sub Dim l2 = Function() static x2 As Integer = 0 'Error Return x2 End Function 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 End Sub Dim l4 = Function() sl1 += 1 Return sl1 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StaticInLambda, "static"), Diagnostic(ERRID.ERR_StaticInLambda, "static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalInTryCatchBlockScope() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test(False) test(True) End Sub Sub test(ThrowException As Boolean) Try If ThrowException Then Throw New Exception End If Catch ex As Exception Static sl As Integer = 1 sl += 1 End Try Console.WriteLine(SL.tostring) 'Error Outside Scope End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "SL").WithArguments("SL")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_ArgIterator() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As ArgIterator End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "ArgIterator").WithArguments("System.ArgIterator"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem2").WithArguments("SLItem2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_TypedReference() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As TypedReference = Nothing End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "TypedReference").WithArguments("System.TypedReference")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalWithRangeVariables() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test() test() End Sub Sub test() Static sl As Integer = 1 Dim x = From sl In {1, 2, 3} Select sl 'Error Same Scope Console.WriteLine(sl.ToString) sl += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "{1, 2, 3}").WithArguments("Integer()"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl")) 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 Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class StaticLocalDeclarationTests Inherits BasicTestBase <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static Dim x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithoutDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarations_InSameScopes() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InSameScopes() StaticLocal_DuplicationDeclarations_InSameScopes() End Sub Sub StaticLocal_DuplicationDeclarations_InSameScopes() Static x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31401: Static local variable 'x' is already declared. Static x As Integer = 2 'Err ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal1() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Static x As Integer = 1 'Err Console.WriteLine(x) Dim x As Integer = 2 Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Dim x As Integer = 2 ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal2() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Dim x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Static x As Integer = 2 'Err ~ </expected>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Try Dim y As Integer = 1 Static x As Integer = 1 Catch ex As Exception Dim y As Integer = 2 Static x As Integer = 2 'Error End Try End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(1) StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(2) End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(a As Integer) Select Case a Case 1 Dim y As Integer = 1 Static x As Integer = 1 Case 2 Dim y As Integer = 1 Static x As Integer = 1 'Error End Select End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_If() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_If() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_If() If True Then Dim y As Integer = 1 Static x As Integer = 1 Else Dim y As Integer = 2 Static x As Integer = 2 'Error End If End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_For() 'Show differences between static local and normal local Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_For() Dim y As Integer = 1 Static x As Integer = 1 'Warning Hide in enclosing block For i = 1 To 2 Dim y As Integer = 2 'Warning Hide in enclosing block Static x As Integer = 3 'Error Next End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "y").WithArguments("y"), Diagnostic(ERRID.ERR_BlockLocalShadowing1, "x").WithArguments("x"), Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InGeneric() 'Cannot declare in generic method Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x as new UDTest() x.Goo(of Integer)() x.Goo(of Integer)() End Sub End Module Public Class UDTest Public Sub Goo(of t) Static SLItem as integer = 1 SLItem +=1 End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInGenericMethod, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InStructure() 'Cannot declare in Structure Type Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x As New UDTest() x.Goo() x.Goo() End Sub End Module Public Structure UDTest Public Sub Goo() Static SLItem As Integer = 1 SLItem += 1 End Sub End Structure </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInStruct, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_WithModifiers() 'Errors in conjunction with access modifiers Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() End Sub Sub AccessModifiers() 'These are prettylisted with Access Modified beforehand Public Static SLItem1 As String = "" Private Static SLItem2 As String = "" Protected Static SLItem3 As String = "" Friend Static SLItem4 As String = "" Protected Friend Static SLItem5 As String = "" Static Shared SLItem6 Static Dim SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Public").WithArguments("Public"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Private").WithArguments("Private"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem6").WithArguments("SLItem6")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_OutsideOfMethod() 'Static Locals outside of method bodies Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() AccessModifiers() End Sub Static SLItem_Valid1 As String = "" 'Invalid Sub AccessModifiers() Static SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadDimFlags1, "Static").WithArguments("Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_TryingToAccessStaticLocalFromOutsideMethod() 'trying to access SL from oUtside method not possible Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() 'trying to access SL from oUtside method not possible StaticLocalInSub() StaticLocalInSub.slItem = 2 'ERROR StaticLocalInSub2() StaticLocalInSub2.slItem = 2 'ERROR End Sub Sub StaticLocalInSub() Static SLItem1 = 1 SLItem1 += 1 End Sub Public Sub StaticLocalInSub2() 'With Method Accessibility set to Public Static SLItem1 = 1 SLItem1 += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub"), Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_HideLocalInCatchBlock() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() 'trying to access SL from oUtside method not possible Test4_Err() End Sub Public Sub Test4_Err() Static sl1 As String = "" Try Throw New Exception("Test") Catch sl1 As Exception 'Err sl1 &amp;= "InCatch" 'Err - this is the exception instance not the static local Finally End Try End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "sl1").WithArguments("sl1"), Diagnostic(ERRID.ERR_BinaryOperands3, "sl1 &= ""InCatch""").WithArguments("&", "System.Exception", "String")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameClashInIdentifier() 'declare UnEscaped identifier called static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts1() End Sub Sub AvoidingNameConflicts1() Static Static as double = 1 'Error End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "as"), Diagnostic(ERRID.ERR_DuplicateSpecifier, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameTypeClash() 'declare escaped identifier and type called static along with static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As New [Static] End Sub End Module Class Static 'Error Clash With Keyword End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_SingleLine() 'Single Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InSingleLineLambda() End Sub Sub InSingleLineLambda() Static sl1 As Integer = 0 'Declaring Static in Single Line Lambda Dim l1 = Sub() static x1 As Integer = 0 'Error Dim l2 = Function() static x2 As Integer = 0 'Error 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 Dim l4 = Function() (sl1 + 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_SubDisallowsStatement, "static x1 As Integer = 0")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_MultiLine() 'Multi-Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InMultiLineLambda() End Sub Sub InMultiLineLambda() Static sl1 As Integer = 0 'Declaring Static in MultiLine Dim l1 = Sub() static x1 As Integer = 0 'Error End Sub Dim l2 = Function() static x2 As Integer = 0 'Error Return x2 End Function 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 End Sub Dim l4 = Function() sl1 += 1 Return sl1 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StaticInLambda, "static"), Diagnostic(ERRID.ERR_StaticInLambda, "static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalInTryCatchBlockScope() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test(False) test(True) End Sub Sub test(ThrowException As Boolean) Try If ThrowException Then Throw New Exception End If Catch ex As Exception Static sl As Integer = 1 sl += 1 End Try Console.WriteLine(SL.tostring) 'Error Outside Scope End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "SL").WithArguments("SL")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_ArgIterator() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As ArgIterator End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "ArgIterator").WithArguments("System.ArgIterator"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem2").WithArguments("SLItem2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_TypedReference() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As TypedReference = Nothing End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "TypedReference").WithArguments("System.TypedReference")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalWithRangeVariables() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test() test() End Sub Sub test() Static sl As Integer = 1 Dim x = From sl In {1, 2, 3} Select sl 'Error Same Scope Console.WriteLine(sl.ToString) sl += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "{1, 2, 3}").WithArguments("Integer()"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl")) End Sub End Class End Namespace
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Workspaces/CSharp/Portable/CodeGeneration/PropertyGenerator.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 Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class PropertyGenerator { public static bool CanBeGenerated(IPropertySymbol property) => property.IsIndexer || property.Parameters.Length == 0; private static MemberDeclarationSyntax LastPropertyOrField( SyntaxList<MemberDeclarationSyntax> members) { var lastProperty = members.LastOrDefault(m => m is PropertyDeclarationSyntax); return lastProperty ?? LastField(members); } internal static CompilationUnitSyntax AddPropertyTo( CompilationUnitSyntax destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GeneratePropertyOrIndexer( property, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastPropertyOrField, before: FirstMember); return destination.WithMembers(members); } internal static TypeDeclarationSyntax AddPropertyTo( TypeDeclarationSyntax destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GeneratePropertyOrIndexer(property, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, declaration, options, availableIndices, after: LastPropertyOrField, before: FirstMember); // Find the best place to put the field. It should go after the last field if we already // have fields, or at the beginning of the file if we don't. return AddMembersTo(destination, members); } public static MemberDeclarationSyntax GeneratePropertyOrIndexer( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(property, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = property.IsIndexer ? GenerateIndexerDeclaration(property, destination, options, parseOptions) : GeneratePropertyDeclaration(property, destination, options, parseOptions); return ConditionallyAddDocumentationCommentTo(declaration, property, options); } private static MemberDeclarationSyntax GenerateIndexerDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations); var declaration = SyntaxFactory.IndexerDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options), modifiers: GenerateModifiers(property, destination, options), type: GenerateTypeSyntax(property), explicitInterfaceSpecifier: explicitInterfaceSpecifier, parameterList: ParameterGenerator.GenerateBracketedParameterList(property.Parameters, explicitInterfaceSpecifier != null, options), accessorList: GenerateAccessorList(property, destination, options, parseOptions)); declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo( AddAnnotationsTo(property, declaration)); } private static MemberDeclarationSyntax GeneratePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var initializer = CodeGenerationPropertyInfo.GetInitializer(property) is ExpressionSyntax initializerNode ? SyntaxFactory.EqualsValueClause(initializerNode) : null; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations); var accessorList = GenerateAccessorList(property, destination, options, parseOptions); var propertyDeclaration = SyntaxFactory.PropertyDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options), modifiers: GenerateModifiers(property, destination, options), type: GenerateTypeSyntax(property), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: property.Name.ToIdentifierToken(), accessorList: accessorList, expressionBody: null, initializer: initializer); propertyDeclaration = UseExpressionBodyIfDesired(options, propertyDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo( AddAnnotationsTo(property, propertyDeclaration)); } private static TypeSyntax GenerateTypeSyntax(IPropertySymbol property) { var returnType = property.Type; if (property.ReturnsByRef) { return returnType.GenerateRefTypeSyntax(); } else if (property.ReturnsByRefReadonly) { return returnType.GenerateRefReadOnlyTypeSyntax(); } else { return returnType.GenerateTypeSyntax(); } } private static bool TryGetExpressionBody( BasePropertyDeclarationSyntax baseProperty, ParseOptions options, ExpressionBodyPreference preference, out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken) { var accessorList = baseProperty.AccessorList; if (preference != ExpressionBodyPreference.Never && accessorList.Accessors.Count == 1) { var accessor = accessorList.Accessors[0]; if (accessor.IsKind(SyntaxKind.GetAccessorDeclaration)) { return TryGetArrowExpressionBody( baseProperty.Kind(), accessor, options, preference, out arrowExpression, out semicolonToken); } } arrowExpression = null; semicolonToken = default; return false; } private static PropertyDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, PropertyDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value; if (declaration.Initializer == null) { if (TryGetExpressionBody( declaration, parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { declaration = declaration.WithAccessorList(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } } return declaration; } private static IndexerDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, IndexerDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers).Value; if (TryGetExpressionBody( declaration, parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { declaration = declaration.WithAccessorList(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return declaration; } private static AccessorDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, AccessorDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value; if (declaration.Body.TryConvertToArrowExpressionBody( declaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { declaration = declaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return declaration; } private static bool TryGetArrowExpressionBody( SyntaxKind declaratoinKind, AccessorDeclarationSyntax accessor, ParseOptions options, ExpressionBodyPreference preference, out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken) { // If the accessor has an expression body already, then use that as the expression body // for the property. if (accessor.ExpressionBody != null) { arrowExpression = accessor.ExpressionBody; semicolonToken = accessor.SemicolonToken; return true; } return accessor.Body.TryConvertToArrowExpressionBody( declaratoinKind, options, preference, out arrowExpression, out semicolonToken); } private static AccessorListSyntax GenerateAccessorList( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var setAccessorKind = property.SetMethod?.IsInitOnly == true ? SyntaxKind.InitAccessorDeclaration : SyntaxKind.SetAccessorDeclaration; var accessors = new List<AccessorDeclarationSyntax> { GenerateAccessorDeclaration(property, property.GetMethod, SyntaxKind.GetAccessorDeclaration, destination, options, parseOptions), GenerateAccessorDeclaration(property, property.SetMethod, setAccessorKind, destination, options, parseOptions), }; return accessors[0] == null && accessors[1] == null ? null : SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList()); } private static AccessorDeclarationSyntax GenerateAccessorDeclaration( IPropertySymbol property, IMethodSymbol accessor, SyntaxKind kind, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var hasBody = options.GenerateMethodBodies && HasAccessorBodies(property, destination, accessor); return accessor == null ? null : GenerateAccessorDeclaration(property, accessor, kind, hasBody, options, parseOptions); } private static AccessorDeclarationSyntax GenerateAccessorDeclaration( IPropertySymbol property, IMethodSymbol accessor, SyntaxKind kind, bool hasBody, CodeGenerationOptions options, ParseOptions parseOptions) { var declaration = SyntaxFactory.AccessorDeclaration(kind) .WithModifiers(GenerateAccessorModifiers(property, accessor, options)) .WithBody(hasBody ? GenerateBlock(accessor) : null) .WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken)); declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions); return AddAnnotationsTo(accessor, declaration); } private static BlockSyntax GenerateBlock(IMethodSymbol accessor) { return SyntaxFactory.Block( StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor))); } private static bool HasAccessorBodies( IPropertySymbol property, CodeGenerationDestination destination, IMethodSymbol accessor) { return destination != CodeGenerationDestination.InterfaceType && !property.IsAbstract && accessor != null && !accessor.IsAbstract; } private static SyntaxTokenList GenerateAccessorModifiers( IPropertySymbol property, IMethodSymbol accessor, CodeGenerationOptions options) { var modifiers = ArrayBuilder<SyntaxToken>.GetInstance(); if (accessor.DeclaredAccessibility != Accessibility.NotApplicable && accessor.DeclaredAccessibility != property.DeclaredAccessibility) { AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, options, property.DeclaredAccessibility); } var hasNonReadOnlyAccessor = property.GetMethod?.IsReadOnly == false || property.SetMethod?.IsReadOnly == false; if (hasNonReadOnlyAccessor && accessor.IsReadOnly) { modifiers.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } return modifiers.ToSyntaxTokenListAndFree(); } private static SyntaxTokenList GenerateModifiers( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Most modifiers not allowed if we're an explicit impl. if (!property.ExplicitInterfaceImplementations.Any()) { if (destination is not CodeGenerationDestination.CompilationUnit and not CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(property.DeclaredAccessibility, tokens, options, Accessibility.Private); if (property.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } // note: explicit interface impls are allowed to be 'readonly' but it never actually affects callers // because of the boxing requirement in order to call the method. // therefore it seems like a small oversight to leave out the keyword for an explicit impl from metadata. var hasAllReadOnlyAccessors = property.GetMethod?.IsReadOnly != false && property.SetMethod?.IsReadOnly != false; // Don't show the readonly modifier if the containing type is already readonly if (hasAllReadOnlyAccessors && !property.ContainingType.IsReadOnly) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (property.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } if (property.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (property.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (property.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } } } if (CodeGenerationPropertyInfo.GetIsUnsafe(property)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } return tokens.ToSyntaxTokenList(); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class PropertyGenerator { public static bool CanBeGenerated(IPropertySymbol property) => property.IsIndexer || property.Parameters.Length == 0; private static MemberDeclarationSyntax LastPropertyOrField( SyntaxList<MemberDeclarationSyntax> members) { var lastProperty = members.LastOrDefault(m => m is PropertyDeclarationSyntax); return lastProperty ?? LastField(members); } internal static CompilationUnitSyntax AddPropertyTo( CompilationUnitSyntax destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GeneratePropertyOrIndexer( property, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastPropertyOrField, before: FirstMember); return destination.WithMembers(members); } internal static TypeDeclarationSyntax AddPropertyTo( TypeDeclarationSyntax destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GeneratePropertyOrIndexer(property, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, declaration, options, availableIndices, after: LastPropertyOrField, before: FirstMember); // Find the best place to put the field. It should go after the last field if we already // have fields, or at the beginning of the file if we don't. return AddMembersTo(destination, members); } public static MemberDeclarationSyntax GeneratePropertyOrIndexer( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(property, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = property.IsIndexer ? GenerateIndexerDeclaration(property, destination, options, parseOptions) : GeneratePropertyDeclaration(property, destination, options, parseOptions); return ConditionallyAddDocumentationCommentTo(declaration, property, options); } private static MemberDeclarationSyntax GenerateIndexerDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations); var declaration = SyntaxFactory.IndexerDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options), modifiers: GenerateModifiers(property, destination, options), type: GenerateTypeSyntax(property), explicitInterfaceSpecifier: explicitInterfaceSpecifier, parameterList: ParameterGenerator.GenerateBracketedParameterList(property.Parameters, explicitInterfaceSpecifier != null, options), accessorList: GenerateAccessorList(property, destination, options, parseOptions)); declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo( AddAnnotationsTo(property, declaration)); } private static MemberDeclarationSyntax GeneratePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var initializer = CodeGenerationPropertyInfo.GetInitializer(property) is ExpressionSyntax initializerNode ? SyntaxFactory.EqualsValueClause(initializerNode) : null; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations); var accessorList = GenerateAccessorList(property, destination, options, parseOptions); var propertyDeclaration = SyntaxFactory.PropertyDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options), modifiers: GenerateModifiers(property, destination, options), type: GenerateTypeSyntax(property), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: property.Name.ToIdentifierToken(), accessorList: accessorList, expressionBody: null, initializer: initializer); propertyDeclaration = UseExpressionBodyIfDesired(options, propertyDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo( AddAnnotationsTo(property, propertyDeclaration)); } private static TypeSyntax GenerateTypeSyntax(IPropertySymbol property) { var returnType = property.Type; if (property.ReturnsByRef) { return returnType.GenerateRefTypeSyntax(); } else if (property.ReturnsByRefReadonly) { return returnType.GenerateRefReadOnlyTypeSyntax(); } else { return returnType.GenerateTypeSyntax(); } } private static bool TryGetExpressionBody( BasePropertyDeclarationSyntax baseProperty, ParseOptions options, ExpressionBodyPreference preference, out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken) { var accessorList = baseProperty.AccessorList; if (preference != ExpressionBodyPreference.Never && accessorList.Accessors.Count == 1) { var accessor = accessorList.Accessors[0]; if (accessor.IsKind(SyntaxKind.GetAccessorDeclaration)) { return TryGetArrowExpressionBody( baseProperty.Kind(), accessor, options, preference, out arrowExpression, out semicolonToken); } } arrowExpression = null; semicolonToken = default; return false; } private static PropertyDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, PropertyDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value; if (declaration.Initializer == null) { if (TryGetExpressionBody( declaration, parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { declaration = declaration.WithAccessorList(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } } return declaration; } private static IndexerDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, IndexerDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers).Value; if (TryGetExpressionBody( declaration, parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { declaration = declaration.WithAccessorList(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return declaration; } private static AccessorDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, AccessorDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value; if (declaration.Body.TryConvertToArrowExpressionBody( declaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { declaration = declaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return declaration; } private static bool TryGetArrowExpressionBody( SyntaxKind declaratoinKind, AccessorDeclarationSyntax accessor, ParseOptions options, ExpressionBodyPreference preference, out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken) { // If the accessor has an expression body already, then use that as the expression body // for the property. if (accessor.ExpressionBody != null) { arrowExpression = accessor.ExpressionBody; semicolonToken = accessor.SemicolonToken; return true; } return accessor.Body.TryConvertToArrowExpressionBody( declaratoinKind, options, preference, out arrowExpression, out semicolonToken); } private static AccessorListSyntax GenerateAccessorList( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var setAccessorKind = property.SetMethod?.IsInitOnly == true ? SyntaxKind.InitAccessorDeclaration : SyntaxKind.SetAccessorDeclaration; var accessors = new List<AccessorDeclarationSyntax> { GenerateAccessorDeclaration(property, property.GetMethod, SyntaxKind.GetAccessorDeclaration, destination, options, parseOptions), GenerateAccessorDeclaration(property, property.SetMethod, setAccessorKind, destination, options, parseOptions), }; return accessors[0] == null && accessors[1] == null ? null : SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList()); } private static AccessorDeclarationSyntax GenerateAccessorDeclaration( IPropertySymbol property, IMethodSymbol accessor, SyntaxKind kind, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var hasBody = options.GenerateMethodBodies && HasAccessorBodies(property, destination, accessor); return accessor == null ? null : GenerateAccessorDeclaration(property, accessor, kind, hasBody, options, parseOptions); } private static AccessorDeclarationSyntax GenerateAccessorDeclaration( IPropertySymbol property, IMethodSymbol accessor, SyntaxKind kind, bool hasBody, CodeGenerationOptions options, ParseOptions parseOptions) { var declaration = SyntaxFactory.AccessorDeclaration(kind) .WithModifiers(GenerateAccessorModifiers(property, accessor, options)) .WithBody(hasBody ? GenerateBlock(accessor) : null) .WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken)); declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions); return AddAnnotationsTo(accessor, declaration); } private static BlockSyntax GenerateBlock(IMethodSymbol accessor) { return SyntaxFactory.Block( StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor))); } private static bool HasAccessorBodies( IPropertySymbol property, CodeGenerationDestination destination, IMethodSymbol accessor) { return destination != CodeGenerationDestination.InterfaceType && !property.IsAbstract && accessor != null && !accessor.IsAbstract; } private static SyntaxTokenList GenerateAccessorModifiers( IPropertySymbol property, IMethodSymbol accessor, CodeGenerationOptions options) { var modifiers = ArrayBuilder<SyntaxToken>.GetInstance(); if (accessor.DeclaredAccessibility != Accessibility.NotApplicable && accessor.DeclaredAccessibility != property.DeclaredAccessibility) { AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, options, property.DeclaredAccessibility); } var hasNonReadOnlyAccessor = property.GetMethod?.IsReadOnly == false || property.SetMethod?.IsReadOnly == false; if (hasNonReadOnlyAccessor && accessor.IsReadOnly) { modifiers.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } return modifiers.ToSyntaxTokenListAndFree(); } private static SyntaxTokenList GenerateModifiers( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Most modifiers not allowed if we're an explicit impl. if (!property.ExplicitInterfaceImplementations.Any()) { if (destination is not CodeGenerationDestination.CompilationUnit and not CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(property.DeclaredAccessibility, tokens, options, Accessibility.Private); if (property.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } // note: explicit interface impls are allowed to be 'readonly' but it never actually affects callers // because of the boxing requirement in order to call the method. // therefore it seems like a small oversight to leave out the keyword for an explicit impl from metadata. var hasAllReadOnlyAccessors = property.GetMethod?.IsReadOnly != false && property.SetMethod?.IsReadOnly != false; // Don't show the readonly modifier if the containing type is already readonly if (hasAllReadOnlyAccessors && !property.ContainingType.IsReadOnly) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (property.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } if (property.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (property.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (property.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } } } if (CodeGenerationPropertyInfo.GetIsUnsafe(property)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } return tokens.ToSyntaxTokenList(); } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/EditorFeatures/CSharpTest/Intents/GenerateConstructorIntentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Intents { [UseExportProvider] public class GenerateConstructorIntentTests : IntentTestsBase { [Fact] public async Task GenerateConstructorSimpleResult() { var initialText = @"class C { private readonly int _someInt; {|typed:public C|} }"; var expectedText = @"class C { private readonly int _someInt; public C(int someInt) { _someInt = someInt; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorTypedPrivate() { var initialText = @"class C { private readonly int _someInt; {|typed:private C|} }"; var expectedText = @"class C { private readonly int _someInt; public C(int someInt) { _someInt = someInt; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithFieldsInPartial() { var initialText = @"partial class C { {|typed:public C|} }"; var additionalDocuments = new string[] { @"partial class C { private readonly int _someInt; }" }; var expectedText = @"partial class C { public C(int someInt) { _someInt = someInt; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, additionalDocuments, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithReferenceType() { var initialText = @"class C { private readonly object _someObject; {|typed:public C|} }"; var expectedText = @"class C { private readonly object _someObject; public C(object someObject) { _someObject = someObject; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithExpressionBodyOption() { var initialText = @"class C { private readonly int _someInt; {|typed:public C|} }"; var expectedText = @"class C { private readonly int _someInt; public C(int someInt) => _someInt = someInt; }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText, options: new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement } }).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Intents { [UseExportProvider] public class GenerateConstructorIntentTests : IntentTestsBase { [Fact] public async Task GenerateConstructorSimpleResult() { var initialText = @"class C { private readonly int _someInt; {|typed:public C|} }"; var expectedText = @"class C { private readonly int _someInt; public C(int someInt) { _someInt = someInt; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorTypedPrivate() { var initialText = @"class C { private readonly int _someInt; {|typed:private C|} }"; var expectedText = @"class C { private readonly int _someInt; public C(int someInt) { _someInt = someInt; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithFieldsInPartial() { var initialText = @"partial class C { {|typed:public C|} }"; var additionalDocuments = new string[] { @"partial class C { private readonly int _someInt; }" }; var expectedText = @"partial class C { public C(int someInt) { _someInt = someInt; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, additionalDocuments, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithReferenceType() { var initialText = @"class C { private readonly object _someObject; {|typed:public C|} }"; var expectedText = @"class C { private readonly object _someObject; public C(object someObject) { _someObject = someObject; } }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText).ConfigureAwait(false); } [Fact] public async Task GenerateConstructorWithExpressionBodyOption() { var initialText = @"class C { private readonly int _someInt; {|typed:public C|} }"; var expectedText = @"class C { private readonly int _someInt; public C(int someInt) => _someInt = someInt; }"; await VerifyExpectedTextAsync(WellKnownIntents.GenerateConstructor, initialText, expectedText, options: new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement } }).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/VisualStudio/Core/Test/CodeModel/AbstractFileCodeModelTests.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.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractFileCodeModelTests Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2) Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() End Using End Sub Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object)) TestOperation(code, Sub(fileCodeModel) Dim children = fileCodeModel.CodeElements Assert.Equal(expectedChildren.Length, children.Count) For i = 1 To children.Count expectedChildren(i - 1)(children.Item(i)) Next End Sub) End Sub Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(data.Name, newAttribute.Name) End Sub) End Function Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newClass) Assert.Equal(data.Name, newClass.Name) End Sub) End Function Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access) Assert.NotNull(newDelegate) Assert.Equal(data.Name, newDelegate.Name) End Sub) End Function Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access) Assert.NotNull(newEnum) Assert.Equal(data.Name, newEnum.Name) End Sub) End Function Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias) Assert.NotNull(newImport) Assert.Equal(data.Namespace, newImport.Namespace) If data.Alias IsNot Nothing Then Assert.Equal(data.Alias, newImport.Alias) End If End Sub) End Function Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access) Assert.NotNull(newInterface) Assert.Equal(data.Name, newInterface.Name) End Sub) End Function Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position) Assert.NotNull(newNamespace) Assert.Equal(data.Name, newNamespace.Name) End Sub) End Function Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newStruct) Assert.Equal(data.Name, newStruct.Name) End Sub) End Function Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) fileCodeModel.Remove(element) End Sub) 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.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractFileCodeModelTests Inherits AbstractCodeModelObjectTests(Of EnvDTE80.FileCodeModel2) Protected Async Function TestOperation(code As XElement, expectedCode As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestOperation)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function Protected Sub TestOperation(code As XElement, operation As Action(Of EnvDTE80.FileCodeModel2)) Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) operation(fileCodeModel) End Using Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() operation(fileCodeModel) fileCodeModel.EndBatch() End Using End Sub Protected Overrides Sub TestChildren(code As XElement, ParamArray expectedChildren() As Action(Of Object)) TestOperation(code, Sub(fileCodeModel) Dim children = fileCodeModel.CodeElements Assert.Equal(expectedChildren.Length, children.Count) For i = 1 To children.Count expectedChildren(i - 1)(children.Item(i)) Next End Sub) End Sub Protected Overrides Async Function TestAddAttribute(code As XElement, expectedCode As XElement, data As AttributeData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(data.Name, newAttribute.Name) End Sub) End Function Protected Overrides Async Function TestAddClass(code As XElement, expectedCode As XElement, data As ClassData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newClass = fileCodeModel.AddClass(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newClass) Assert.Equal(data.Name, newClass.Name) End Sub) End Function Protected Overrides Async Function TestAddDelegate(code As XElement, expectedCode As XElement, data As DelegateData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newDelegate = fileCodeModel.AddDelegate(data.Name, data.Type, data.Position, data.Access) Assert.NotNull(newDelegate) Assert.Equal(data.Name, newDelegate.Name) End Sub) End Function Protected Overrides Async Function TestAddEnum(code As XElement, expectedCode As XElement, data As EnumData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newEnum = fileCodeModel.AddEnum(data.Name, data.Position, data.Base, data.Access) Assert.NotNull(newEnum) Assert.Equal(data.Name, newEnum.Name) End Sub) End Function Protected Overrides Async Function TestAddFunction(code As XElement, expectedCode As XElement, data As FunctionData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestAddImport(code As XElement, expectedCode As XElement, data As ImportData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newImport = fileCodeModel.AddImport(data.Namespace, data.Position, data.Alias) Assert.NotNull(newImport) Assert.Equal(data.Namespace, newImport.Namespace) If data.Alias IsNot Nothing Then Assert.Equal(data.Alias, newImport.Alias) End If End Sub) End Function Protected Overrides Async Function TestAddInterface(code As XElement, expectedCode As XElement, data As InterfaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newInterface = fileCodeModel.AddInterface(data.Name, data.Position, data.Bases, data.Access) Assert.NotNull(newInterface) Assert.Equal(data.Name, newInterface.Name) End Sub) End Function Protected Overrides Async Function TestAddNamespace(code As XElement, expectedCode As XElement, data As NamespaceData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newNamespace = fileCodeModel.AddNamespace(data.Name, data.Position) Assert.NotNull(newNamespace) Assert.Equal(data.Name, newNamespace.Name) End Sub) End Function Protected Overrides Async Function TestAddStruct(code As XElement, expectedCode As XElement, data As StructData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Dim newStruct = fileCodeModel.AddStruct(data.Name, data.Position, data.Bases, data.ImplementedInterfaces, data.Access) Assert.NotNull(newStruct) Assert.Equal(data.Name, newStruct.Name) End Sub) End Function Protected Overrides Async Function TestAddVariable(code As XElement, expectedCode As XElement, data As VariableData) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) Assert.Throws(Of System.Runtime.InteropServices.COMException)( Sub() fileCodeModel.AddVariable(data.Name, data.Type, data.Position, data.Access) End Sub) End Sub) End Function Protected Overrides Async Function TestRemoveChild(code As XElement, expectedCode As XElement, element As Object) As Task Await TestOperation(code, expectedCode, Sub(fileCodeModel) fileCodeModel.Remove(element) End Sub) End Function End Class End Namespace
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/EnumCodeStyleOptionConfigurationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle { public abstract partial class EnumCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { /* /// <summary> /// Assignment preference for unused values from expression statements and assignments. /// </summary> internal enum UnusedValuePreference { // Unused values must be explicitly assigned to a local variable // that is never read/used. UnusedLocalVariable = 1, // Unused values must be explicitly assigned to a discard '_' variable. DiscardVariable = 2, } */ return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider()); } public class UnusedLocalVariableConfigurationTests : EnumCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 csharp_style_unused_value_assignment_preference = discard_variable:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = warning ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = warning ; Comment2 # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_ConflictingDotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = error ; Comment2 csharp_style_unused_value_assignment_preference = discard_variable:suggestion ; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = error ; Comment2 csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion ; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = discard_variable:suggestion [*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preferencer = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preferencer = discard_variable:suggestion # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class DiscardVariableConfigurationTests : EnumCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DiscardVariable_WithoutSeveritySuffix() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion [*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference_error = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference_error = discard_variable:suggestion # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle { public abstract partial class EnumCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { /* /// <summary> /// Assignment preference for unused values from expression statements and assignments. /// </summary> internal enum UnusedValuePreference { // Unused values must be explicitly assigned to a local variable // that is never read/used. UnusedLocalVariable = 1, // Unused values must be explicitly assigned to a discard '_' variable. DiscardVariable = 2, } */ return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider()); } public class UnusedLocalVariableConfigurationTests : EnumCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 csharp_style_unused_value_assignment_preference = discard_variable:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = warning ; Comment2 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = warning ; Comment2 # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_ConflictingDotnetDiagnosticEntry() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = error ; Comment2 csharp_style_unused_value_assignment_preference = discard_variable:suggestion ; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_diagnostic.IDE0059.severity = error ; Comment2 csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion ; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = discard_variable:suggestion [*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_UnusedLocalVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preferencer = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preferencer = discard_variable:suggestion # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class DiscardVariableConfigurationTests : EnumCodeStyleOptionConfigurationTests { protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_DiscardVariable_WithoutSeveritySuffix() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = unused_local_variable </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion [*.cs] # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainSeverity_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] csharp_style_unused_value_assignment_preference = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_DiscardVariable() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } [|var obj = new Program1();|] obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference_error = discard_variable:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // csharp_style_unused_value_assignment_preference = { discard_variable, unused_local_variable } var obj = new Program1(); obj = null; var obj2 = obj; } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_unused_value_assignment_preference_error = discard_variable:suggestion # IDE0059: Unnecessary assignment of a value csharp_style_unused_value_assignment_preference = discard_variable </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/EditorFeatures/VisualBasicTest/SignatureHelp/CastExpressionSignatureHelpProviderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class CastExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(CastExpressionSignatureHelpProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForCType() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = CType($$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"CType({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type, VBWorkspaceResources.The_expression_to_be_evaluated_and_converted, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForCTypeAfterComma() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = CType(bar, $$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"CType({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type, VBWorkspaceResources.The_name_of_the_data_type_to_which_the_value_of_expression_will_be_converted, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForDirectCast() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = DirectCast($$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"DirectCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type, VBWorkspaceResources.The_expression_to_be_evaluated_and_converted, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(530132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530132")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForTryCast() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = [|TryCast($$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"TryCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for, VBWorkspaceResources.The_expression_to_be_evaluated_and_converted, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class CastExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(CastExpressionSignatureHelpProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForCType() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = CType($$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"CType({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type, VBWorkspaceResources.The_expression_to_be_evaluated_and_converted, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForCTypeAfterComma() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = CType(bar, $$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"CType({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type, VBWorkspaceResources.The_name_of_the_data_type_to_which_the_value_of_expression_will_be_converted, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForDirectCast() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = DirectCast($$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"DirectCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type, VBWorkspaceResources.The_expression_to_be_evaluated_and_converted, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(530132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530132")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForTryCast() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = [|TryCast($$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"TryCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}", VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for, VBWorkspaceResources.The_expression_to_be_evaluated_and_converted, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function End Class End Namespace
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/BasicMoveTypeTestsBase.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.Xml.Linq Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeRefactorings.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Public Class BasicMoveTypeTestsBase Inherits AbstractMoveTypeTest Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overloads Function TestRenameTypeToMatchFileAsync( originalCode As XElement, Optional expectedCode As XElement = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Dim expectedText As String = Nothing If Not expectedCode Is Nothing Then expectedText = expectedCode.ConvertTestSourceTag() End If Return MyBase.TestRenameTypeToMatchFileAsync( originalCode.ConvertTestSourceTag(), expectedText, expectedCodeAction) End Function Protected Overloads Function TestRenameFileToMatchTypeAsync( originalCode As XElement, Optional expectedDocumentName As String = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Return MyBase.TestRenameFileToMatchTypeAsync( originalCode.ConvertTestSourceTag(), expectedDocumentName, expectedCodeAction) End Function Protected Overloads Function TestMoveTypeToNewFileAsync( originalCode As XElement, expectedSourceTextAfterRefactoring As XElement, expectedDocumentName As String, destinationDocumentText As XElement, Optional destinationDocumentContainers As ImmutableArray(Of String) = Nothing, Optional expectedCodeAction As Boolean = True, Optional index As Integer = 0 ) As Task Dim originalCodeText = originalCode.ConvertTestSourceTag() Dim expectedSourceText = expectedSourceTextAfterRefactoring.ConvertTestSourceTag() Dim expectedDestinationText = destinationDocumentText.ConvertTestSourceTag() Return MyBase.TestMoveTypeToNewFileAsync( originalCodeText, expectedSourceText, expectedDocumentName, expectedDestinationText, destinationDocumentContainers, expectedCodeAction, index) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeRefactorings.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.MoveType Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Public Class BasicMoveTypeTestsBase Inherits AbstractMoveTypeTest Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overloads Function TestRenameTypeToMatchFileAsync( originalCode As XElement, Optional expectedCode As XElement = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Dim expectedText As String = Nothing If Not expectedCode Is Nothing Then expectedText = expectedCode.ConvertTestSourceTag() End If Return MyBase.TestRenameTypeToMatchFileAsync( originalCode.ConvertTestSourceTag(), expectedText, expectedCodeAction) End Function Protected Overloads Function TestRenameFileToMatchTypeAsync( originalCode As XElement, Optional expectedDocumentName As String = Nothing, Optional expectedCodeAction As Boolean = True ) As Task Return MyBase.TestRenameFileToMatchTypeAsync( originalCode.ConvertTestSourceTag(), expectedDocumentName, expectedCodeAction) End Function Protected Overloads Function TestMoveTypeToNewFileAsync( originalCode As XElement, expectedSourceTextAfterRefactoring As XElement, expectedDocumentName As String, destinationDocumentText As XElement, Optional destinationDocumentContainers As ImmutableArray(Of String) = Nothing, Optional expectedCodeAction As Boolean = True, Optional index As Integer = 0 ) As Task Dim originalCodeText = originalCode.ConvertTestSourceTag() Dim expectedSourceText = expectedSourceTextAfterRefactoring.ConvertTestSourceTag() Dim expectedDestinationText = destinationDocumentText.ConvertTestSourceTag() Return MyBase.TestMoveTypeToNewFileAsync( originalCodeText, expectedSourceText, expectedDocumentName, expectedDestinationText, destinationDocumentContainers, expectedCodeAction, index) End Function End Class End Namespace
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/EditorFeatures/Test/Attributes/AttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Attributes { public class AttributeTests { #if false [WpfFact] public void CreateExportSyntaxTokenCodeIssueProviderAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTokenCodeIssueProviderAttribute("name", null)); Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTokenCodeIssueProviderAttribute(null, "language")); new ExportSyntaxTokenCodeIssueProviderAttribute("name", "language"); } [WpfFact] public void CreateExportSyntaxTriviaCodeIssueProviderAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTriviaCodeIssueProviderAttribute("name", null)); Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTriviaCodeIssueProviderAttribute(null, "language")); new ExportSyntaxTriviaCodeIssueProviderAttribute("name", "language"); } #endif [Fact] public void CreateExportBraceMatcherAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportBraceMatcherAttribute(null)); } [Fact] public void CreateExportCompletionProviderAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportCompletionProviderMef1Attribute("name", null)); Assert.Throws<ArgumentNullException>(() => new ExportCompletionProviderMef1Attribute(null, "language")); } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Attributes { public class AttributeTests { #if false [WpfFact] public void CreateExportSyntaxTokenCodeIssueProviderAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTokenCodeIssueProviderAttribute("name", null)); Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTokenCodeIssueProviderAttribute(null, "language")); new ExportSyntaxTokenCodeIssueProviderAttribute("name", "language"); } [WpfFact] public void CreateExportSyntaxTriviaCodeIssueProviderAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTriviaCodeIssueProviderAttribute("name", null)); Assert.Throws<ArgumentNullException>(() => new ExportSyntaxTriviaCodeIssueProviderAttribute(null, "language")); new ExportSyntaxTriviaCodeIssueProviderAttribute("name", "language"); } #endif [Fact] public void CreateExportBraceMatcherAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportBraceMatcherAttribute(null)); } [Fact] public void CreateExportCompletionProviderAttributeWithNullArg() { Assert.Throws<ArgumentNullException>(() => new ExportCompletionProviderMef1Attribute("name", null)); Assert.Throws<ArgumentNullException>(() => new ExportCompletionProviderMef1Attribute(null, "language")); } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisState.SyntaxReferenceAnalyzerStateData.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.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalysisState { /// <summary> /// Stores the partial analysis state for a specific symbol declaration for a specific analyzer. /// </summary> internal sealed class DeclarationAnalyzerStateData : SyntaxNodeAnalyzerStateData { /// <summary> /// Partial analysis state for code block actions executed on the declaration. /// </summary> public CodeBlockAnalyzerStateData CodeBlockAnalysisState { get; } /// <summary> /// Partial analysis state for operation block actions executed on the declaration. /// </summary> public OperationBlockAnalyzerStateData OperationBlockAnalysisState { get; } public static new readonly DeclarationAnalyzerStateData FullyProcessedInstance = CreateFullyProcessedInstance(); public DeclarationAnalyzerStateData() { CodeBlockAnalysisState = new CodeBlockAnalyzerStateData(); OperationBlockAnalysisState = new OperationBlockAnalyzerStateData(); } private static DeclarationAnalyzerStateData CreateFullyProcessedInstance() { var instance = new DeclarationAnalyzerStateData(); instance.SetStateKind(StateKind.FullyProcessed); return instance; } public override void SetStateKind(StateKind stateKind) { CodeBlockAnalysisState.SetStateKind(stateKind); OperationBlockAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); CodeBlockAnalysisState.Free(); OperationBlockAnalysisState.Free(); } } /// <summary> /// Stores the partial analysis state for syntax node actions executed on the declaration. /// </summary> internal class SyntaxNodeAnalyzerStateData : AnalyzerStateData { public HashSet<SyntaxNode> ProcessedNodes { get; } public SyntaxNode CurrentNode { get; set; } public SyntaxNodeAnalyzerStateData() { CurrentNode = null; ProcessedNodes = new HashSet<SyntaxNode>(); } public void ClearNodeAnalysisState() { CurrentNode = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentNode = null; ProcessedNodes.Clear(); } } /// <summary> /// Stores the partial analysis state for operation actions executed on the declaration. /// </summary> internal class OperationAnalyzerStateData : AnalyzerStateData { public HashSet<IOperation> ProcessedOperations { get; } public IOperation CurrentOperation { get; set; } public OperationAnalyzerStateData() { CurrentOperation = null; ProcessedOperations = new HashSet<IOperation>(); } public void ClearNodeAnalysisState() { CurrentOperation = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentOperation = null; ProcessedOperations.Clear(); } } /// <summary> /// Stores the partial analysis state for code block actions or operation block actions executed on the declaration. /// </summary> internal abstract class BlockAnalyzerStateData<TBlockAction, TNodeStateData> : AnalyzerStateData where TBlockAction : AnalyzerAction where TNodeStateData : AnalyzerStateData, new() { public TNodeStateData ExecutableNodesAnalysisState { get; } public ImmutableHashSet<TBlockAction> CurrentBlockEndActions { get; set; } public ImmutableHashSet<AnalyzerAction> CurrentBlockNodeActions { get; set; } public BlockAnalyzerStateData() { ExecutableNodesAnalysisState = new TNodeStateData(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } public override void SetStateKind(StateKind stateKind) { ExecutableNodesAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); ExecutableNodesAnalysisState.Free(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } } /// <summary> /// Stores the partial analysis state for code block actions executed on the declaration. /// </summary> internal sealed class CodeBlockAnalyzerStateData : BlockAnalyzerStateData<CodeBlockAnalyzerAction, SyntaxNodeAnalyzerStateData> { } /// <summary> /// Stores the partial analysis state for operation block actions executed on the declaration. /// </summary> internal sealed class OperationBlockAnalyzerStateData : BlockAnalyzerStateData<OperationBlockAnalyzerAction, OperationAnalyzerStateData> { } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalysisState { /// <summary> /// Stores the partial analysis state for a specific symbol declaration for a specific analyzer. /// </summary> internal sealed class DeclarationAnalyzerStateData : SyntaxNodeAnalyzerStateData { /// <summary> /// Partial analysis state for code block actions executed on the declaration. /// </summary> public CodeBlockAnalyzerStateData CodeBlockAnalysisState { get; } /// <summary> /// Partial analysis state for operation block actions executed on the declaration. /// </summary> public OperationBlockAnalyzerStateData OperationBlockAnalysisState { get; } public static new readonly DeclarationAnalyzerStateData FullyProcessedInstance = CreateFullyProcessedInstance(); public DeclarationAnalyzerStateData() { CodeBlockAnalysisState = new CodeBlockAnalyzerStateData(); OperationBlockAnalysisState = new OperationBlockAnalyzerStateData(); } private static DeclarationAnalyzerStateData CreateFullyProcessedInstance() { var instance = new DeclarationAnalyzerStateData(); instance.SetStateKind(StateKind.FullyProcessed); return instance; } public override void SetStateKind(StateKind stateKind) { CodeBlockAnalysisState.SetStateKind(stateKind); OperationBlockAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); CodeBlockAnalysisState.Free(); OperationBlockAnalysisState.Free(); } } /// <summary> /// Stores the partial analysis state for syntax node actions executed on the declaration. /// </summary> internal class SyntaxNodeAnalyzerStateData : AnalyzerStateData { public HashSet<SyntaxNode> ProcessedNodes { get; } public SyntaxNode CurrentNode { get; set; } public SyntaxNodeAnalyzerStateData() { CurrentNode = null; ProcessedNodes = new HashSet<SyntaxNode>(); } public void ClearNodeAnalysisState() { CurrentNode = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentNode = null; ProcessedNodes.Clear(); } } /// <summary> /// Stores the partial analysis state for operation actions executed on the declaration. /// </summary> internal class OperationAnalyzerStateData : AnalyzerStateData { public HashSet<IOperation> ProcessedOperations { get; } public IOperation CurrentOperation { get; set; } public OperationAnalyzerStateData() { CurrentOperation = null; ProcessedOperations = new HashSet<IOperation>(); } public void ClearNodeAnalysisState() { CurrentOperation = null; ProcessedActions.Clear(); } public override void Free() { base.Free(); CurrentOperation = null; ProcessedOperations.Clear(); } } /// <summary> /// Stores the partial analysis state for code block actions or operation block actions executed on the declaration. /// </summary> internal abstract class BlockAnalyzerStateData<TBlockAction, TNodeStateData> : AnalyzerStateData where TBlockAction : AnalyzerAction where TNodeStateData : AnalyzerStateData, new() { public TNodeStateData ExecutableNodesAnalysisState { get; } public ImmutableHashSet<TBlockAction> CurrentBlockEndActions { get; set; } public ImmutableHashSet<AnalyzerAction> CurrentBlockNodeActions { get; set; } public BlockAnalyzerStateData() { ExecutableNodesAnalysisState = new TNodeStateData(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } public override void SetStateKind(StateKind stateKind) { ExecutableNodesAnalysisState.SetStateKind(stateKind); base.SetStateKind(stateKind); } public override void Free() { base.Free(); ExecutableNodesAnalysisState.Free(); CurrentBlockEndActions = null; CurrentBlockNodeActions = null; } } /// <summary> /// Stores the partial analysis state for code block actions executed on the declaration. /// </summary> internal sealed class CodeBlockAnalyzerStateData : BlockAnalyzerStateData<CodeBlockAnalyzerAction, SyntaxNodeAnalyzerStateData> { } /// <summary> /// Stores the partial analysis state for operation block actions executed on the declaration. /// </summary> internal sealed class OperationBlockAnalyzerStateData : BlockAnalyzerStateData<OperationBlockAnalyzerAction, OperationAnalyzerStateData> { } } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Compilers/VisualBasic/Test/Emit/PDB/PDBVariableInitializerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBVariableInitializerTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartialClass() Dim source = <compilation> <file name="a.vb"> Option strict on imports system partial Class C1 public f1 as integer = 23 public f3 As New C1() public f4, f5 As New C1() Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub End Class </file> <file name="b.vb"> Option strict on imports system partial Class C1 ' more lines to see a different span in the sequence points ... public f2 as integer = 42 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="01-41-D1-CA-DD-B0-0B-39-BE-3C-3D-69-AA-18-B3-7A-F5-65-C5-DD"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="FE-FF-3A-FC-5E-54-7C-6D-96-86-05-B8-B6-FD-FC-5F-81-51-AE-FA"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="6" startColumn="12" endLine="6" endColumn="30" document="1"/> <entry offset="0xf" startLine="7" startColumn="12" endLine="7" endColumn="26" document="1"/> <entry offset="0x1a" startLine="8" startColumn="12" endLine="8" endColumn="14" document="1"/> <entry offset="0x25" startLine="8" startColumn="16" endLine="8" endColumn="18" document="1"/> <entry offset="0x30" startLine="11" startColumn="36" endLine="11" endColumn="54" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x39"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty1() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As Integer = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As Integer = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty2() Dim source = <compilation> <file> Interface I Property P As Object End Interface Class C Implements I Property P = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoPropertyAsNew() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As New Integer Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As New Integer".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedField() Dim source = <compilation> <file> Class C Dim F(1), G(2) As Integer End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedLocal() Dim source = <compilation> <file> Class C Sub M Dim F(1), G(2) As Integer End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewMultiInitializer() Dim source = <compilation> <file> Class C Dim F, G As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewMultiInitializer() Dim source = <compilation> <file> Class C Sub M Dim F, G As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewSingleInitializer() Dim source = <compilation> <file> Class C Dim F As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewSingleInitializer() Dim source = <compilation> <file> Class C Sub M Dim F As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldInitializer() Dim source = <compilation> <file> Class C Dim F = 1 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalInitializer() Dim source = <compilation> <file> Class C Sub M Dim F = 1 End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBVariableInitializerTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartialClass() Dim source = <compilation> <file name="a.vb"> Option strict on imports system partial Class C1 public f1 as integer = 23 public f3 As New C1() public f4, f5 As New C1() Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub End Class </file> <file name="b.vb"> Option strict on imports system partial Class C1 ' more lines to see a different span in the sequence points ... public f2 as integer = 42 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="01-41-D1-CA-DD-B0-0B-39-BE-3C-3D-69-AA-18-B3-7A-F5-65-C5-DD"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="FE-FF-3A-FC-5E-54-7C-6D-96-86-05-B8-B6-FD-FC-5F-81-51-AE-FA"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="6" startColumn="12" endLine="6" endColumn="30" document="1"/> <entry offset="0xf" startLine="7" startColumn="12" endLine="7" endColumn="26" document="1"/> <entry offset="0x1a" startLine="8" startColumn="12" endLine="8" endColumn="14" document="1"/> <entry offset="0x25" startLine="8" startColumn="16" endLine="8" endColumn="18" document="1"/> <entry offset="0x30" startLine="11" startColumn="36" endLine="11" endColumn="54" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x39"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty1() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As Integer = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As Integer = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty2() Dim source = <compilation> <file> Interface I Property P As Object End Interface Class C Implements I Property P = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoPropertyAsNew() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As New Integer Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As New Integer".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedField() Dim source = <compilation> <file> Class C Dim F(1), G(2) As Integer End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedLocal() Dim source = <compilation> <file> Class C Sub M Dim F(1), G(2) As Integer End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewMultiInitializer() Dim source = <compilation> <file> Class C Dim F, G As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewMultiInitializer() Dim source = <compilation> <file> Class C Sub M Dim F, G As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewSingleInitializer() Dim source = <compilation> <file> Class C Dim F As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewSingleInitializer() Dim source = <compilation> <file> Class C Sub M Dim F As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldInitializer() Dim source = <compilation> <file> Class C Dim F = 1 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalInitializer() Dim source = <compilation> <file> Class C Sub M Dim F = 1 End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub End Class End Namespace
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationPropertySymbol : CodeGenerationSymbol, IPropertySymbol { private readonly RefKind _refKind; public ITypeSymbol Type { get; } public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; public bool IsIndexer { get; } public ImmutableArray<IParameterSymbol> Parameters { get; } public ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get; } public IMethodSymbol GetMethod { get; } public IMethodSymbol SetMethod { get; } public CodeGenerationPropertySymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, ITypeSymbol type, RefKind refKind, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations, string name, bool isIndexer, ImmutableArray<IParameterSymbol> parametersOpt, IMethodSymbol getMethod, IMethodSymbol setMethod) : base(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name) { this.Type = type; _refKind = refKind; this.IsIndexer = isIndexer; this.Parameters = parametersOpt.NullToEmpty(); this.ExplicitInterfaceImplementations = explicitInterfaceImplementations.NullToEmpty(); this.GetMethod = getMethod; this.SetMethod = setMethod; } protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationPropertySymbol( this.ContainingType, this.GetAttributes(), this.DeclaredAccessibility, this.Modifiers, this.Type, this.RefKind, this.ExplicitInterfaceImplementations, this.Name, this.IsIndexer, this.Parameters, this.GetMethod, this.SetMethod); CodeGenerationPropertyInfo.Attach(result, CodeGenerationPropertyInfo.GetIsNew(this), CodeGenerationPropertyInfo.GetIsUnsafe(this), CodeGenerationPropertyInfo.GetInitializer(this)); return result; } public override SymbolKind Kind => SymbolKind.Property; public override void Accept(SymbolVisitor visitor) => visitor.VisitProperty(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitProperty(this); public bool IsReadOnly => this.GetMethod != null && this.SetMethod == null; public bool IsWriteOnly => this.GetMethod == null && this.SetMethod != null; public new IPropertySymbol OriginalDefinition => this; public RefKind RefKind => _refKind; public bool ReturnsByRef => _refKind == RefKind.Ref; public bool ReturnsByRefReadonly => _refKind == RefKind.RefReadOnly; public IPropertySymbol OverriddenProperty => null; public bool IsWithEvents => false; public ImmutableArray<CustomModifier> RefCustomModifiers => ImmutableArray<CustomModifier>.Empty; public ImmutableArray<CustomModifier> TypeCustomModifiers => ImmutableArray<CustomModifier>.Empty; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationPropertySymbol : CodeGenerationSymbol, IPropertySymbol { private readonly RefKind _refKind; public ITypeSymbol Type { get; } public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; public bool IsIndexer { get; } public ImmutableArray<IParameterSymbol> Parameters { get; } public ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get; } public IMethodSymbol GetMethod { get; } public IMethodSymbol SetMethod { get; } public CodeGenerationPropertySymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, ITypeSymbol type, RefKind refKind, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations, string name, bool isIndexer, ImmutableArray<IParameterSymbol> parametersOpt, IMethodSymbol getMethod, IMethodSymbol setMethod) : base(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name) { this.Type = type; _refKind = refKind; this.IsIndexer = isIndexer; this.Parameters = parametersOpt.NullToEmpty(); this.ExplicitInterfaceImplementations = explicitInterfaceImplementations.NullToEmpty(); this.GetMethod = getMethod; this.SetMethod = setMethod; } protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationPropertySymbol( this.ContainingType, this.GetAttributes(), this.DeclaredAccessibility, this.Modifiers, this.Type, this.RefKind, this.ExplicitInterfaceImplementations, this.Name, this.IsIndexer, this.Parameters, this.GetMethod, this.SetMethod); CodeGenerationPropertyInfo.Attach(result, CodeGenerationPropertyInfo.GetIsNew(this), CodeGenerationPropertyInfo.GetIsUnsafe(this), CodeGenerationPropertyInfo.GetInitializer(this)); return result; } public override SymbolKind Kind => SymbolKind.Property; public override void Accept(SymbolVisitor visitor) => visitor.VisitProperty(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitProperty(this); public bool IsReadOnly => this.GetMethod != null && this.SetMethod == null; public bool IsWriteOnly => this.GetMethod == null && this.SetMethod != null; public new IPropertySymbol OriginalDefinition => this; public RefKind RefKind => _refKind; public bool ReturnsByRef => _refKind == RefKind.Ref; public bool ReturnsByRefReadonly => _refKind == RefKind.RefReadOnly; public IPropertySymbol OverriddenProperty => null; public bool IsWithEvents => false; public ImmutableArray<CustomModifier> RefCustomModifiers => ImmutableArray<CustomModifier>.Empty; public ImmutableArray<CustomModifier> TypeCustomModifiers => ImmutableArray<CustomModifier>.Empty; } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Features/CSharp/Portable/ConvertAutoPropertyToFullProperty/CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.ConvertAutoPropertyToFullProperty; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertAutoPropertyToFullProperty), Shared] internal class CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider : AbstractConvertAutoPropertyToFullPropertyCodeRefactoringProvider<PropertyDeclarationSyntax, TypeDeclarationSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider() { } internal override async Task<string> GetFieldNameAsync(Document document, IPropertySymbol property, CancellationToken cancellationToken) { var rule = await document.GetApplicableNamingRuleAsync( new SymbolKindOrTypeKind(SymbolKind.Field), property.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None, Accessibility.Private, cancellationToken).ConfigureAwait(false); var fieldName = rule.NamingStyle.MakeCompliant(property.Name).First(); return NameGenerator.GenerateUniqueName(fieldName, n => !property.ContainingType.GetMembers(n).Any()); } internal override (SyntaxNode newGetAccessor, SyntaxNode newSetAccessor) GetNewAccessors( DocumentOptionSet options, SyntaxNode property, string fieldName, SyntaxGenerator generator) { // C# might have trivia with the accessors that needs to be preserved. // so we will update the existing accessors instead of creating new ones var accessorListSyntax = ((PropertyDeclarationSyntax)property).AccessorList; var (getAccessor, setAccessor) = GetExistingAccessors(accessorListSyntax); var getAccessorStatement = generator.ReturnStatement(generator.IdentifierName(fieldName)); var newGetter = GetUpdatedAccessor(options, getAccessor, getAccessorStatement); SyntaxNode newSetter = null; if (setAccessor != null) { var setAccessorStatement = generator.ExpressionStatement(generator.AssignmentStatement( generator.IdentifierName(fieldName), generator.IdentifierName("value"))); newSetter = GetUpdatedAccessor(options, setAccessor, setAccessorStatement); } return (newGetAccessor: newGetter, newSetAccessor: newSetter); } private static (AccessorDeclarationSyntax getAccessor, AccessorDeclarationSyntax setAccessor) GetExistingAccessors(AccessorListSyntax accessorListSyntax) => (accessorListSyntax.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.GetAccessorDeclaration)), accessorListSyntax.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.SetAccessorDeclaration) || a.IsKind(SyntaxKind.InitAccessorDeclaration))); private static SyntaxNode GetUpdatedAccessor(DocumentOptionSet options, SyntaxNode accessor, SyntaxNode statement) { var newAccessor = AddStatement(accessor, statement); var accessorDeclarationSyntax = (AccessorDeclarationSyntax)newAccessor; var preference = GetAccessorExpressionBodyPreference(options); if (preference == ExpressionBodyPreference.Never) { return accessorDeclarationSyntax.WithSemicolonToken(default); } if (!accessorDeclarationSyntax.Body.TryConvertToArrowExpressionBody( accessorDeclarationSyntax.Kind(), accessor.SyntaxTree.Options, preference, out var arrowExpression, out _)) { return accessorDeclarationSyntax.WithSemicolonToken(default); } return accessorDeclarationSyntax .WithExpressionBody(arrowExpression) .WithBody(null) .WithSemicolonToken(accessorDeclarationSyntax.SemicolonToken) .WithAdditionalAnnotations(Formatter.Annotation); } internal static SyntaxNode AddStatement(SyntaxNode accessor, SyntaxNode statement) { var blockSyntax = SyntaxFactory.Block( SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed), new SyntaxList<StatementSyntax>((StatementSyntax)statement), SyntaxFactory.Token(SyntaxKind.CloseBraceToken) .WithTrailingTrivia(((AccessorDeclarationSyntax)accessor).SemicolonToken.TrailingTrivia)); return ((AccessorDeclarationSyntax)accessor).WithBody(blockSyntax); } internal override SyntaxNode ConvertPropertyToExpressionBodyIfDesired( DocumentOptionSet options, SyntaxNode property) { var propertyDeclaration = (PropertyDeclarationSyntax)property; var preference = GetPropertyExpressionBodyPreference(options); if (preference == ExpressionBodyPreference.Never) { return propertyDeclaration.WithSemicolonToken(default); } // if there is a get accessors only, we can move the expression body to the property if (propertyDeclaration.AccessorList?.Accessors.Count == 1 && propertyDeclaration.AccessorList.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration) { var getAccessor = propertyDeclaration.AccessorList.Accessors[0]; if (getAccessor.ExpressionBody != null) { return propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody) .WithSemicolonToken(getAccessor.SemicolonToken) .WithAccessorList(null); } } return propertyDeclaration.WithSemicolonToken(default); } internal static ExpressionBodyPreference GetAccessorExpressionBodyPreference(DocumentOptionSet options) => options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value; internal static ExpressionBodyPreference GetPropertyExpressionBodyPreference(DocumentOptionSet options) => options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value; internal override SyntaxNode GetTypeBlock(SyntaxNode syntaxNode) => syntaxNode; internal override SyntaxNode GetInitializerValue(SyntaxNode property) => ((PropertyDeclarationSyntax)property).Initializer?.Value; internal override SyntaxNode GetPropertyWithoutInitializer(SyntaxNode property) => ((PropertyDeclarationSyntax)property).WithInitializer(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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.ConvertAutoPropertyToFullProperty; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertAutoPropertyToFullProperty), Shared] internal class CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider : AbstractConvertAutoPropertyToFullPropertyCodeRefactoringProvider<PropertyDeclarationSyntax, TypeDeclarationSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider() { } internal override async Task<string> GetFieldNameAsync(Document document, IPropertySymbol property, CancellationToken cancellationToken) { var rule = await document.GetApplicableNamingRuleAsync( new SymbolKindOrTypeKind(SymbolKind.Field), property.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None, Accessibility.Private, cancellationToken).ConfigureAwait(false); var fieldName = rule.NamingStyle.MakeCompliant(property.Name).First(); return NameGenerator.GenerateUniqueName(fieldName, n => !property.ContainingType.GetMembers(n).Any()); } internal override (SyntaxNode newGetAccessor, SyntaxNode newSetAccessor) GetNewAccessors( DocumentOptionSet options, SyntaxNode property, string fieldName, SyntaxGenerator generator) { // C# might have trivia with the accessors that needs to be preserved. // so we will update the existing accessors instead of creating new ones var accessorListSyntax = ((PropertyDeclarationSyntax)property).AccessorList; var (getAccessor, setAccessor) = GetExistingAccessors(accessorListSyntax); var getAccessorStatement = generator.ReturnStatement(generator.IdentifierName(fieldName)); var newGetter = GetUpdatedAccessor(options, getAccessor, getAccessorStatement); SyntaxNode newSetter = null; if (setAccessor != null) { var setAccessorStatement = generator.ExpressionStatement(generator.AssignmentStatement( generator.IdentifierName(fieldName), generator.IdentifierName("value"))); newSetter = GetUpdatedAccessor(options, setAccessor, setAccessorStatement); } return (newGetAccessor: newGetter, newSetAccessor: newSetter); } private static (AccessorDeclarationSyntax getAccessor, AccessorDeclarationSyntax setAccessor) GetExistingAccessors(AccessorListSyntax accessorListSyntax) => (accessorListSyntax.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.GetAccessorDeclaration)), accessorListSyntax.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.SetAccessorDeclaration) || a.IsKind(SyntaxKind.InitAccessorDeclaration))); private static SyntaxNode GetUpdatedAccessor(DocumentOptionSet options, SyntaxNode accessor, SyntaxNode statement) { var newAccessor = AddStatement(accessor, statement); var accessorDeclarationSyntax = (AccessorDeclarationSyntax)newAccessor; var preference = GetAccessorExpressionBodyPreference(options); if (preference == ExpressionBodyPreference.Never) { return accessorDeclarationSyntax.WithSemicolonToken(default); } if (!accessorDeclarationSyntax.Body.TryConvertToArrowExpressionBody( accessorDeclarationSyntax.Kind(), accessor.SyntaxTree.Options, preference, out var arrowExpression, out _)) { return accessorDeclarationSyntax.WithSemicolonToken(default); } return accessorDeclarationSyntax .WithExpressionBody(arrowExpression) .WithBody(null) .WithSemicolonToken(accessorDeclarationSyntax.SemicolonToken) .WithAdditionalAnnotations(Formatter.Annotation); } internal static SyntaxNode AddStatement(SyntaxNode accessor, SyntaxNode statement) { var blockSyntax = SyntaxFactory.Block( SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed), new SyntaxList<StatementSyntax>((StatementSyntax)statement), SyntaxFactory.Token(SyntaxKind.CloseBraceToken) .WithTrailingTrivia(((AccessorDeclarationSyntax)accessor).SemicolonToken.TrailingTrivia)); return ((AccessorDeclarationSyntax)accessor).WithBody(blockSyntax); } internal override SyntaxNode ConvertPropertyToExpressionBodyIfDesired( DocumentOptionSet options, SyntaxNode property) { var propertyDeclaration = (PropertyDeclarationSyntax)property; var preference = GetPropertyExpressionBodyPreference(options); if (preference == ExpressionBodyPreference.Never) { return propertyDeclaration.WithSemicolonToken(default); } // if there is a get accessors only, we can move the expression body to the property if (propertyDeclaration.AccessorList?.Accessors.Count == 1 && propertyDeclaration.AccessorList.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration) { var getAccessor = propertyDeclaration.AccessorList.Accessors[0]; if (getAccessor.ExpressionBody != null) { return propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody) .WithSemicolonToken(getAccessor.SemicolonToken) .WithAccessorList(null); } } return propertyDeclaration.WithSemicolonToken(default); } internal static ExpressionBodyPreference GetAccessorExpressionBodyPreference(DocumentOptionSet options) => options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value; internal static ExpressionBodyPreference GetPropertyExpressionBodyPreference(DocumentOptionSet options) => options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value; internal override SyntaxNode GetTypeBlock(SyntaxNode syntaxNode) => syntaxNode; internal override SyntaxNode GetInitializerValue(SyntaxNode property) => ((PropertyDeclarationSyntax)property).Initializer?.Value; internal override SyntaxNode GetPropertyWithoutInitializer(SyntaxNode property) => ((PropertyDeclarationSyntax)property).WithInitializer(null); } }
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/CrossRefModule1.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. Public Class M1 End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Public Class M1 End Class
-1
dotnet/roslyn
56,545
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.
Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
AlekseyTs
"2021-09-20T16:15:00Z"
"2021-09-20T23:24:24Z"
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
c74bb2f2653fe6767af8fed3e63c293cc7747dd3
Separate the process of performing nullable analysis on attribute applications from the process of filling the attribute bag with data.. Fixes #47125. The second commit contains only renames, it might be simpler to review it separately.
./src/Compilers/VisualBasic/Portable/Locations/EmbeddedTreeLocation.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> ''' A program location in source code. ''' </summary> Friend NotInheritable Class EmbeddedTreeLocation Inherits VBLocation Friend ReadOnly _embeddedKind As EmbeddedSymbolKind Friend ReadOnly _span As TextSpan Public Overrides ReadOnly Property Kind As LocationKind Get Return LocationKind.None End Get End Property Friend Overrides ReadOnly Property EmbeddedKind As EmbeddedSymbolKind Get Return _embeddedKind End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceSpan As TextSpan Get Return _span End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceTree As SyntaxTree Get Return EmbeddedSymbolManager.GetEmbeddedTree(Me._embeddedKind) End Get End Property Public Sub New(embeddedKind As EmbeddedSymbolKind, span As TextSpan) Debug.Assert(embeddedKind = EmbeddedSymbolKind.VbCore OrElse embeddedKind = EmbeddedSymbolKind.XmlHelper OrElse embeddedKind = EmbeddedSymbolKind.EmbeddedAttribute) _embeddedKind = embeddedKind _span = span End Sub Public Overloads Function Equals(other As EmbeddedTreeLocation) As Boolean If Me Is other Then Return True End If Return other IsNot Nothing AndAlso other.EmbeddedKind = Me._embeddedKind AndAlso other._span.Equals(Me._span) End Function Public Overloads Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, EmbeddedTreeLocation)) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(CInt(_embeddedKind).GetHashCode(), _span.GetHashCode()) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A program location in source code. ''' </summary> Friend NotInheritable Class EmbeddedTreeLocation Inherits VBLocation Friend ReadOnly _embeddedKind As EmbeddedSymbolKind Friend ReadOnly _span As TextSpan Public Overrides ReadOnly Property Kind As LocationKind Get Return LocationKind.None End Get End Property Friend Overrides ReadOnly Property EmbeddedKind As EmbeddedSymbolKind Get Return _embeddedKind End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceSpan As TextSpan Get Return _span End Get End Property Friend Overrides ReadOnly Property PossiblyEmbeddedOrMySourceTree As SyntaxTree Get Return EmbeddedSymbolManager.GetEmbeddedTree(Me._embeddedKind) End Get End Property Public Sub New(embeddedKind As EmbeddedSymbolKind, span As TextSpan) Debug.Assert(embeddedKind = EmbeddedSymbolKind.VbCore OrElse embeddedKind = EmbeddedSymbolKind.XmlHelper OrElse embeddedKind = EmbeddedSymbolKind.EmbeddedAttribute) _embeddedKind = embeddedKind _span = span End Sub Public Overloads Function Equals(other As EmbeddedTreeLocation) As Boolean If Me Is other Then Return True End If Return other IsNot Nothing AndAlso other.EmbeddedKind = Me._embeddedKind AndAlso other._span.Equals(Me._span) End Function Public Overloads Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, EmbeddedTreeLocation)) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(CInt(_embeddedKind).GetHashCode(), _span.GetHashCode()) End Function End Class End Namespace
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.GetTypeOrFunctionType(); //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.GetTypeOrFunctionType() == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (source is FunctionTypeSymbol functionType) { return HasImplicitFunctionTypeConversion(functionType, destination, ref useSiteInfo) ? Conversion.FunctionType : Conversion.NoConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } #nullable enable /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if (d is null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } #nullable disable private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.GetTypeOrFunctionType() == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: case BoundKind.BinaryOperator when ((BoundBinaryOperator)sourceExpression).IsUnconvertedInterpolatedStringAddition: Conversion interpolatedStringConversion = GetInterpolatedStringConversion(sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } var sourceType = sourceExpression.GetTypeOrFunctionType(); if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if ((object)invokeMethod == null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsExpressionTree()); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (!delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } internal bool IsAssignableFromMulticastDelegate(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var multicastDelegateType = corLibrary.GetSpecialType(SpecialType.System_MulticastDelegate); multicastDelegateType.AddUseSiteInfo(ref useSiteInfo); return ClassifyImplicitConversionFromType(multicastDelegateType, type, ref useSiteInfo).Exists; } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsExpressionTree()) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } return LambdaConversionResult.BadTargetType; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } #nullable enable internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var s = source as ArrayTypeSymbol; if (s is null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitFunctionTypeConversion(FunctionTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination is FunctionTypeSymbol destinationFunctionType) { return HasImplicitSignatureConversion(source, destinationFunctionType, ref useSiteInfo); } return IsValidFunctionTypeConversionTarget(destination, ref useSiteInfo); } internal bool IsValidFunctionTypeConversionTarget(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (destination.IsNonGenericExpressionType()) { return true; } var derivedType = this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate); if (IsBaseClass(derivedType, destination, ref useSiteInfo) || IsBaseInterface(destination, derivedType, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitSignatureConversion(FunctionTypeSymbol sourceType, FunctionTypeSymbol destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var sourceDelegate = sourceType.GetInternalDelegateType(); var destinationDelegate = destinationType.GetInternalDelegateType(); // https://github.com/dotnet/roslyn/issues/55909: We're relying on the variance of // FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. return HasDelegateVarianceConversion(sourceDelegate, destinationDelegate, ref useSiteInfo); } #nullable disable public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.GetTypeOrFunctionType(); //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.GetTypeOrFunctionType() == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (source is FunctionTypeSymbol functionType) { return HasImplicitFunctionTypeConversion(functionType, destination, ref useSiteInfo) ? Conversion.FunctionType : Conversion.NoConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } #nullable enable /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if (d is null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } #nullable disable private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.GetTypeOrFunctionType() == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: case BoundKind.BinaryOperator when ((BoundBinaryOperator)sourceExpression).IsUnconvertedInterpolatedStringAddition: Conversion interpolatedStringConversion = GetInterpolatedStringConversion(sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } var sourceType = sourceExpression.GetTypeOrFunctionType(); if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if (invokeMethod is null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsExpressionTree()); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (!delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } internal bool IsAssignableFromMulticastDelegate(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var multicastDelegateType = corLibrary.GetSpecialType(SpecialType.System_MulticastDelegate); multicastDelegateType.AddUseSiteInfo(ref useSiteInfo); return ClassifyImplicitConversionFromType(multicastDelegateType, type, ref useSiteInfo).Exists; } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsExpressionTree()) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } return LambdaConversionResult.BadTargetType; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } #nullable enable internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var s = source as ArrayTypeSymbol; if (s is null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitFunctionTypeConversion(FunctionTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination is FunctionTypeSymbol destinationFunctionType) { return HasImplicitSignatureConversion(source, destinationFunctionType, ref useSiteInfo); } return IsValidFunctionTypeConversionTarget(destination, ref useSiteInfo); } internal bool IsValidFunctionTypeConversionTarget(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (destination.IsNonGenericExpressionType()) { return true; } var derivedType = this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate); if (IsBaseClass(derivedType, destination, ref useSiteInfo) || IsBaseInterface(destination, derivedType, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitSignatureConversion(FunctionTypeSymbol sourceType, FunctionTypeSymbol destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var sourceDelegate = sourceType.GetInternalDelegateType(); var destinationDelegate = destinationType.GetInternalDelegateType(); // https://github.com/dotnet/roslyn/issues/55909: We're relying on the variance of // FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. return HasDelegateVarianceConversion(sourceDelegate, destinationDelegate, ref useSiteInfo); } #nullable disable public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal readonly struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; /// <summary> /// At least one type argument was inferred from a function type. /// </summary> public readonly bool HasTypeArgumentInferredFromFunctionType; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments, bool hasTypeArgumentInferredFromFunctionType) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; this.HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly (TypeWithAnnotations Type, bool FromFunctionType)[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/nullable-reference-types-specification.md#fixing // If the resulting candidate is a reference type and *all* of the exact bounds or *any* of // the lower bounds are nullable reference types, `null` or `default`, then `?` is added to // the resulting candidate, making it a nullable reference type. // // This set of bounds effectively tracks whether a typeless null expression (i.e. null // literal) was used as an argument to a parameter whose type is one of this method's type // parameters. Because such expressions only occur as by-value inputs, we only need to track // the lower bounds, not the exact or upper bounds. private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(success: false, inferredTypeArguments: default, hasTypeArgumentInferredFromFunctionType: false); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new (TypeWithAnnotations, bool)[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; Debug.Assert(_nullableAnnotationLowerBounds.All(annotation => annotation.IsNotAnnotated())); _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i].Type; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults(out bool inferredFromFunctionType) { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { var fixedResultType = _fixedResults[i].Type; if (fixedResultType.HasType) { if (!fixedResultType.Type.IsErrorType()) { if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) { _fixedResults[i] = _fixedResults[i] with { Type = fixedResultType.AsAnnotated() }; } continue; } var errorTypeName = fixedResultType.Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = (TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)), false); } return GetInferredTypeArguments(out inferredFromFunctionType); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].Type.HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = _methodTypeParameters.SelectAsArray( static (typeParameter, i, self) => self.IsUnfixed(i) ? TypeWithAnnotations.Create(typeParameter) : self._fixedResults[i].Type, this); TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); var inferredTypeArguments = GetResults(out bool inferredFromFunctionType); return new MethodTypeInferenceResult(success, inferredTypeArguments, inferredFromFunctionType); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, an explicit type parameter // SPEC: inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.GetTypeOrFunctionType())) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } else if (IsUnfixedTypeParameter(target) && kind is ExactOrBoundsKind.LowerBound) { var ordinal = ((TypeParameterSymbol)target.Type).Ordinal; var typeWithAnnotations = _extensions.GetTypeWithAnnotations(argument); _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(typeWithAnnotations.NullableAnnotation); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.Type.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo).Type; // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static (TypeWithAnnotations Type, bool FromFunctionType) Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Upper bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); bool fromFunctionType = false; if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); fromFunctionType = true; } return (best, fromFunctionType); static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(out _); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments(out bool inferredFromFunctionType) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_fixedResults.Length); inferredFromFunctionType = false; foreach (var fixedResult in _fixedResults) { builder.Add(fixedResult.Type); if (fixedResult.FromFunctionType) { inferredFromFunctionType = true; } } return builder.ToImmutableAndFree(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal readonly struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; /// <summary> /// At least one type argument was inferred from a function type. /// </summary> public readonly bool HasTypeArgumentInferredFromFunctionType; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments, bool hasTypeArgumentInferredFromFunctionType) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; this.HasTypeArgumentInferredFromFunctionType = hasTypeArgumentInferredFromFunctionType; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly (TypeWithAnnotations Type, bool FromFunctionType)[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/nullable-reference-types-specification.md#fixing // If the resulting candidate is a reference type and *all* of the exact bounds or *any* of // the lower bounds are nullable reference types, `null` or `default`, then `?` is added to // the resulting candidate, making it a nullable reference type. // // This set of bounds effectively tracks whether a typeless null expression (i.e. null // literal) was used as an argument to a parameter whose type is one of this method's type // parameters. Because such expressions only occur as by-value inputs, we only need to track // the lower bounds, not the exact or upper bounds. private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(success: false, inferredTypeArguments: default, hasTypeArgumentInferredFromFunctionType: false); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new (TypeWithAnnotations, bool)[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; Debug.Assert(_nullableAnnotationLowerBounds.All(annotation => annotation.IsNotAnnotated())); _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i].Type; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults(out bool inferredFromFunctionType) { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { var fixedResultType = _fixedResults[i].Type; if (fixedResultType.HasType) { if (!fixedResultType.Type.IsErrorType()) { if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) { _fixedResults[i] = _fixedResults[i] with { Type = fixedResultType.AsAnnotated() }; } continue; } var errorTypeName = fixedResultType.Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = (TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)), false); } return GetInferredTypeArguments(out inferredFromFunctionType); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].Type.HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = _methodTypeParameters.SelectAsArray( static (typeParameter, i, self) => self.IsUnfixed(i) ? TypeWithAnnotations.Create(typeParameter) : self._fixedResults[i].Type, this); TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); var inferredTypeArguments = GetResults(out bool inferredFromFunctionType); return new MethodTypeInferenceResult(success, inferredTypeArguments, inferredFromFunctionType); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, and Ti is a delegate type or expression tree type, // SPEC: an explicit type parameter inference is made from Ei to Ti and // SPEC: an explicit return type inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); ExplicitReturnTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.GetTypeOrFunctionType())) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } else if (IsUnfixedTypeParameter(target) && kind is ExactOrBoundsKind.LowerBound) { var ordinal = ((TypeParameterSymbol)target.Type).Ordinal; var typeWithAnnotations = _extensions.GetTypeWithAnnotations(argument); _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(typeWithAnnotations.NullableAnnotation); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } #nullable enable //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if (delegateType is null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } private void ExplicitReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type return type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an anonymous function with explicit return type Ur and // SPEC: T is a delegate type or expression tree type with return type Vr then // SPEC: an exact inference is made from Ur to Vr. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitReturnType(out _, out TypeWithAnnotations anonymousFunctionReturnType)) { return; } var delegateInvokeMethod = target.Type.GetDelegateType()?.DelegateInvokeMethod(); if (delegateInvokeMethod is null) { return; } ExactInference(anonymousFunctionReturnType, delegateInvokeMethod.ReturnTypeWithAnnotations, ref useSiteInfo); } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.Type.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo).Type; // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static (TypeWithAnnotations Type, bool FromFunctionType) Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Upper bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); bool fromFunctionType = false; if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); fromFunctionType = true; } return (best, fromFunctionType); static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(out _); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments(out bool inferredFromFunctionType) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(_fixedResults.Length); inferredFromFunctionType = false; foreach (var fixedResult in _fixedResults) { builder.Add(fixedResult.Type); if (fixedResult.FromFunctionType) { inferredFromFunctionType = true; } } return builder.ToImmutableAndFree(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.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.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.NullableAnalysisData is { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(returnStatement.Syntax, pendingReturn.State); enforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // We don't use a default initial state for value type instance constructors without `: this()` because // any usages of uninitialized fields will get definite assignment errors anyway. if (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } void enforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } void reportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } } void enforceNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.NullableAnalysisData?.Data is { } state) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || nodeType!.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState(overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = delegateOrMethod.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, boundObjectCreationExpression!.ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(resultTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol? asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); } // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue splitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } void splitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { SetNotNullResult(node); } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed conditional or switch. Debug.Assert(argumentNoConversion is not (BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) && _conditionalInfoForConversionOpt?.ContainsKey(argumentNoConversion) is null or false); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull); } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (!notNullWhenTrueMembers.IsEmpty || !notNullWhenFalseMembers.IsEmpty) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } break; case RefKind.Out: break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment learnFromPostConditions(argument, parameterType, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return resultType; } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int GetArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda.UnboundLambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (operandType.Type?.IsErrorType() != true && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(null, operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object) { method = CheckMethodGroupReceiverNullability(group, delegateType.DelegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, argType.DelegateInvokeMethod(), invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => getFieldAnnotations(field.FieldSymbol), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.UnderlyingConversions, right); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var underlyingConversion = conversion.UnderlyingConversions[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand); } } break; } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.OperandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, node.OperandConversion, targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, node.ResultConversion, operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, node.LeftConversion, TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, node.FinalConversion, leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.ConsiderEverything2)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (node.Conversion.Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if (!@event.IsStatic) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Nullability flow analysis. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed partial class NullableWalker : LocalDataFlowPass<NullableWalker.LocalState, NullableWalker.LocalFunctionState> { /// <summary> /// Used to copy variable slots and types from the NullableWalker for the containing method /// or lambda to the NullableWalker created for a nested lambda or local function. /// </summary> internal sealed class VariableState { // Consider referencing the Variables instance directly from the original NullableWalker // rather than cloning. (Items are added to the collections but never replaced so the // collections are lazily populated but otherwise immutable. We'd probably want a // clone when analyzing from speculative semantic model though.) internal readonly VariablesSnapshot Variables; // The nullable state of all variables captured at the point where the function or lambda appeared. internal readonly LocalStateSnapshot VariableNullableStates; internal VariableState(VariablesSnapshot variables, LocalStateSnapshot variableNullableStates) { Variables = variables; VariableNullableStates = variableNullableStates; } } /// <summary> /// Data recorded for a particular analysis run. /// </summary> internal readonly struct Data { /// <summary> /// Number of entries tracked during analysis. /// </summary> internal readonly int TrackedEntries; /// <summary> /// True if analysis was required; false if analysis was optional and results dropped. /// </summary> internal readonly bool RequiredAnalysis; internal Data(int trackedEntries, bool requiredAnalysis) { TrackedEntries = trackedEntries; RequiredAnalysis = requiredAnalysis; } } /// <summary> /// Represents the result of visiting an expression. /// Contains a result type which tells us whether the expression may be null, /// and an l-value type which tells us whether we can assign null to the expression. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private readonly struct VisitResult { public readonly TypeWithState RValueType; public readonly TypeWithAnnotations LValueType; public VisitResult(TypeWithState rValueType, TypeWithAnnotations lValueType) { RValueType = rValueType; LValueType = lValueType; // https://github.com/dotnet/roslyn/issues/34993: Doesn't hold true for Tuple_Assignment_10. See if we can make it hold true //Debug.Assert((RValueType.Type is null && LValueType.TypeSymbol is null) || // RValueType.Type.Equals(LValueType.TypeSymbol, TypeCompareKind.ConsiderEverything | TypeCompareKind.AllIgnoreOptions)); } public VisitResult(TypeSymbol? type, NullableAnnotation annotation, NullableFlowState state) { RValueType = TypeWithState.Create(type, state); LValueType = TypeWithAnnotations.Create(type, annotation); Debug.Assert(TypeSymbol.Equals(RValueType.Type, LValueType.Type, TypeCompareKind.ConsiderEverything)); } internal string GetDebuggerDisplay() => $"{{LValue: {LValueType.GetDebuggerDisplay()}, RValue: {RValueType.GetDebuggerDisplay()}}}"; } /// <summary> /// Represents the result of visiting an argument expression. /// In addition to storing the <see cref="VisitResult"/>, also stores the <see cref="LocalState"/> /// for reanalyzing a lambda. /// </summary> [DebuggerDisplay("{VisitResult.GetDebuggerDisplay(), nq}")] private readonly struct VisitArgumentResult { public readonly VisitResult VisitResult; public readonly Optional<LocalState> StateForLambda; public TypeWithState RValueType => VisitResult.RValueType; public TypeWithAnnotations LValueType => VisitResult.LValueType; public VisitArgumentResult(VisitResult visitResult, Optional<LocalState> stateForLambda) { VisitResult = visitResult; StateForLambda = stateForLambda; } } private Variables _variables; /// <summary> /// Binder for symbol being analyzed. /// </summary> private readonly Binder _binder; /// <summary> /// Conversions with nullability and unknown matching any. /// </summary> private readonly Conversions _conversions; /// <summary> /// 'true' if non-nullable member warnings should be issued at return points. /// One situation where this is 'false' is when we are analyzing field initializers and there is a constructor symbol in the type. /// </summary> private readonly bool _useConstructorExitWarnings; /// <summary> /// If true, the parameter types and nullability from _delegateInvokeMethod is used for /// initial parameter state. If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeParameterTypes; /// <summary> /// If true, the return type and nullability from _delegateInvokeMethod is used. /// If false, the signature of CurrentSymbol is used instead. /// </summary> private bool _useDelegateInvokeReturnType; /// <summary> /// Method signature used for return or parameter types. Distinct from CurrentSymbol signature /// when CurrentSymbol is a lambda and type is inferred from MethodTypeInferrer. /// </summary> private MethodSymbol? _delegateInvokeMethod; /// <summary> /// Return statements and the result types from analyzing the returned expressions. Used when inferring lambda return type in MethodTypeInferrer. /// </summary> private ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? _returnTypesOpt; /// <summary> /// Invalid type, used only to catch Visit methods that do not set /// _result.Type. See VisitExpressionWithoutStackGuard. /// </summary> private static readonly TypeWithState _invalidType = TypeWithState.Create(ErrorTypeSymbol.UnknownResultType, NullableFlowState.NotNull); /// <summary> /// Contains the map of expressions to inferred nullabilities and types used by the optional rewriter phase of the /// compiler. /// </summary> private readonly ImmutableDictionary<BoundExpression, (NullabilityInfo Info, TypeSymbol? Type)>.Builder? _analyzedNullabilityMapOpt; /// <summary> /// Manages creating snapshots of the walker as appropriate. Null if we're not taking snapshots of /// this walker. /// </summary> private readonly SnapshotManager.Builder? _snapshotBuilderOpt; // https://github.com/dotnet/roslyn/issues/35043: remove this when all expression are supported private bool _disableNullabilityAnalysis; /// <summary> /// State of method group receivers, used later when analyzing the conversion to a delegate. /// (Could be replaced by _analyzedNullabilityMapOpt if that map is always available.) /// </summary> private PooledDictionary<BoundExpression, TypeWithState>? _methodGroupReceiverMapOpt; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.GetInstance(); /// <summary> /// True if we're analyzing speculative code. This turns off some initialization steps /// that would otherwise be taken. /// </summary> private readonly bool _isSpeculative; /// <summary> /// True if this walker was created using an initial state. /// </summary> private readonly bool _hasInitialState; #if DEBUG /// <summary> /// Contains the expressions that should not be inserted into <see cref="_analyzedNullabilityMapOpt"/>. /// </summary> private static readonly ImmutableArray<BoundKind> s_skippedExpressions = ImmutableArray.Create(BoundKind.ArrayInitialization, BoundKind.ObjectInitializerExpression, BoundKind.CollectionInitializerExpression, BoundKind.DynamicCollectionElementInitializer); #endif /// <summary> /// The result and l-value type of the last visited expression. /// </summary> private VisitResult _visitResult; /// <summary> /// The visit result of the receiver for the current conditional access. /// /// For example: A conditional invocation uses a placeholder as a receiver. By storing the /// visit result from the actual receiver ahead of time, we can give this placeholder a correct result. /// </summary> private VisitResult _currentConditionalReceiverVisitResult; /// <summary> /// The result type represents the state of the last visited expression. /// </summary> private TypeWithState ResultType { get => _visitResult.RValueType; } private void SetResultType(BoundExpression? expression, TypeWithState type, bool updateAnalyzedNullability = true) { SetResult(expression, resultType: type, lvalueType: type.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: updateAnalyzedNullability); } /// <summary> /// Force the inference of the LValueResultType from ResultType. /// </summary> private void UseRvalueOnly(BoundExpression? expression) { SetResult(expression, ResultType, ResultType.ToTypeWithAnnotations(compilation), isLvalue: false); } private TypeWithAnnotations LvalueResultType { get => _visitResult.LValueType; } private void SetLvalueResultType(BoundExpression? expression, TypeWithAnnotations type) { SetResult(expression, resultType: type.ToTypeWithState(), lvalueType: type); } /// <summary> /// Force the inference of the ResultType from LValueResultType. /// </summary> private void UseLvalueOnly(BoundExpression? expression) { SetResult(expression, LvalueResultType.ToTypeWithState(), LvalueResultType, isLvalue: true); } private void SetInvalidResult() => SetResult(expression: null, _invalidType, _invalidType.ToTypeWithAnnotations(compilation), updateAnalyzedNullability: false); private void SetResult(BoundExpression? expression, TypeWithState resultType, TypeWithAnnotations lvalueType, bool updateAnalyzedNullability = true, bool? isLvalue = null) { _visitResult = new VisitResult(resultType, lvalueType); if (updateAnalyzedNullability) { SetAnalyzedNullability(expression, _visitResult, isLvalue); } } private bool ShouldMakeNotNullRvalue(BoundExpression node) => node.IsSuppressed || node.HasAnyErrors || !IsReachable(); /// <summary> /// Sets the analyzed nullability of the expression to be the given result. /// </summary> private void SetAnalyzedNullability(BoundExpression? expr, VisitResult result, bool? isLvalue = null) { if (expr == null || _disableNullabilityAnalysis) return; #if DEBUG // https://github.com/dotnet/roslyn/issues/34993: This assert is essential for ensuring that we aren't // changing the observable results of GetTypeInfo beyond nullability information. //Debug.Assert(AreCloseEnough(expr.Type, result.RValueType.Type), // $"Cannot change the type of {expr} from {expr.Type} to {result.RValueType.Type}"); #endif if (_analyzedNullabilityMapOpt != null) { // https://github.com/dotnet/roslyn/issues/34993: enable and verify these assertions #if false if (_analyzedNullabilityMapOpt.TryGetValue(expr, out var existing)) { if (!(result.RValueType.State == NullableFlowState.NotNull && ShouldMakeNotNullRvalue(expr, State.Reachable))) { switch (isLvalue) { case true: Debug.Assert(existing.Info.Annotation == result.LValueType.NullableAnnotation.ToPublicAnnotation(), $"Tried to update the nullability of {expr} from {existing.Info.Annotation} to {result.LValueType.NullableAnnotation}"); break; case false: Debug.Assert(existing.Info.FlowState == result.RValueType.State, $"Tried to update the nullability of {expr} from {existing.Info.FlowState} to {result.RValueType.State}"); break; case null: Debug.Assert(existing.Info.Equals((NullabilityInfo)result), $"Tried to update the nullability of {expr} from ({existing.Info.Annotation}, {existing.Info.FlowState}) to ({result.LValueType.NullableAnnotation}, {result.RValueType.State})"); break; } } } #endif _analyzedNullabilityMapOpt[expr] = (new NullabilityInfo(result.LValueType.ToPublicAnnotation(), result.RValueType.State.ToPublicFlowState()), // https://github.com/dotnet/roslyn/issues/35046 We're dropping the result if the type doesn't match up completely // with the existing type expr.Type?.Equals(result.RValueType.Type, TypeCompareKind.AllIgnoreOptions) == true ? result.RValueType.Type : expr.Type); } } /// <summary> /// Placeholder locals, e.g. for objects being constructed. /// </summary> private PooledDictionary<object, PlaceholderLocal>? _placeholderLocalsOpt; /// <summary> /// For methods with annotations, we'll need to visit the arguments twice. /// Once for diagnostics and once for result state (but disabling diagnostics). /// </summary> private bool _disableDiagnostics = false; /// <summary> /// Whether we are going to read the currently visited expression. /// </summary> private bool _expressionIsRead = true; /// <summary> /// Used to allow <see cref="MakeSlot(BoundExpression)"/> to substitute the correct slot for a <see cref="BoundConditionalReceiver"/> when /// it's encountered. /// </summary> private int _lastConditionalAccessSlot = -1; private bool IsAnalyzingAttribute => methodMainNode.Kind == BoundKind.Attribute; protected override void Free() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.Free(); base.Free(); } private NullableWalker( CSharpCompilation compilation, Symbol? symbol, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, BoundNode node, Binder binder, Conversions conversions, Variables? variables, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, bool isSpeculative = false) : base(compilation, symbol, node, EmptyStructTypeCache.CreatePrecise(), trackUnassignments: true) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethodOpt is object); _variables = variables ?? Variables.Create(symbol); _binder = binder; _conversions = (Conversions)conversions.WithNullability(true); _useConstructorExitWarnings = useConstructorExitWarnings; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; _delegateInvokeMethod = delegateInvokeMethodOpt; _analyzedNullabilityMapOpt = analyzedNullabilityMapOpt; _returnTypesOpt = returnTypesOpt; _snapshotBuilderOpt = snapshotBuilderOpt; _isSpeculative = isSpeculative; _hasInitialState = variables is { }; } public string GetDebuggerDisplay() { if (this.IsConditionalState) { return $"{{{GetType().Name} WhenTrue:{Dump(StateWhenTrue)} WhenFalse:{Dump(StateWhenFalse)}{"}"}"; } else { return $"{{{GetType().Name} {Dump(State)}{"}"}"; } } // For purpose of nullability analysis, awaits create pending branches, so async usings and foreachs do too public sealed override bool AwaitUsingAndForeachAddsPendingBranch => true; protected override void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > StackGuard.MaxUncheckedRecursionDepth && compilation.NullableAnalysisData is { MaxRecursionDepth: var depth } && depth > 0 && recursionDepth > depth) { throw new InsufficientExecutionStackException(); } base.EnsureSufficientExecutionStack(recursionDepth); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } protected override bool TryGetVariable(VariableIdentifier identifier, out int slot) { return _variables.TryGetValue(identifier, out slot); } protected override int AddVariable(VariableIdentifier identifier) { return _variables.Add(identifier); } protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { if (_returnTypesOpt != null) { _returnTypesOpt.Clear(); } this.Diagnostics.Clear(); this.regionPlace = RegionPlace.Before; if (!_isSpeculative) { ParameterSymbol methodThisParameter = MethodThisParameter; EnterParameters(); // assign parameters if (methodThisParameter is object) { EnterParameter(methodThisParameter, methodThisParameter.TypeWithAnnotations); } makeNotNullMembersMaybeNull(); // We need to create a snapshot even of the first node, because we want to have the state of the initial parameters. _snapshotBuilderOpt?.TakeIncrementalSnapshot(methodMainNode, State); } ImmutableArray<PendingBranch> pendingReturns = base.Scan(ref badRegion); if ((_symbol as MethodSymbol)?.IsConstructor() != true || _useConstructorExitWarnings) { EnforceDoesNotReturn(syntaxOpt: null); enforceMemberNotNull(syntaxOpt: null, this.State); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(returnStatement.Syntax, pendingReturn.State); enforceNotNullWhenForPendingReturn(pendingReturn, returnStatement); enforceMemberNotNullWhenForPendingReturn(pendingReturn, returnStatement); } } } return pendingReturns; void enforceMemberNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } var method = _symbol as MethodSymbol; if (method is object) { if (method.IsConstructor()) { Debug.Assert(_useConstructorExitWarnings); var thisSlot = 0; if (method.RequiresInstanceReceiver) { method.TryGetThisParameter(out var thisParameter); Debug.Assert(thisParameter is object); thisSlot = GetOrCreateSlot(thisParameter); } // https://github.com/dotnet/roslyn/issues/46718: give diagnostics on return points, not constructor signature var exitLocation = method.DeclaringSyntaxReferences.IsEmpty ? null : method.Locations.FirstOrDefault(); foreach (var member in method.ContainingType.GetMembersUnordered()) { checkMemberStateOnConstructorExit(method, member, state, thisSlot, exitLocation); } } else { do { foreach (var memberName in method.NotNullMembers) { enforceMemberNotNullOnMember(syntaxOpt, state, method, memberName); } method = method.OverriddenMethod; } while (method != null); } } } void checkMemberStateOnConstructorExit(MethodSymbol constructor, Symbol member, LocalState state, int thisSlot, Location? exitLocation) { var isStatic = !constructor.RequiresInstanceReceiver(); if (member.IsStatic != isStatic) { return; } // This is not required for correctness, but in the case where the member has // an initializer, we know we've assigned to the member and // have given any applicable warnings about a bad value going in. // Therefore we skip this check when the member has an initializer to reduce noise. if (HasInitializer(member)) { return; } TypeWithAnnotations fieldType; FieldSymbol? field; Symbol symbol; switch (member) { case FieldSymbol f: fieldType = f.TypeWithAnnotations; field = f; symbol = (Symbol?)(f.AssociatedSymbol as PropertySymbol) ?? f; break; case EventSymbol e: fieldType = e.TypeWithAnnotations; field = e.AssociatedField; symbol = e; if (field is null) { return; } break; default: return; } if (field.IsConst) { return; } if (fieldType.Type.IsValueType || fieldType.Type.IsErrorType()) { return; } var annotations = symbol.GetFlowAnalysisAnnotations(); if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { // We assume that if a member has AllowNull then the user // does not care that we exit at a point where the member might be null. return; } fieldType = ApplyUnconditionalAnnotations(fieldType, annotations); if (!fieldType.NullableAnnotation.IsNotAnnotated()) { return; } var slot = GetOrCreateSlot(symbol, thisSlot); if (slot < 0) { return; } var memberState = state[slot]; var badState = fieldType.Type.IsPossiblyNullableReferenceTypeTypeParameter() && (annotations & FlowAnalysisAnnotations.NotNull) == 0 ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; if (memberState >= badState) // is 'memberState' as bad as or worse than 'badState'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } void enforceMemberNotNullOnMember(SyntaxNode? syntaxOpt, LocalState state, MethodSymbol method, string memberName) { foreach (var member in method.ContainingType.GetMembers(memberName)) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_MemberNotNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name); } } } void enforceMemberNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } if (_symbol is MethodSymbol method) { foreach (var memberName in method.NotNullWhenTrueMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: true, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenTrue, pendingReturn.StateWhenFalse); } foreach (var memberName in method.NotNullWhenFalseMembers) { enforceMemberNotNullWhenIfAffected(returnStatement.Syntax, sense: false, method.ContainingType.GetMembers(memberName), pendingReturn.StateWhenFalse, pendingReturn.StateWhenTrue); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceMemberNotNullWhen(returnStatement.Syntax, sense: value, pendingReturn.State); } } void enforceMemberNotNullWhenIfAffected(SyntaxNode? syntaxOpt, bool sense, ImmutableArray<Symbol> members, LocalState state, LocalState otherState) { foreach (var member in members) { // For non-constant values, only complain if we were able to analyze a difference for this member between two branches if (memberHasBadState(member, state) != memberHasBadState(member, otherState)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } void enforceMemberNotNullWhen(SyntaxNode? syntaxOpt, bool sense, LocalState state) { if (_symbol is MethodSymbol method) { var notNullMembers = sense ? method.NotNullWhenTrueMembers : method.NotNullWhenFalseMembers; foreach (var memberName in notNullMembers) { foreach (var member in method.ContainingType.GetMembers(memberName)) { reportMemberIfBadConditionalState(syntaxOpt, sense, member, state); } } } } void reportMemberIfBadConditionalState(SyntaxNode? syntaxOpt, bool sense, Symbol member, LocalState state) { if (memberHasBadState(member, state)) { // Member '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_MemberNotNullWhen, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), member.Name, sense ? "true" : "false"); } } bool memberHasBadState(Symbol member, LocalState state) { switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { var parameterState = state[memberSlot]; return !parameterState.IsNotNull(); } else { return false; } case SymbolKind.Event: case SymbolKind.Method: break; } return false; } void makeNotNullMembersMaybeNull() { if (_symbol is MethodSymbol method) { if (method.IsConstructor()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { if (member.IsStatic != method.IsStatic) { continue; } var memberToInitialize = member; switch (member) { case PropertySymbol: // skip any manually implemented properties. continue; case FieldSymbol { IsConst: true }: continue; case FieldSymbol { AssociatedSymbol: PropertySymbol prop }: // this is a property where assigning 'default' causes us to simply update // the state to the output state of the property // thus we skip setting an initial state for it here if (IsPropertyOutputMoreStrictThanInput(prop)) { continue; } // We want to initialize auto-property state to the default state, but not computed properties. memberToInitialize = prop; break; default: break; } var memberSlot = getSlotForFieldOrPropertyOrEvent(memberToInitialize); if (memberSlot > 0) { var type = memberToInitialize.GetTypeOrReturnType(); if (!type.NullableAnnotation.IsOblivious()) { this.State[memberSlot] = type.Type.IsPossiblyNullableReferenceTypeTypeParameter() ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } } } else { do { makeMembersMaybeNull(method, method.NotNullMembers); makeMembersMaybeNull(method, method.NotNullWhenTrueMembers); makeMembersMaybeNull(method, method.NotNullWhenFalseMembers); method = method.OverriddenMethod; } while (method != null); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // We don't use a default initial state for value type instance constructors without `: this()` because // any usages of uninitialized fields will get definite assignment errors anyway. if (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } void makeMembersMaybeNull(MethodSymbol method, ImmutableArray<string> members) { foreach (var memberName in members) { makeMemberMaybeNull(method, memberName); } } void makeMemberMaybeNull(MethodSymbol method, string memberName) { var type = method.ContainingType; foreach (var member in type.GetMembers(memberName)) { if (getSlotForFieldOrPropertyOrEvent(member) is int memberSlot && memberSlot > 0) { this.State[memberSlot] = NullableFlowState.MaybeNull; } } } void enforceNotNullWhenForPendingReturn(PendingBranch pendingReturn, BoundReturnStatement returnStatement) { var parameters = this.MethodParameters; if (!parameters.IsEmpty) { if (pendingReturn.IsConditionalState) { if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } if (!pendingReturn.StateWhenTrue.Reachable || !pendingReturn.StateWhenFalse.Reachable) { return; } foreach (var parameter in parameters) { // For non-constant values, only complain if we were able to analyze a difference for this parameter between two branches if (GetOrCreateSlot(parameter) is > 0 and var slot && pendingReturn.StateWhenTrue[slot] != pendingReturn.StateWhenFalse[slot]) { reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: true, stateWhen: pendingReturn.StateWhenTrue); reportParameterIfBadConditionalState(returnStatement.Syntax, parameter, sense: false, stateWhen: pendingReturn.StateWhenFalse); } } } else if (returnStatement.ExpressionOpt is { ConstantValue: { IsBoolean: true, BooleanValue: bool value } }) { // example: return (bool)true; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } void reportParameterIfBadConditionalState(SyntaxNode syntax, ParameterSymbol parameter, bool sense, LocalState stateWhen) { if (parameterHasBadConditionalState(parameter, sense, stateWhen)) { // Parameter '{name}' must have a non-null value when exiting with '{sense}'. Diagnostics.Add(ErrorCode.WRN_ParameterConditionallyDisallowsNull, syntax.Location, parameter.Name, sense ? "true" : "false"); } } void enforceNotNull(SyntaxNode? syntaxOpt, LocalState state) { if (!state.Reachable) { return; } foreach (var parameter in this.MethodParameters) { var slot = GetOrCreateSlot(parameter); if (slot <= 0) { continue; } var annotations = parameter.FlowAnalysisAnnotations; var hasNotNull = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; var parameterState = state[slot]; if (hasNotNull && parameterState.MayBeNull()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } bool parameterHasBadConditionalState(ParameterSymbol parameter, bool sense, LocalState stateWhen) { var refKind = parameter.RefKind; if (refKind != RefKind.Out && refKind != RefKind.Ref) { return false; } var slot = GetOrCreateSlot(parameter); if (slot > 0) { var parameterState = stateWhen[slot]; // On a parameter marked with MaybeNullWhen, we would have not reported an assignment warning. // We should only check if an assignment warning would have been warranted ignoring the MaybeNullWhen. FlowAnalysisAnnotations annotations = parameter.FlowAnalysisAnnotations; if (sense) { bool hasNotNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenTrue; bool hasMaybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenFalse; return (hasNotNullWhenTrue && parameterState.MayBeNull()) || (hasMaybeNullWhenFalse && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } else { bool hasNotNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNullWhenFalse; bool hasMaybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNullWhenTrue; return (hasNotNullWhenFalse && parameterState.MayBeNull()) || (hasMaybeNullWhenTrue && ShouldReportNullableAssignment(parameter.TypeWithAnnotations, parameterState)); } } return false; } int getSlotForFieldOrPropertyOrEvent(Symbol member) { if (member.Kind != SymbolKind.Field && member.Kind != SymbolKind.Property && member.Kind != SymbolKind.Event) { return -1; } int containingSlot = 0; if (!member.IsStatic) { if (MethodThisParameter is null) { return -1; } containingSlot = GetOrCreateSlot(MethodThisParameter); if (containingSlot < 0) { return -1; } Debug.Assert(containingSlot > 0); } return GetOrCreateSlot(member, containingSlot); } } private void EnforceNotNullIfNotNull(SyntaxNode? syntaxOpt, LocalState state, ImmutableArray<ParameterSymbol> parameters, ImmutableHashSet<string> inputParamNames, NullableFlowState outputState, ParameterSymbol? outputParam) { if (inputParamNames.IsEmpty || outputState.IsNotNull()) { return; } foreach (var inputParam in parameters) { if (inputParamNames.Contains(inputParam.Name) && GetOrCreateSlot(inputParam) is > 0 and int inputSlot && state[inputSlot].IsNotNull()) { var location = syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(); if (outputParam is object) { // Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null. Diagnostics.Add(ErrorCode.WRN_ParameterNotNullIfNotNull, location, outputParam.Name, inputParam.Name); } else if (CurrentSymbol is MethodSymbol { IsAsync: false }) { // Return value must be non-null because parameter '{0}' is non-null. Diagnostics.Add(ErrorCode.WRN_ReturnNotNullIfNotNull, location, inputParam.Name); } break; } } } private void EnforceDoesNotReturn(SyntaxNode? syntaxOpt) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } method && ((method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) && this.IsReachable()) { // A method marked [DoesNotReturn] should not return. ReportDiagnostic(ErrorCode.WRN_ShouldNotReturn, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation()); } } /// <summary> /// Analyzes a method body if settings indicate we should. /// </summary> internal static void AnalyzeIfNeeded( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState) { if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(method)) { if (compilation.IsNullableAnalysisEnabledAlways) { // Once we address https://github.com/dotnet/roslyn/issues/46579 we should also always pass `getFinalNullableState: true` in debug mode. // We will likely always need to write a 'null' out for the out parameter in this code path, though, because // we don't want to introduce behavior differences between debug and release builds Analyze(compilation, method, node, new DiagnosticBag(), useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: false, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { if (method.IsImplicitlyDeclared && !method.IsImplicitConstructor && !method.IsScriptInitializer) { finalNullableState = null; return; } Debug.Assert(node.SyntaxTree is object); var binder = method is SynthesizedSimpleProgramEntryPointSymbol entryPoint ? entryPoint.GetBodyBinder(ignoreAccessibility: false) : compilation.GetBinderFactory(node.SyntaxTree).GetBinder(node.Syntax); var conversions = binder.Conversions; Analyze(compilation, method, node, binder, conversions, diagnostics, useConstructorExitWarnings, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: initialNullableState, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return null; } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information. This method is only /// used when nullable is explicitly enabled for all methods but disabled otherwise to verify that /// correct semantic information is being recorded for all bound nodes. The results are thrown away. /// </summary> internal static void AnalyzeWithoutRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, DiagnosticBag diagnostics, bool createSnapshots) { _ = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState: GetAfterInitializersState(compilation, symbol), diagnostics, createSnapshots, requiresAnalysis: false); } /// <summary> /// Analyzes a set of bound nodes, recording updated nullability information, and returns an /// updated BoundNode with the information populated. /// </summary> internal static BoundNode AnalyzeAndRewrite( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, out SnapshotManager? snapshotManager, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> analyzedNullabilitiesMap; (snapshotManager, analyzedNullabilitiesMap) = AnalyzeWithSemanticInfo(compilation, symbol, node, binder, initialState, diagnostics, createSnapshots, requiresAnalysis: true); return Rewrite(analyzedNullabilitiesMap, snapshotManager, node, ref remappedSymbols); } private static (SnapshotManager?, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>) AnalyzeWithSemanticInfo( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, VariableState? initialState, DiagnosticBag diagnostics, bool createSnapshots, bool requiresAnalysis) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); // Attributes don't have a symbol, which is what SnapshotBuilder uses as an index for maintaining global state. // Until we have a workaround for this, disable snapshots for null symbols. // https://github.com/dotnet/roslyn/issues/36066 var snapshotBuilder = createSnapshots && symbol != null ? new SnapshotManager.Builder() : null; Analyze( compilation, symbol, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: true, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState, analyzedNullabilities, snapshotBuilder, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); var snapshotManager = snapshotBuilder?.ToManagerAndFree(); #if DEBUG // https://github.com/dotnet/roslyn/issues/34993 Enable for all calls if (isNullableAnalysisEnabledAnywhere(compilation)) { DebugVerifier.Verify(analyzedNullabilitiesMap, snapshotManager, node); } static bool isNullableAnalysisEnabledAnywhere(CSharpCompilation compilation) { if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { return true; } return compilation.SyntaxTrees.Any(tree => ((CSharpSyntaxTree)tree).IsNullableAnalysisEnabled(new Text.TextSpan(0, tree.Length)) == true); } #endif return (snapshotManager, analyzedNullabilitiesMap); } internal static BoundNode AnalyzeAndRewriteSpeculation( int position, BoundNode node, Binder binder, SnapshotManager originalSnapshots, out SnapshotManager newSnapshots, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var analyzedNullabilities = ImmutableDictionary.CreateBuilder<BoundExpression, (NullabilityInfo, TypeSymbol?)>(EqualityComparer<BoundExpression>.Default, NullabilityInfoTypeComparer.Instance); var newSnapshotBuilder = new SnapshotManager.Builder(); var (variables, localState) = originalSnapshots.GetSnapshot(position); var symbol = variables.Symbol; var walker = new NullableWalker( binder.Compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, binder.Conversions, Variables.Create(variables), returnTypesOpt: null, analyzedNullabilities, newSnapshotBuilder, isSpeculative: true); try { Analyze(walker, symbol, diagnostics: null, LocalState.Create(localState), snapshotBuilderOpt: newSnapshotBuilder); } finally { walker.Free(); } var analyzedNullabilitiesMap = analyzedNullabilities.ToImmutable(); newSnapshots = newSnapshotBuilder.ToManagerAndFree(); #if DEBUG DebugVerifier.Verify(analyzedNullabilitiesMap, newSnapshots, node); #endif return Rewrite(analyzedNullabilitiesMap, newSnapshots, node, ref remappedSymbols); } private static BoundNode Rewrite(ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)> updatedNullabilities, SnapshotManager? snapshotManager, BoundNode node, ref ImmutableDictionary<Symbol, Symbol>? remappedSymbols) { var remappedSymbolsBuilder = ImmutableDictionary.CreateBuilder<Symbol, Symbol>(Symbols.SymbolEqualityComparer.ConsiderEverything, Symbols.SymbolEqualityComparer.ConsiderEverything); if (remappedSymbols is object) { // When we're rewriting for the speculative model, there will be a set of originally-mapped symbols, and we need to // use them in addition to any symbols found during this pass of the walker. remappedSymbolsBuilder.AddRange(remappedSymbols); } var rewriter = new NullabilityRewriter(updatedNullabilities, snapshotManager, remappedSymbolsBuilder); var rewrittenNode = rewriter.Visit(node); remappedSymbols = remappedSymbolsBuilder.ToImmutable(); return rewrittenNode; } private static bool HasRequiredLanguageVersion(CSharpCompilation compilation) { return compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); } /// <summary> /// Returns true if the nullable analysis is needed for the region represented by <paramref name="syntaxNode"/>. /// The syntax node is used to determine the overall nullable context for the region. /// </summary> internal static bool NeedsAnalysis(CSharpCompilation compilation, SyntaxNode syntaxNode) { return HasRequiredLanguageVersion(compilation) && (compilation.IsNullableAnalysisEnabledIn(syntaxNode) || compilation.IsNullableAnalysisEnabledAlways); } /// <summary>Analyzes a node in a "one-off" context, such as for attributes or parameter default values.</summary> /// <remarks><paramref name="syntax"/> is the syntax span used to determine the overall nullable context.</remarks> internal static void AnalyzeIfNeeded( Binder binder, BoundNode node, SyntaxNode syntax, DiagnosticBag diagnostics) { bool requiresAnalysis = true; var compilation = binder.Compilation; if (!HasRequiredLanguageVersion(compilation) || !compilation.IsNullableAnalysisEnabledIn(syntax)) { if (!compilation.IsNullableAnalysisEnabledAlways) { return; } diagnostics = new DiagnosticBag(); requiresAnalysis = false; } Analyze( compilation, symbol: null, node, binder, binder.Conversions, diagnostics, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, initialState: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState: false, out _, requiresAnalysis); } internal static void Analyze( CSharpCompilation compilation, BoundLambda lambda, Conversions conversions, DiagnosticBag diagnostics, MethodSymbol? delegateInvokeMethodOpt, VariableState initialState, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt) { var symbol = lambda.Symbol; var variables = Variables.Create(initialState.Variables).CreateNestedMethodScope(symbol); UseDelegateInvokeParameterAndReturnTypes(lambda, delegateInvokeMethodOpt, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); var walker = new NullableWalker( compilation, symbol, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: useDelegateInvokeParameterTypes, useDelegateInvokeReturnType: useDelegateInvokeReturnType, delegateInvokeMethodOpt: delegateInvokeMethodOpt, lambda.Body, lambda.Binder, conversions, variables, returnTypesOpt, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); try { var localState = LocalState.Create(initialState.VariableNullableStates).CreateNestedMethodState(variables); Analyze(walker, symbol, diagnostics, localState, snapshotBuilderOpt: null); } finally { walker.Free(); } } private static void Analyze( CSharpCompilation compilation, Symbol? symbol, BoundNode node, Binder binder, Conversions conversions, DiagnosticBag diagnostics, bool useConstructorExitWarnings, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType, MethodSymbol? delegateInvokeMethodOpt, VariableState? initialState, ImmutableDictionary<BoundExpression, (NullabilityInfo, TypeSymbol?)>.Builder? analyzedNullabilityMapOpt, SnapshotManager.Builder? snapshotBuilderOpt, ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>? returnTypesOpt, bool getFinalNullableState, out VariableState? finalNullableState, bool requiresAnalysis = true) { Debug.Assert(diagnostics != null); var walker = new NullableWalker(compilation, symbol, useConstructorExitWarnings, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType, delegateInvokeMethodOpt, node, binder, conversions, initialState is null ? null : Variables.Create(initialState.Variables), returnTypesOpt, analyzedNullabilityMapOpt, snapshotBuilderOpt); finalNullableState = null; try { Analyze(walker, symbol, diagnostics, initialState is null ? (Optional<LocalState>)default : LocalState.Create(initialState.VariableNullableStates), snapshotBuilderOpt, requiresAnalysis); if (getFinalNullableState) { Debug.Assert(!walker.IsConditionalState); finalNullableState = GetVariableState(walker._variables, walker.State); } } finally { walker.Free(); } } private static void Analyze( NullableWalker walker, Symbol? symbol, DiagnosticBag? diagnostics, Optional<LocalState> initialState, SnapshotManager.Builder? snapshotBuilderOpt, bool requiresAnalysis = true) { Debug.Assert(snapshotBuilderOpt is null || symbol is object); var previousSlot = snapshotBuilderOpt?.EnterNewWalker(symbol!) ?? -1; try { bool badRegion = false; ImmutableArray<PendingBranch> returns = walker.Analyze(ref badRegion, initialState); diagnostics?.AddRange(walker.Diagnostics); Debug.Assert(!badRegion); } catch (CancelledByStackGuardException ex) when (diagnostics != null) { ex.AddAnError(diagnostics); } finally { snapshotBuilderOpt?.ExitWalker(walker.SaveSharedState(), previousSlot); } walker.RecordNullableAnalysisData(symbol, requiresAnalysis); } private void RecordNullableAnalysisData(Symbol? symbol, bool requiredAnalysis) { if (compilation.NullableAnalysisData?.Data is { } state) { var key = (object?)symbol ?? methodMainNode.Syntax; if (state.TryGetValue(key, out var result)) { Debug.Assert(result.RequiredAnalysis == requiredAnalysis); } else { state.TryAdd(key, new Data(_variables.GetTotalVariableCount(), requiredAnalysis)); } } } private SharedWalkerState SaveSharedState() { return new SharedWalkerState(_variables.CreateSnapshot()); } private void TakeIncrementalSnapshot(BoundNode? node) { Debug.Assert(!IsConditionalState); _snapshotBuilderOpt?.TakeIncrementalSnapshot(node, State); } private void SetUpdatedSymbol(BoundNode node, Symbol originalSymbol, Symbol updatedSymbol) { if (_snapshotBuilderOpt is null) { return; } var lambdaIsExactMatch = false; if (node is BoundLambda boundLambda && originalSymbol is LambdaSymbol l && updatedSymbol is NamedTypeSymbol n) { if (!AreLambdaAndNewDelegateSimilar(l, n)) { return; } lambdaIsExactMatch = updatedSymbol.Equals(boundLambda.Type!.GetDelegateType(), TypeCompareKind.ConsiderEverything); } #if DEBUG Debug.Assert(node is object); Debug.Assert(AreCloseEnough(originalSymbol, updatedSymbol), $"Attempting to set {node.Syntax} from {originalSymbol.ToDisplayString()} to {updatedSymbol.ToDisplayString()}"); #endif if (lambdaIsExactMatch || Symbol.Equals(originalSymbol, updatedSymbol, TypeCompareKind.ConsiderEverything)) { // If the symbol is reset, remove the updated symbol so we don't needlessly update the // bound node later on. We do this unconditionally, as Remove will just return false // if the key wasn't in the dictionary. _snapshotBuilderOpt.RemoveSymbolIfPresent(node, originalSymbol); } else { _snapshotBuilderOpt.SetUpdatedSymbol(node, originalSymbol, updatedSymbol); } } protected override void Normalize(ref LocalState state) { if (!state.Reachable) return; state.Normalize(this, _variables); } private NullableFlowState GetDefaultState(ref LocalState state, int slot) { Debug.Assert(slot > 0); if (!state.Reachable) return NullableFlowState.NotNull; var variable = _variables[slot]; var symbol = variable.Symbol; switch (symbol.Kind) { case SymbolKind.Local: { var local = (LocalSymbol)symbol; if (!_variables.TryGetType(local, out TypeWithAnnotations localType)) { localType = local.TypeWithAnnotations; } return localType.ToTypeWithState().State; } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (!_variables.TryGetType(parameter, out TypeWithAnnotations parameterType)) { parameterType = parameter.TypeWithAnnotations; } return GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; } case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return GetDefaultState(symbol); case SymbolKind.ErrorType: return NullableFlowState.NotNull; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundExpression? receiver, [NotNullWhen(true)] out Symbol? member) { receiver = null; member = null; switch (expr.Kind) { case BoundKind.FieldAccess: { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; member = fieldSymbol; if (fieldSymbol.IsFixedSizeBuffer) { return false; } if (fieldSymbol.IsStatic) { return true; } receiver = fieldAccess.ReceiverOpt; break; } case BoundKind.EventAccess: { var eventAccess = (BoundEventAccess)expr; var eventSymbol = eventAccess.EventSymbol; // https://github.com/dotnet/roslyn/issues/29901 Use AssociatedField for field-like events? member = eventSymbol; if (eventSymbol.IsStatic) { return true; } receiver = eventAccess.ReceiverOpt; break; } case BoundKind.PropertyAccess: { var propAccess = (BoundPropertyAccess)expr; var propSymbol = propAccess.PropertySymbol; member = propSymbol; if (propSymbol.IsStatic) { return true; } receiver = propAccess.ReceiverOpt; break; } } Debug.Assert(member?.RequiresInstanceReceiver() ?? true); return member is object && receiver is object && receiver.Kind != BoundKind.TypeExpression && receiver.Type is object; } protected override int MakeSlot(BoundExpression node) { int result = makeSlot(node); #if DEBUG if (result != -1) { // Check that the slot represents a value of an equivalent type to the node TypeSymbol slotType = NominalSlotType(result); TypeSymbol? nodeType = node.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = this.compilation.Conversions; Debug.Assert(node.HasErrors || nodeType!.IsErrorType() || conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(slotType, nodeType, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(slotType, nodeType, ref discardedUseSiteInfo)); } #endif return result; int makeSlot(BoundExpression node) { switch (node.Kind) { case BoundKind.ThisReference: case BoundKind.BaseReference: { var method = getTopLevelMethod(_symbol as MethodSymbol); var thisParameter = method?.ThisParameter; return thisParameter is object ? GetOrCreateSlot(thisParameter) : -1; } case BoundKind.Conversion: { int slot = getPlaceholderSlot(node); if (slot > 0) { return slot; } var conv = (BoundConversion)node; switch (conv.Conversion.Kind) { case ConversionKind.ExplicitNullable: { var operand = conv.Operand; var operandType = operand.Type; var convertedType = conv.Type; if (AreNullableAndUnderlyingTypes(operandType, convertedType, out _)) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. // For instance, in the following, when evaluating `((A)a).B` we need to recognize // the nullability of `(A)a` (not nullable) and the slot (the slot for `a.Value`). // struct A { B? B; } // struct B { } // if (a?.B != null) _ = ((A)a).B.Value; // no warning int containingSlot = MakeSlot(operand); return containingSlot < 0 ? -1 : GetNullableOfTValueSlot(operandType, containingSlot, out _); } } break; case ConversionKind.Identity: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.Boxing: // No need to create a slot for the boxed value (in the Boxing case) since assignment already // clones slots and there is not another scenario where creating a slot is observable. return MakeSlot(conv.Operand); } } break; case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.ObjectCreationExpression: case BoundKind.DynamicObjectCreationExpression: case BoundKind.AnonymousObjectCreationExpression: case BoundKind.NewT: case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return getPlaceholderSlot(node); case BoundKind.ConditionalAccess: return getPlaceholderSlot(node); case BoundKind.ConditionalReceiver: return _lastConditionalAccessSlot; default: { int slot = getPlaceholderSlot(node); return (slot > 0) ? slot : base.MakeSlot(node); } } return -1; } int getPlaceholderSlot(BoundExpression expr) { if (_placeholderLocalsOpt != null && _placeholderLocalsOpt.TryGetValue(expr, out var placeholder)) { return GetOrCreateSlot(placeholder); } return -1; } static MethodSymbol? getTopLevelMethod(MethodSymbol? method) { while (method is object) { var container = method.ContainingSymbol; if (container.Kind == SymbolKind.NamedType) { return method; } method = container as MethodSymbol; } return null; } } protected override int GetOrCreateSlot(Symbol symbol, int containingSlot = 0, bool forceSlotEvenIfEmpty = false, bool createIfMissing = true) { if (containingSlot > 0 && !IsSlotMember(containingSlot, symbol)) return -1; return base.GetOrCreateSlot(symbol, containingSlot, forceSlotEvenIfEmpty, createIfMissing); } private void VisitAndUnsplitAll<T>(ImmutableArray<T> nodes) where T : BoundNode { if (nodes.IsDefault) { return; } foreach (var node in nodes) { Visit(node); Unsplit(); } } private void VisitWithoutDiagnostics(BoundNode? node) { var previousDiagnostics = _disableDiagnostics; _disableDiagnostics = true; Visit(node); _disableDiagnostics = previousDiagnostics; } protected override void VisitRvalue(BoundExpression? node, bool isKnownToBeAnLvalue = false) { Visit(node); VisitRvalueEpilogue(node); } /// <summary> /// The contents of this method, particularly <see cref="UseRvalueOnly"/>, are problematic when /// inlined. The methods themselves are small but they end up allocating significantly larger /// frames due to the use of biggish value types within them. The <see cref="VisitRvalue"/> method /// is used on a hot path for fluent calls and this size change is enough that it causes us /// to exceed our thresholds in EndToEndTests.OverflowOnFluentCall. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void VisitRvalueEpilogue(BoundExpression? node) { Unsplit(); UseRvalueOnly(node); // drop lvalue part } private TypeWithState VisitRvalueWithState(BoundExpression? node) { VisitRvalue(node); return ResultType; } private TypeWithAnnotations VisitLvalueWithAnnotations(BoundExpression node) { VisitLValue(node); Unsplit(); return LvalueResultType; } private static object GetTypeAsDiagnosticArgument(TypeSymbol? typeOpt) { return typeOpt ?? (object)"<null>"; } private static object GetParameterAsDiagnosticArgument(ParameterSymbol? parameterOpt) { return parameterOpt is null ? (object)"" : new FormattedSymbol(parameterOpt, SymbolDisplayFormat.ShortFormat); } private static object GetContainingSymbolAsDiagnosticArgument(ParameterSymbol? parameterOpt) { var containingSymbol = parameterOpt?.ContainingSymbol; return containingSymbol is null ? (object)"" : new FormattedSymbol(containingSymbol, SymbolDisplayFormat.MinimallyQualifiedFormat); } private enum AssignmentKind { Assignment, Return, Argument, ForEachIterationVariable } /// <summary> /// Should we warn for assigning this state into this type? /// /// This should often be checked together with <seealso cref="IsDisallowedNullAssignment(TypeWithState, FlowAnalysisAnnotations)"/> /// It catches putting a `null` into a `[DisallowNull]int?` for example, which cannot simply be represented as a non-nullable target type. /// </summary> private static bool ShouldReportNullableAssignment(TypeWithAnnotations type, NullableFlowState state) { if (!type.HasType || type.Type.IsValueType) { return false; } switch (type.NullableAnnotation) { case NullableAnnotation.Oblivious: case NullableAnnotation.Annotated: return false; } switch (state) { case NullableFlowState.NotNull: return false; case NullableFlowState.MaybeNull: if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8() && !(type.Type is TypeParameterSymbol { IsNotNullable: true })) { return false; } break; } return true; } /// <summary> /// Reports top-level nullability problem in assignment. /// Any conversion of the value should have been applied. /// </summary> private void ReportNullableAssignmentIfNecessary( BoundExpression? value, TypeWithAnnotations targetType, TypeWithState valueType, bool useLegacyWarnings, AssignmentKind assignmentKind = AssignmentKind.Assignment, ParameterSymbol? parameterOpt = null, Location? location = null) { // Callers should apply any conversions before calling this method // (see https://github.com/dotnet/roslyn/issues/39867). if (targetType.HasType && !targetType.Type.Equals(valueType.Type, TypeCompareKind.AllIgnoreOptions)) { return; } if (value == null || // This prevents us from giving undesired warnings for synthesized arguments for optional parameters, // but allows us to give warnings for synthesized assignments to record properties and for parameter default values at the declaration site. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !ShouldReportNullableAssignment(targetType, valueType.State)) { return; } location ??= value.Syntax.GetLocation(); var unwrappedValue = SkipReferenceConversions(value); if (unwrappedValue.IsSuppressed) { return; } if (value.ConstantValue?.IsNull == true && !useLegacyWarnings) { // Report warning converting null literal to non-nullable reference type. // target (e.g.: `object F() => null;` or calling `void F(object y)` with `F(null)`). ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullAsNonNullable, location); } else if (assignmentKind == AssignmentKind.Argument) { ReportDiagnostic(ErrorCode.WRN_NullReferenceArgument, location, GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); LearnFromNonNullTest(value, ref State); } else if (useLegacyWarnings) { if (isMaybeDefaultValue(valueType) && !allowUnconstrainedTypeParameterAnnotations(compilation)) { // No W warning reported assigning or casting [MaybeNull]T value to T // because there is no syntax for declaring the target type as [MaybeNull]T. return; } ReportNonSafetyDiagnostic(location); } else { ReportDiagnostic(assignmentKind == AssignmentKind.Return ? ErrorCode.WRN_NullReferenceReturn : ErrorCode.WRN_NullReferenceAssignment, location); } static bool isMaybeDefaultValue(TypeWithState valueType) { return valueType.Type?.TypeKind == TypeKind.TypeParameter && valueType.State == NullableFlowState.MaybeDefault; } static bool allowUnconstrainedTypeParameterAnnotations(CSharpCompilation compilation) { // Check IDS_FeatureDefaultTypeParameterConstraint feature since `T?` and `where ... : default` // are treated as a single feature, even though the errors reported for the two cases are distinct. var requiredVersion = MessageID.IDS_FeatureDefaultTypeParameterConstraint.RequiredVersion(); return requiredVersion <= compilation.LanguageVersion; } } internal static bool AreParameterAnnotationsCompatible( RefKind refKind, TypeWithAnnotations overriddenType, FlowAnalysisAnnotations overriddenAnnotations, TypeWithAnnotations overridingType, FlowAnalysisAnnotations overridingAnnotations, bool forRef = false) { // We've already checked types and annotations, let's check nullability attributes as well // Return value is treated as an `out` parameter (or `ref` if it is a `ref` return) if (refKind == RefKind.Ref) { // ref variables are invariant return AreParameterAnnotationsCompatible(RefKind.None, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations, forRef: true) && AreParameterAnnotationsCompatible(RefKind.Out, overriddenType, overriddenAnnotations, overridingType, overridingAnnotations); } if (refKind == RefKind.None || refKind == RefKind.In) { // pre-condition attributes // Check whether we can assign a value from overridden parameter to overriding var valueState = GetParameterState(overriddenType, overriddenAnnotations); if (isBadAssignment(valueState, overridingType, overridingAnnotations)) { return false; } // unconditional post-condition attributes on inputs bool overridingHasNotNull = (overridingAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; bool overriddenHasNotNull = (overriddenAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull; if (overriddenHasNotNull && !overridingHasNotNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise not to return if parameter is null) return false; } bool overridingHasMaybeNull = (overridingAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; bool overriddenHasMaybeNull = (overriddenAnnotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull; if (overriddenHasMaybeNull && !overridingHasMaybeNull && !forRef) { // Overriding doesn't conform to contract of overridden (ie. promise to only return if parameter is null) return false; } } if (refKind == RefKind.Out) { // post-condition attributes (`Maybe/NotNull` and `Maybe/NotNullWhen`) if (!canAssignOutputValueWhen(true) || !canAssignOutputValueWhen(false)) { return false; } } return true; bool canAssignOutputValueWhen(bool sense) { var valueWhen = ApplyUnconditionalAnnotations( overridingType.ToTypeWithState(), makeUnconditionalAnnotation(overridingAnnotations, sense)); var destAnnotationsWhen = ToInwardAnnotations(makeUnconditionalAnnotation(overriddenAnnotations, sense)); if (isBadAssignment(valueWhen, overriddenType, destAnnotationsWhen)) { // Can't assign value from overriding to overridden in 'sense' case return false; } return true; } static bool isBadAssignment(TypeWithState valueState, TypeWithAnnotations destinationType, FlowAnalysisAnnotations destinationAnnotations) { if (ShouldReportNullableAssignment( ApplyLValueAnnotations(destinationType, destinationAnnotations), valueState.State)) { return true; } if (IsDisallowedNullAssignment(valueState, destinationAnnotations)) { return true; } return false; } // Convert both conditional annotations to unconditional ones or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotation(FlowAnalysisAnnotations annotations, bool sense) { if (sense) { var unconditionalAnnotationWhenTrue = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenTrue, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenTrue, FlowAnalysisAnnotations.MaybeNullWhenTrue, FlowAnalysisAnnotations.MaybeNull); } var unconditionalAnnotationWhenFalse = makeUnconditionalAnnotationCore(annotations, FlowAnalysisAnnotations.NotNullWhenFalse, FlowAnalysisAnnotations.NotNull); return makeUnconditionalAnnotationCore(unconditionalAnnotationWhenFalse, FlowAnalysisAnnotations.MaybeNullWhenFalse, FlowAnalysisAnnotations.MaybeNull); } // Convert Maybe/NotNullWhen into Maybe/NotNull or nothing static FlowAnalysisAnnotations makeUnconditionalAnnotationCore(FlowAnalysisAnnotations annotations, FlowAnalysisAnnotations conditionalAnnotation, FlowAnalysisAnnotations replacementAnnotation) { if ((annotations & conditionalAnnotation) != 0) { return annotations | replacementAnnotation; } return annotations & ~replacementAnnotation; } } private static bool IsDefaultValue(BoundExpression expr) { switch (expr.Kind) { case BoundKind.Conversion: { var conversion = (BoundConversion)expr; var conversionKind = conversion.Conversion.Kind; return (conversionKind == ConversionKind.DefaultLiteral || conversionKind == ConversionKind.NullLiteral) && IsDefaultValue(conversion.Operand); } case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; default: return false; } } private void ReportNullabilityMismatchInAssignment(SyntaxNode syntaxNode, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, syntaxNode, sourceType, destinationType); } private void ReportNullabilityMismatchInAssignment(Location location, object sourceType, object destinationType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, location, sourceType, destinationType); } /// <summary> /// Update tracked value on assignment. /// </summary> private void TrackNullableStateForAssignment( BoundExpression? valueOpt, TypeWithAnnotations targetType, int targetSlot, TypeWithState valueType, int valueSlot = -1) { Debug.Assert(!IsConditionalState); if (this.State.Reachable) { if (!targetType.HasType) { return; } if (targetSlot <= 0 || targetSlot == valueSlot) { return; } if (!this.State.HasValue(targetSlot)) Normalize(ref this.State); var newState = valueType.State; SetStateAndTrackForFinally(ref this.State, targetSlot, newState); InheritDefaultState(targetType.Type, targetSlot); // https://github.com/dotnet/roslyn/issues/33428: Can the areEquivalentTypes check be removed // if InheritNullableStateOfMember asserts the member is valid for target and value? if (areEquivalentTypes(targetType, valueType)) { if (targetType.Type.IsReferenceType || targetType.TypeKind == TypeKind.TypeParameter || targetType.IsNullableType()) { if (valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot: targetSlot); } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.Type)) { InheritNullableStateOfTrackableStruct(targetType.Type, targetSlot, valueSlot, isDefaultValue: !(valueOpt is null) && IsDefaultValue(valueOpt), skipSlot: targetSlot); } } } static bool areEquivalentTypes(TypeWithAnnotations target, TypeWithState assignedValue) => target.Type.Equals(assignedValue.Type, TypeCompareKind.AllIgnoreOptions); } private void ReportNonSafetyDiagnostic(Location location) { ReportDiagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, location); } private void ReportDiagnostic(ErrorCode errorCode, SyntaxNode syntaxNode, params object[] arguments) { ReportDiagnostic(errorCode, syntaxNode.GetLocation(), arguments); } private void ReportDiagnostic(ErrorCode errorCode, Location location, params object[] arguments) { Debug.Assert(ErrorFacts.NullableWarnings.Contains(MessageProvider.Instance.GetIdForErrorCode((int)errorCode))); if (IsReachable() && !_disableDiagnostics) { Diagnostics.Add(errorCode, location, arguments); } } private void InheritNullableStateOfTrackableStruct(TypeSymbol targetType, int targetSlot, int valueSlot, bool isDefaultValue, int skipSlot = -1) { Debug.Assert(targetSlot > 0); Debug.Assert(EmptyStructTypeCache.IsTrackableStructType(targetType)); if (skipSlot < 0) { skipSlot = targetSlot; } if (!isDefaultValue && valueSlot > 0) { InheritNullableStateOfTrackableType(targetSlot, valueSlot, skipSlot); } else { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(targetType)) { InheritNullableStateOfMember(targetSlot, valueSlot, field, isDefaultValue: isDefaultValue, skipSlot); } } } private bool IsSlotMember(int slot, Symbol possibleMember) { TypeSymbol possibleBase = possibleMember.ContainingType; TypeSymbol possibleDerived = NominalSlotType(slot); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversionsWithoutNullability = _conversions.WithNullability(false); return conversionsWithoutNullability.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo) || conversionsWithoutNullability.HasBoxingConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } // 'skipSlot' is the original target slot that should be skipped in case of cycles. private void InheritNullableStateOfMember(int targetContainerSlot, int valueContainerSlot, Symbol member, bool isDefaultValue, int skipSlot) { Debug.Assert(targetContainerSlot > 0); Debug.Assert(skipSlot > 0); // Ensure member is valid for target and value. if (!IsSlotMember(targetContainerSlot, member)) return; TypeWithAnnotations fieldOrPropertyType = member.GetTypeOrReturnType(); if (fieldOrPropertyType.Type.IsReferenceType || fieldOrPropertyType.TypeKind == TypeKind.TypeParameter || fieldOrPropertyType.IsNullableType()) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { NullableFlowState value = isDefaultValue ? NullableFlowState.MaybeNull : fieldOrPropertyType.ToTypeWithState().State; int valueMemberSlot = -1; if (valueContainerSlot > 0) { valueMemberSlot = VariableSlot(member, valueContainerSlot); if (valueMemberSlot == skipSlot) { return; } value = this.State.HasValue(valueMemberSlot) ? this.State[valueMemberSlot] : NullableFlowState.NotNull; } SetStateAndTrackForFinally(ref this.State, targetMemberSlot, value); if (valueMemberSlot > 0) { InheritNullableStateOfTrackableType(targetMemberSlot, valueMemberSlot, skipSlot); } } } else if (EmptyStructTypeCache.IsTrackableStructType(fieldOrPropertyType.Type)) { int targetMemberSlot = GetOrCreateSlot(member, targetContainerSlot); if (targetMemberSlot > 0) { int valueMemberSlot = (valueContainerSlot > 0) ? GetOrCreateSlot(member, valueContainerSlot) : -1; if (valueMemberSlot == skipSlot) { return; } InheritNullableStateOfTrackableStruct(fieldOrPropertyType.Type, targetMemberSlot, valueMemberSlot, isDefaultValue: isDefaultValue, skipSlot); } } } private TypeSymbol NominalSlotType(int slot) { return _variables[slot].Symbol.GetTypeOrReturnType().Type; } /// <summary> /// Whenever assigning a variable, and that variable is not declared at the point the state is being set, /// and the new state is not <see cref="NullableFlowState.NotNull"/>, this method should be called to perform the /// state setting and to ensure the mutation is visible outside the finally block when the mutation occurs in a /// finally block. /// </summary> private void SetStateAndTrackForFinally(ref LocalState state, int slot, NullableFlowState newState) { state[slot] = newState; if (newState != NullableFlowState.NotNull && NonMonotonicState.HasValue) { var tryState = NonMonotonicState.Value; if (tryState.HasVariable(slot)) { tryState[slot] = newState.Join(tryState[slot]); NonMonotonicState = tryState; } } } protected override void JoinTryBlockState(ref LocalState self, ref LocalState other) { var tryState = other.GetStateForVariables(self.Id); Join(ref self, ref tryState); } private void InheritDefaultState(TypeSymbol targetType, int targetSlot) { Debug.Assert(targetSlot > 0); // Reset the state of any members of the target. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, targetSlot); foreach (var (variable, slot) in members) { var symbol = AsMemberOfType(targetType, variable.Symbol); SetStateAndTrackForFinally(ref this.State, slot, GetDefaultState(symbol)); InheritDefaultState(symbol.GetTypeOrReturnType().Type, slot); } members.Free(); } private NullableFlowState GetDefaultState(Symbol symbol) => ApplyUnconditionalAnnotations(symbol.GetTypeOrReturnType().ToTypeWithState(), GetRValueAnnotations(symbol)).State; private void InheritNullableStateOfTrackableType(int targetSlot, int valueSlot, int skipSlot) { Debug.Assert(targetSlot > 0); Debug.Assert(valueSlot > 0); // Clone the state for members that have been set on the value. var members = ArrayBuilder<(VariableIdentifier, int)>.GetInstance(); _variables.GetMembers(members, valueSlot); foreach (var (variable, slot) in members) { var member = variable.Symbol; Debug.Assert(member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property || member.Kind == SymbolKind.Event); InheritNullableStateOfMember(targetSlot, valueSlot, member, isDefaultValue: false, skipSlot); } members.Free(); } protected override LocalState TopState() { var state = LocalState.ReachableState(_variables); state.PopulateAll(this); return state; } protected override LocalState UnreachableState() { return LocalState.UnreachableState(_variables); } protected override LocalState ReachableBottomState() { // Create a reachable state in which all variables are known to be non-null. return LocalState.ReachableState(_variables); } private void EnterParameters() { if (!(CurrentSymbol is MethodSymbol methodSymbol)) { return; } if (methodSymbol is SynthesizedRecordConstructor) { if (_hasInitialState) { // A record primary constructor's parameters are entered before analyzing initializers. // On the second pass, the correct parameter states (potentially modified by initializers) // are contained in the initial state. return; } } else if (methodSymbol.IsConstructor()) { if (!_hasInitialState) { // For most constructors, we only enter parameters after analyzing initializers. return; } } // The partial definition part may include optional parameters whose default values we want to simulate assigning at the beginning of the method methodSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol; var methodParameters = methodSymbol.Parameters; var signatureParameters = (_useDelegateInvokeParameterTypes ? _delegateInvokeMethod! : methodSymbol).Parameters; // save a state representing the possibility that parameter default values were not assigned to the parameters. var parameterDefaultsNotAssignedState = State.Clone(); for (int i = 0; i < methodParameters.Length; i++) { var parameter = methodParameters[i]; // In error scenarios, the method can potentially have more parameters than the signature. If so, use the parameter type for those // errored parameters var parameterType = i >= signatureParameters.Length ? parameter.TypeWithAnnotations : signatureParameters[i].TypeWithAnnotations; EnterParameter(parameter, parameterType); } Join(ref State, ref parameterDefaultsNotAssignedState); } private void EnterParameter(ParameterSymbol parameter, TypeWithAnnotations parameterType) { _variables.SetType(parameter, parameterType); if (parameter.RefKind != RefKind.Out) { int slot = GetOrCreateSlot(parameter); Debug.Assert(!IsConditionalState); if (slot > 0) { var state = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations).State; this.State[slot] = state; if (EmptyStructTypeCache.IsTrackableStructType(parameterType.Type)) { InheritNullableStateOfTrackableStruct( parameterType.Type, slot, valueSlot: -1, isDefaultValue: parameter.ExplicitDefaultConstantValue?.IsNull == true); } } } } public override BoundNode? VisitParameterEqualsValue(BoundParameterEqualsValue equalsValue) { var parameter = equalsValue.Parameter; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterLValueType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); var resultType = VisitOptionalImplicitConversion( equalsValue.Value, parameterLValueType, useLegacyWarnings: false, trackMembers: false, assignmentKind: AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, equalsValue.Value.Syntax.Location); return null; } internal static TypeWithState GetParameterState(TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { if ((parameterAnnotations & FlowAnalysisAnnotations.AllowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.MaybeDefault); } if ((parameterAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) { return TypeWithState.Create(parameterType.Type, NullableFlowState.NotNull); } return parameterType.ToTypeWithState(); } public sealed override BoundNode? VisitReturnStatement(BoundReturnStatement node) { Debug.Assert(!IsConditionalState); var expr = node.ExpressionOpt; if (expr == null) { EnforceDoesNotReturn(node.Syntax); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return null; } // Should not convert to method return type when inferring return type (when _returnTypesOpt != null). if (_returnTypesOpt == null && TryGetReturnType(out TypeWithAnnotations returnType, out FlowAnalysisAnnotations returnAnnotations)) { if (node.RefKind == RefKind.None && returnType.Type.SpecialType == SpecialType.System_Boolean) { // visit the expression without unsplitting, then check parameters marked with flow analysis attributes Visit(expr); } else { TypeWithState returnState; if (node.RefKind == RefKind.None) { returnState = VisitOptionalImplicitConversion(expr, returnType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); } else { // return ref expr; returnState = VisitRefExpression(expr, returnType); } // If the return has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(returnState, ToInwardAnnotations(returnAnnotations), node.Syntax.Location, boundValueOpt: expr); } } else { var result = VisitRvalueWithState(expr); if (_returnTypesOpt != null) { _returnTypesOpt.Add((node, result.ToTypeWithAnnotations(compilation))); } } EnforceDoesNotReturn(node.Syntax); if (IsConditionalState) { var joinedState = this.StateWhenTrue.Clone(); Join(ref joinedState, ref this.StateWhenFalse); PendingBranches.Add(new PendingBranch(node, joinedState, label: null, this.IsConditionalState, this.StateWhenTrue, this.StateWhenFalse)); } else { PendingBranches.Add(new PendingBranch(node, this.State, label: null)); } Unsplit(); if (CurrentSymbol is MethodSymbol method) { EnforceNotNullIfNotNull(node.Syntax, this.State, method.Parameters, method.ReturnNotNullIfParameterNotNull, ResultType.State, outputParam: null); } SetUnreachable(); return null; } private TypeWithState VisitRefExpression(BoundExpression expr, TypeWithAnnotations destinationType) { Visit(expr); TypeWithState resultType = ResultType; if (!expr.IsSuppressed && RemoveConversion(expr, includeExplicitConversions: false).expression.Kind != BoundKind.ThrowExpression) { var lvalueResultType = LvalueResultType; if (IsNullabilityMismatch(lvalueResultType, destinationType)) { // declared types must match ReportNullabilityMismatchInAssignment(expr.Syntax, lvalueResultType, destinationType); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(expr, destinationType, resultType, useLegacyWarnings: false); } } return resultType; } private bool TryGetReturnType(out TypeWithAnnotations type, out FlowAnalysisAnnotations annotations) { var method = CurrentSymbol as MethodSymbol; if (method is null) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } var delegateOrMethod = _useDelegateInvokeReturnType ? _delegateInvokeMethod! : method; var returnType = delegateOrMethod.ReturnTypeWithAnnotations; Debug.Assert((object)returnType != LambdaSymbol.ReturnTypeIsBeingInferred); if (returnType.IsVoidType()) { type = default; annotations = FlowAnalysisAnnotations.None; return false; } if (!method.IsAsync) { annotations = delegateOrMethod.ReturnTypeFlowAnalysisAnnotations; type = ApplyUnconditionalAnnotations(returnType, annotations); return true; } if (method.IsAsyncEffectivelyReturningGenericTask(compilation)) { type = ((NamedTypeSymbol)returnType.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); annotations = FlowAnalysisAnnotations.None; return true; } type = default; annotations = FlowAnalysisAnnotations.None; return false; } public override BoundNode? VisitLocal(BoundLocal node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); var type = GetDeclaredLocalResult(local); if (!node.Type.Equals(type.Type, TypeCompareKind.ConsiderEverything | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames)) { // When the local is used before or during initialization, there can potentially be a mismatch between node.LocalSymbol.Type and node.Type. We // need to prefer node.Type as we shouldn't be changing the type of the BoundLocal node during rewrite. // https://github.com/dotnet/roslyn/issues/34158 Debug.Assert(node.Type.IsErrorType() || type.Type.IsErrorType()); type = TypeWithAnnotations.Create(node.Type, type.NullableAnnotation); } SetResult(node, GetAdjustedResult(type.ToTypeWithState(), slot), type); SplitIfBooleanConstant(node); return null; } public override BoundNode? VisitBlock(BoundBlock node) { DeclareLocals(node.Locals); VisitStatementsWithLocalFunctions(node); return null; } private void VisitStatementsWithLocalFunctions(BoundBlock block) { // Since the nullable flow state affects type information, and types can be queried by // the semantic model, there needs to be a single flow state input to a local function // that cannot be path-dependent. To decide the local starting state we Meet the state // of captured variables from all the uses of the local function, computing the // conservative combination of all potential starting states. // // For performance we split the analysis into two phases: the first phase where we // analyze everything except the local functions, hoping to visit all of the uses of the // local function, and then a pass where we visit the local functions. If there's no // recursion or calls between the local functions, the starting state of the local // function should be stable and we don't need a second pass. if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) { // First visit everything else foreach (var stmt in block.Statements) { if (stmt.Kind != BoundKind.LocalFunctionStatement) { VisitStatement(stmt); } } // Now visit the local function bodies foreach (var stmt in block.Statements) { if (stmt is BoundLocalFunctionStatement localFunc) { VisitLocalFunctionStatement(localFunc); } } } else { foreach (var stmt in block.Statements) { VisitStatement(stmt); } } } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var localFunc = node.Symbol; var localFunctionState = GetOrCreateLocalFuncUsages(localFunc); // The starting state is the top state, but with captured // variables set according to Joining the state at all the // local function use sites var state = TopState(); var startingState = localFunctionState.StartingState; startingState.ForEach( (slot, variables) => { var symbol = variables[variables.RootSlot(slot)].Symbol; if (Symbol.IsCaptured(symbol, localFunc)) { state[slot] = startingState[slot]; } }, _variables); localFunctionState.Visited = true; AnalyzeLocalFunctionOrLambda( node, localFunc, state, delegateInvokeMethod: null, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false); SetInvalidResult(); return null; } private Variables GetOrCreateNestedFunctionVariables(Variables container, MethodSymbol lambdaOrLocalFunction) { _nestedFunctionVariables ??= PooledDictionary<MethodSymbol, Variables>.GetInstance(); if (!_nestedFunctionVariables.TryGetValue(lambdaOrLocalFunction, out var variables)) { variables = container.CreateNestedMethodScope(lambdaOrLocalFunction); _nestedFunctionVariables.Add(lambdaOrLocalFunction, variables); } Debug.Assert((object?)variables.Container == container); return variables; } private void AnalyzeLocalFunctionOrLambda( IBoundLambdaOrFunction lambdaOrFunction, MethodSymbol lambdaOrFunctionSymbol, LocalState state, MethodSymbol? delegateInvokeMethod, bool useDelegateInvokeParameterTypes, bool useDelegateInvokeReturnType) { Debug.Assert(!useDelegateInvokeParameterTypes || delegateInvokeMethod is object); Debug.Assert(!useDelegateInvokeReturnType || delegateInvokeMethod is object); var oldSymbol = this.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; var oldState = this.State; _variables = GetOrCreateNestedFunctionVariables(_variables, lambdaOrFunctionSymbol); this.State = state.CreateNestedMethodState(_variables); var previousSlot = _snapshotBuilderOpt?.EnterNewWalker(lambdaOrFunctionSymbol) ?? -1; try { var oldPending = SavePending(); EnterParameters(); var oldPending2 = SavePending(); // If this is an iterator, there's an implicit branch before the first statement // of the function where the enumerable is returned. if (lambdaOrFunctionSymbol.IsIterator) { PendingBranches.Add(new PendingBranch(null, this.State, null)); } VisitAlways(lambdaOrFunction.Body); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = oldSymbol; } protected override void VisitLocalFunctionUse( LocalFunctionSymbol symbol, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { // Do not use this overload in NullableWalker. Use the overload below instead. throw ExceptionUtilities.Unreachable; } private void VisitLocalFunctionUse(LocalFunctionSymbol symbol) { Debug.Assert(!IsConditionalState); var localFunctionState = GetOrCreateLocalFuncUsages(symbol); var state = State.GetStateForVariables(localFunctionState.StartingState.Id); if (Join(ref localFunctionState.StartingState, ref state) && localFunctionState.Visited) { // If the starting state of the local function has changed and we've already visited // the local function, we need another pass stateChangedAfterUse = true; } } public override BoundNode? VisitDoStatement(BoundDoStatement node) { DeclareLocals(node.Locals); return base.VisitDoStatement(node); } public override BoundNode? VisitWhileStatement(BoundWhileStatement node) { DeclareLocals(node.Locals); return base.VisitWhileStatement(node); } public override BoundNode? VisitWithExpression(BoundWithExpression withExpr) { Debug.Assert(!IsConditionalState); var receiver = withExpr.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); var resultType = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? ResultType.ToTypeWithAnnotations(compilation); var resultState = ApplyUnconditionalAnnotations(resultType.ToTypeWithState(), GetRValueAnnotations(withExpr.CloneMethod)); var resultSlot = GetOrCreatePlaceholderSlot(withExpr); // carry over the null state of members of 'receiver' to the result of the with-expression. TrackNullableStateForAssignment(receiver, resultType, resultSlot, resultState, MakeSlot(receiver)); // use the declared nullability of Clone() for the top-level nullability of the result of the with-expression. SetResult(withExpr, resultState, resultType); VisitObjectCreationInitializer(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // Note: this does not account for the scenario where `Clone()` returns maybe-null and the with-expression has no initializers. // Tracking in https://github.com/dotnet/roslyn/issues/44759 return null; } public override BoundNode? VisitForStatement(BoundForStatement node) { DeclareLocals(node.OuterLocals); DeclareLocals(node.InnerLocals); return base.VisitForStatement(node); } public override BoundNode? VisitForEachStatement(BoundForEachStatement node) { DeclareLocals(node.IterationVariables); return base.VisitForEachStatement(node); } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { DeclareLocals(node.Locals); Visit(node.AwaitOpt); return base.VisitUsingStatement(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { Visit(node.AwaitOpt); return base.VisitUsingLocalDeclarations(node); } public override BoundNode? VisitFixedStatement(BoundFixedStatement node) { DeclareLocals(node.Locals); return base.VisitFixedStatement(node); } public override BoundNode? VisitConstructorMethodBody(BoundConstructorMethodBody node) { DeclareLocals(node.Locals); return base.VisitConstructorMethodBody(node); } private void DeclareLocal(LocalSymbol local) { if (local.DeclarationKind != LocalDeclarationKind.None) { int slot = GetOrCreateSlot(local); if (slot > 0) { this.State[slot] = GetDefaultState(ref this.State, slot); InheritDefaultState(GetDeclaredLocalResult(local).Type, slot); } } } private void DeclareLocals(ImmutableArray<LocalSymbol> locals) { foreach (var local in locals) { DeclareLocal(local); } } public override BoundNode? VisitLocalDeclaration(BoundLocalDeclaration node) { var local = node.LocalSymbol; int slot = GetOrCreateSlot(local); // We need visit the optional arguments so that we can return nullability information // about them, but we don't want to communicate any information about anything underneath. // Additionally, tests like Scope_DeclaratorArguments_06 can have conditional expressions // in the optional arguments that can leave us in a split state, so we want to make sure // we are not in a conditional state after. Debug.Assert(!IsConditionalState); var oldDisable = _disableDiagnostics; _disableDiagnostics = true; var currentState = State; VisitAndUnsplitAll(node.ArgumentsOpt); _disableDiagnostics = oldDisable; SetState(currentState); if (node.DeclaredTypeOpt != null) { VisitTypeExpression(node.DeclaredTypeOpt); } var initializer = node.InitializerOpt; if (initializer is null) { return null; } TypeWithAnnotations type = local.TypeWithAnnotations; TypeWithState valueType; bool inferredType = node.InferredType; if (local.IsRef) { valueType = VisitRefExpression(initializer, type); } else { valueType = VisitOptionalImplicitConversion(initializer, targetTypeOpt: inferredType ? default : type, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } if (inferredType) { if (valueType.HasNullType) { Debug.Assert(type.Type.IsErrorType()); valueType = type.ToTypeWithState(); } type = valueType.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local, type); if (node.DeclaredTypeOpt != null) { SetAnalyzedNullability(node.DeclaredTypeOpt, new VisitResult(type.ToTypeWithState(), type), true); } } TrackNullableStateForAssignment(initializer, type, slot, valueType, MakeSlot(initializer)); return null; } protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { Debug.Assert(!IsConditionalState); SetInvalidResult(); _ = base.VisitExpressionWithoutStackGuard(node); TypeWithState resultType = ResultType; #if DEBUG // Verify Visit method set _result. Debug.Assert((object?)resultType.Type != _invalidType.Type); Debug.Assert(AreCloseEnough(resultType.Type, node.Type)); #endif if (ShouldMakeNotNullRvalue(node)) { var result = resultType.WithNotNullState(); SetResult(node, result, LvalueResultType); } return null; } #if DEBUG // For asserts only. private static bool AreCloseEnough(TypeSymbol? typeA, TypeSymbol? typeB) { // https://github.com/dotnet/roslyn/issues/34993: We should be able to tighten this to ensure that we're actually always returning the same type, // not error if one is null or ignoring certain types if ((object?)typeA == typeB) { return true; } if (typeA is null || typeB is null) { return typeA?.IsErrorType() != false && typeB?.IsErrorType() != false; } return canIgnoreAnyType(typeA) || canIgnoreAnyType(typeB) || typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(t => canIgnoreAnyType(t.Type)); } } private static bool AreCloseEnough(Symbol original, Symbol updated) { // When https://github.com/dotnet/roslyn/issues/38195 is fixed, this workaround needs to be removed if (original is ConstructedMethodSymbol || updated is ConstructedMethodSymbol) { return AreCloseEnough(original.OriginalDefinition, updated.OriginalDefinition); } return (original, updated) switch { (LambdaSymbol l, NamedTypeSymbol n) _ when n.IsDelegateType() => AreLambdaAndNewDelegateSimilar(l, n), (FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var oi } originalField, FieldSymbol { ContainingType: { IsTupleType: true }, TupleElementIndex: var ui } updatedField) => originalField.Type.Equals(updatedField.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) && oi == ui, _ => original.Equals(updated, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames) }; } #endif private static bool AreLambdaAndNewDelegateSimilar(LambdaSymbol l, NamedTypeSymbol n) { var invokeMethod = n.DelegateInvokeMethod; return invokeMethod!.Parameters.SequenceEqual(l.Parameters, (p1, p2) => p1.Type.Equals(p2.Type, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) && invokeMethod.ReturnType.Equals(l.ReturnType, TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames); } public override BoundNode? Visit(BoundNode? node) { return Visit(node, expressionIsRead: true); } private BoundNode VisitLValue(BoundNode node) { return Visit(node, expressionIsRead: false); } private BoundNode Visit(BoundNode? node, bool expressionIsRead) { bool originalExpressionIsRead = _expressionIsRead; _expressionIsRead = expressionIsRead; TakeIncrementalSnapshot(node); var result = base.Visit(node); _expressionIsRead = originalExpressionIsRead; return result; } protected override void VisitStatement(BoundStatement statement) { SetInvalidResult(); base.VisitStatement(statement); SetInvalidResult(); } public override BoundNode? VisitObjectCreationExpression(BoundObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { // This method is only involved in method inference with unbound lambdas. // The diagnostics on arguments are reported by VisitObjectCreationExpression. SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); return null; } private void VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == true; if (EmptyStructTypeCache.IsTrackableStructType(type)) { var containingType = constructor?.ContainingType; if (containingType?.IsTupleType == true && !isDefaultValueTypeConstructor) { // new System.ValueTuple<T1, ..., TN>(e1, ..., eN) TrackNullableStateOfTupleElements(slot, containingType, arguments, argumentTypes, boundObjectCreationExpression!.ArgsToParamsOpt, useRestField: true); } else { InheritNullableStateOfTrackableStruct( type, slot, valueSlot: -1, isDefaultValue: isDefaultValueTypeConstructor); } } else if (type.IsNullableType()) { if (isDefaultValueTypeConstructor) { // a nullable value type created with its default constructor is by definition null resultState = NullableFlowState.MaybeNull; } else if (constructor?.ParameterCount == 1) { // if we deal with one-parameter ctor that takes underlying, then Value state is inferred from the argument. var parameterType = constructor.ParameterTypesWithAnnotations[0]; if (AreNullableAndUnderlyingTypes(type, parameterType.Type, out TypeWithAnnotations underlyingType)) { var operand = arguments[0]; int valueSlot = MakeSlot(operand); if (valueSlot > 0) { TrackNullableStateOfNullableValue(slot, type, operand, underlyingType.ToTypeWithState(), valueSlot); } } } } this.State[slot] = resultState; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); Debug.Assert(reinferredMethod is object); if (node.ImplicitReceiverOpt != null) { Debug.Assert(node.ImplicitReceiverOpt.Kind == BoundKind.ObjectOrCollectionValuePlaceholder); SetAnalyzedNullability(node.ImplicitReceiverOpt, new VisitResult(node.ImplicitReceiverOpt.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull)); } SetUnknownResultNullability(node); SetUpdatedSymbol(node, node.AddMethod, reinferredMethod); } private void SetNotNullResult(BoundExpression node) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); } /// <summary> /// Returns true if the type is a struct with no fields or properties. /// </summary> protected override bool IsEmptyStructType(TypeSymbol type) { if (type.TypeKind != TypeKind.Struct) { return false; } // EmptyStructTypeCache.IsEmptyStructType() returns false // if there are non-cyclic fields. if (!_emptyStructTypeCache.IsEmptyStructType(type)) { return false; } if (type.SpecialType != SpecialType.None) { return true; } var members = ((NamedTypeSymbol)type).GetMembersUnordered(); // EmptyStructTypeCache.IsEmptyStructType() returned true. If there are fields, // at least one of those fields must be cyclic, so treat the type as empty. if (members.Any(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(m => m.Kind == SymbolKind.Property)) { return false; } return true; } private int GetOrCreatePlaceholderSlot(BoundExpression node) { Debug.Assert(node.Type is object); if (IsEmptyStructType(node.Type)) { return -1; } return GetOrCreatePlaceholderSlot(node, TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated)); } private int GetOrCreatePlaceholderSlot(object identifier, TypeWithAnnotations type) { _placeholderLocalsOpt ??= PooledDictionary<object, PlaceholderLocal>.GetInstance(); if (!_placeholderLocalsOpt.TryGetValue(identifier, out var placeholder)) { placeholder = new PlaceholderLocal(CurrentSymbol, identifier, type); _placeholderLocalsOpt.Add(identifier, placeholder); } Debug.Assert((object)placeholder != null); return GetOrCreateSlot(placeholder, forceSlotEvenIfEmpty: true); } public override BoundNode? VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { Debug.Assert(!IsConditionalState); Debug.Assert(node.Type.IsAnonymousType); var anonymousType = (NamedTypeSymbol)node.Type; var arguments = node.Arguments; var argumentTypes = arguments.SelectAsArray((arg, self) => self.VisitRvalueWithState(arg), this); var argumentsWithAnnotations = argumentTypes.SelectAsArray(arg => arg.ToTypeWithAnnotations(compilation)); if (argumentsWithAnnotations.All(argType => argType.HasType)) { anonymousType = AnonymousTypeManager.ConstructAnonymousTypeSymbol(anonymousType, argumentsWithAnnotations); int receiverSlot = GetOrCreatePlaceholderSlot(node); int currentDeclarationIndex = 0; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var argumentType = argumentTypes[i]; var property = AnonymousTypeManager.GetAnonymousTypeProperty(anonymousType, i); if (property.Type.SpecialType != SpecialType.System_Void) { // A void element results in an error type in the anonymous type but not in the property's container! // To avoid failing an assertion later, we skip them. var slot = GetOrCreateSlot(property, receiverSlot); TrackNullableStateForAssignment(argument, property.TypeWithAnnotations, slot, argumentType, MakeSlot(argument)); var currentDeclaration = getDeclaration(node, property, ref currentDeclarationIndex); if (currentDeclaration is object) { TakeIncrementalSnapshot(currentDeclaration); SetAnalyzedNullability(currentDeclaration, new VisitResult(argumentType, property.TypeWithAnnotations)); } } } } SetResultType(node, TypeWithState.Create(anonymousType, NullableFlowState.NotNull)); return null; static BoundAnonymousPropertyDeclaration? getDeclaration(BoundAnonymousObjectCreationExpression node, PropertySymbol currentProperty, ref int currentDeclarationIndex) { if (currentDeclarationIndex >= node.Declarations.Length) { return null; } var currentDeclaration = node.Declarations[currentDeclarationIndex]; if (currentDeclaration.Property.MemberIndexOpt == currentProperty.MemberIndexOpt) { currentDeclarationIndex++; return currentDeclaration; } return null; } } public override BoundNode? VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } var initialization = node.InitializerOpt; if (initialization is null) { SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return null; } TakeIncrementalSnapshot(initialization); var expressions = ArrayBuilder<BoundExpression>.GetInstance(initialization.Initializers.Length); GetArrayElements(initialization, expressions); int n = expressions.Count; // Consider recording in the BoundArrayCreation // whether the array was implicitly typed, rather than relying on syntax. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(n); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); foreach (var expression in expressions) { // collect expressions, conversions and result types (BoundExpression expressionNoConversion, Conversion conversion) = RemoveConversion(expression, includeExplicitConversions: false); expressionsNoConversions.Add(expressionNoConversion); conversions.Add(conversion); SnapshotWalkerThroughConversionGroup(expression, expressionNoConversion); var resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } TypeWithAnnotations inferredType = (bestType is null) ? elementType.SetUnknownNullabilityForReferenceTypes() : TypeWithAnnotations.Create(bestType); if (bestType is object) { // Convert elements to best type to determine element top-level nullability and to report nested nullability warnings for (int i = 0; i < n; i++) { var expressionNoConversion = expressionsNoConversions[i]; var expression = GetConversionIfApplicable(expressions[i], expressionNoConversion); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: true, reportTopLevelWarnings: false); } // Set top-level nullability on inferred element type var elementState = BestTypeInferrer.GetNullableState(resultTypes); inferredType = TypeWithState.Create(inferredType.Type, elementState).ToTypeWithAnnotations(compilation); for (int i = 0; i < n; i++) { // Report top-level warnings _ = VisitConversion(conversionOpt: null, conversionOperand: expressionsNoConversions[i], Conversion.Identity, targetTypeWithNullability: inferredType, operandType: resultTypes[i], checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportRemainingWarnings: false); } } else { // We need to ensure that we're tracking the inferred type with nullability of any conversions that // were stripped off. for (int i = 0; i < n; i++) { TrackAnalyzedNullabilityThroughConversionGroup(inferredType.ToTypeWithState(), expressions[i] as BoundConversion, expressionsNoConversions[i]); } } expressionsNoConversions.Free(); conversions.Free(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <summary> /// Applies analysis similar to <see cref="VisitArrayCreation"/>. /// The expressions returned from a lambda are not converted though, so we'll have to classify fresh conversions. /// Note: even if some conversions fail, we'll proceed to infer top-level nullability. That is reasonable in common cases. /// </summary> internal static TypeWithAnnotations BestTypeForLambdaReturns( ArrayBuilder<(BoundExpression, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: null, returnTypesOpt: null, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null); int n = returns.Count; var resultTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(n); var placeholdersBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var (returnExpr, resultType) = returns[i]; resultTypes.Add(resultType); placeholdersBuilder.Add(CreatePlaceholderIfNecessary(returnExpr, resultType)); } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var placeholders = placeholdersBuilder.ToImmutableAndFree(); TypeSymbol? bestType = BestTypeInferrer.InferBestType(placeholders, walker._conversions, ref discardedUseSiteInfo); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, ref discardedUseSiteInfo); resultTypes[i] = walker.VisitConversion(conversionOpt: null, placeholder, conversion, bestTypeWithObliviousAnnotation, resultTypes[i].ToTypeWithState(), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Return, reportRemainingWarnings: false, reportTopLevelWarnings: false).ToTypeWithAnnotations(binder.Compilation); } // Set top-level nullability on inferred type inferredType = TypeWithAnnotations.Create(bestType, BestTypeInferrer.GetNullableAnnotation(resultTypes)); } else { inferredType = default; } resultTypes.Free(); walker.Free(); return inferredType; } private static void GetArrayElements(BoundArrayInitialization node, ArrayBuilder<BoundExpression> builder) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { GetArrayElements((BoundArrayInitialization)child, builder); } else { builder.Add(child); } } } public override BoundNode? VisitArrayAccess(BoundArrayAccess node) { Debug.Assert(!IsConditionalState); Visit(node.Expression); Debug.Assert(!IsConditionalState); Debug.Assert(!node.Expression.Type!.IsValueType); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(node.Expression); var type = ResultType.Type as ArrayTypeSymbol; foreach (var i in node.Indices) { VisitRvalue(i); } TypeWithAnnotations result; if (node.Indices.Length == 1 && TypeSymbol.Equals(node.Indices[0].Type, compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything2)) { result = TypeWithAnnotations.Create(type); } else { result = type?.ElementTypeWithAnnotations ?? default; } SetLvalueResultType(node, result); return null; } private TypeWithState InferResultNullability(BinaryOperatorKind operatorKind, MethodSymbol? methodOpt, TypeSymbol resultType, TypeWithState leftType, TypeWithState rightType) { NullableFlowState resultState = NullableFlowState.NotNull; if (operatorKind.IsUserDefined()) { if (methodOpt?.ParameterCount == 2) { if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { return GetLiftedReturnType(methodOpt.ReturnTypeWithAnnotations, leftType.State.Join(rightType.State)); } var resultTypeWithState = GetReturnTypeWithState(methodOpt); if ((leftType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[0].Name)) || (rightType.IsNotNull && methodOpt.ReturnNotNullIfParameterNotNull.Contains(methodOpt.Parameters[1].Name))) { resultTypeWithState = resultTypeWithState.WithNotNullState(); } return resultTypeWithState; } } else if (!operatorKind.IsDynamic() && !resultType.IsValueType) { switch (operatorKind.Operator() | operatorKind.OperandTypes()) { case BinaryOperatorKind.DelegateCombination: resultState = leftType.State.Meet(rightType.State); break; case BinaryOperatorKind.DelegateRemoval: resultState = NullableFlowState.MaybeNull; // Delegate removal can produce null. break; default: resultState = NullableFlowState.NotNull; break; } } if (operatorKind.IsLifted() && !operatorKind.IsComparison()) { resultState = leftType.State.Join(rightType.State); } return TypeWithState.Create(resultType, resultState); } protected override void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); var (leftOperand, leftConversion) = RemoveConversion(binary.Left, includeExplicitConversions: false); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(leftOperand, out var conditionalStateWhenNotNull) && CanPropagateStateWhenNotNull(leftConversion) && binary.OperatorKind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // Consider the following two scenarios: // `a?.b(x = new object()) == c.d(x = null)` // `x` is maybe-null after expression // `a?.b(x = null) == c.d(x = new object())` // `x` is not-null after expression // In this scenario, we visit the RHS twice: // (1) Once using the single "stateWhenNotNull" after the LHS, in order to update the "stateWhenNotNull" with the effects of the RHS // (2) Once using the "worst case" state after the LHS for diagnostics and public API // After the two visits of the RHS, we may set a conditional state using the state after (1) as the StateWhenTrue and the state after (2) as the StateWhenFalse. // Depending on whether `==` or `!=` was used, and depending on the value of the RHS, we may then swap the StateWhenTrue with the StateWhenFalse. var oldDisableDiagnostics = _disableDiagnostics; _disableDiagnostics = true; var stateAfterLeft = this.State; SetState(getUnconditionalStateWhenNotNull(rightOperand, conditionalStateWhenNotNull)); VisitRvalue(rightOperand); var stateWhenNotNull = this.State; _disableDiagnostics = oldDisableDiagnostics; // Now visit the right side for public API and diagnostics using the worst-case state from the LHS. // Note that we do this visit last to try and make sure that the "visit for public API" overwrites walker state recorded during previous visits where possible. SetState(stateAfterLeft); var rightType = VisitRvalueWithState(rightOperand); ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); if (isKnownNullOrNotNull(rightOperand, rightType)) { var isNullConstant = rightOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } if (stack.Count == 0) { return; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } while (true) { if (!learnFromConditionalAccessOrBoolConstant()) { Unsplit(); // VisitRvalue does this UseRvalueOnly(leftOperand); // drop lvalue part AfterLeftChildHasBeenVisited(leftOperand, leftConversion, binary); } if (stack.Count == 0) { break; } leftOperand = binary; leftConversion = Conversion.Identity; binary = stack.Pop(); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; static bool isKnownNullOrNotNull(BoundExpression expr, TypeWithState resultType) { return resultType.State.IsNotNull() || expr.ConstantValue is object; } LocalState getUnconditionalStateWhenNotNull(BoundExpression otherOperand, PossiblyConditionalState conditionalStateWhenNotNull) { LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else if (isEquals(binary) && otherOperand.ConstantValue is { IsBoolean: true, BooleanValue: var boolValue }) { // can preserve conditional state from `.TryGetValue` in `dict?.TryGetValue(key, out value) == true`, // but not in `dict?.TryGetValue(key, out value) != false` stateWhenNotNull = boolValue ? conditionalStateWhenNotNull.StateWhenTrue : conditionalStateWhenNotNull.StateWhenFalse; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } return stateWhenNotNull; } // Returns true if `binary.Right` was visited by the call. bool learnFromConditionalAccessOrBoolConstant() { if (binary.OperatorKind.Operator() is not (BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual)) { return false; } var leftResult = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); // `true == a?.b(out x)` if (isKnownNullOrNotNull(leftOperand, leftResult) && CanPropagateStateWhenNotNull(rightConversion) && TryVisitConditionalAccess(rightOperand, out var conditionalStateWhenNotNull)) { ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftResult, rightOperand, rightConversion, rightType: ResultType, binary); var stateWhenNotNull = getUnconditionalStateWhenNotNull(leftOperand, conditionalStateWhenNotNull); var isNullConstant = leftOperand.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // can only learn from a bool constant operand here if it's using the built in `bool operator ==(bool left, bool right)` if (binary.OperatorKind.IsUserDefined()) { return false; } // `(x != null) == true` if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); // record result for the right SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); } // `true == (x != null)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); UseRvalueOnly(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { return false; } // record result for the binary Debug.Assert(binary.Type.SpecialType == SpecialType.System_Boolean); SetResult(binary, TypeWithState.ForType(binary.Type), TypeWithAnnotations.Create(binary.Type)); return true; } } private void ReinferBinaryOperatorAndSetResult( BoundExpression leftOperand, Conversion leftConversion, TypeWithState leftType, BoundExpression rightOperand, Conversion rightConversion, TypeWithState rightType, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); // At this point, State.Reachable may be false for // invalid code such as `s + throw new Exception()`. var method = binary.Method; if (binary.OperatorKind.IsUserDefined() && method?.ParameterCount == 2) { // Update method based on inferred operand type. TypeSymbol methodContainer = method.ContainingType; bool isLifted = binary.OperatorKind.IsLifted(); TypeWithState leftUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, leftType); TypeWithState rightUnderlyingType = GetNullableUnderlyingTypeIfNecessary(isLifted, rightType); TypeSymbol? asMemberOfType = getTypeIfContainingType(methodContainer, leftUnderlyingType.Type) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { method = (MethodSymbol)AsMemberOfType(asMemberOfType, method); } // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameters = method.Parameters; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } else { // Assume this is a built-in operator in which case the parameter types are unannotated. visitOperandConversion(binary.Left, leftOperand, leftConversion, leftType); visitOperandConversion(binary.Right, rightOperand, rightConversion, rightType); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, TypeWithState operandType) { if (expr.Type is null) { Debug.Assert(operand == expr); } else { _ = VisitConversion( expr as BoundConversion, operand, conversion, TypeWithAnnotations.Create(expr.Type), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument); } } } Debug.Assert(!IsConditionalState); // For nested binary operators, this can be the only time they're visited due to explicit stack used in AbstractFlowPass.VisitBinaryOperator, // so we need to set the flow-analyzed type here. var inferredResult = InferResultNullability(binary.OperatorKind, method, binary.Type, leftType, rightType); SetResult(binary, inferredResult, inferredResult.ToTypeWithAnnotations(compilation)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, ref discardedUseSiteInfo); if (conversion.Exists && !conversion.IsExplicit) { return derivedType; } return null; } } private void AfterLeftChildHasBeenVisited( BoundExpression leftOperand, Conversion leftConversion, BoundBinaryOperator binary) { Debug.Assert(!IsConditionalState); var leftType = ResultType; var (rightOperand, rightConversion) = RemoveConversion(binary.Right, includeExplicitConversions: false); VisitRvalue(rightOperand); var rightType = ResultType; ReinferBinaryOperatorAndSetResult(leftOperand, leftConversion, leftType, rightOperand, rightConversion, rightType, binary); BinaryOperatorKind op = binary.OperatorKind.Operator(); if (op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) { // learn from null constant BoundExpression? operandComparedToNull = null; if (binary.Right.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Left; } else if (binary.Left.ConstantValue?.IsNull == true) { operandComparedToNull = binary.Right; } if (operandComparedToNull != null) { // Set all nested conditional slots. For example in a?.b?.c we'll set a, b, and c. bool nonNullCase = op != BinaryOperatorKind.Equal; // true represents WhenTrue splitAndLearnFromNonNullTest(operandComparedToNull, whenTrue: nonNullCase); // `x == null` and `x != null` are pure null tests so update the null-state in the alternative branch too LearnFromNullTest(operandComparedToNull, ref nonNullCase ? ref StateWhenFalse : ref StateWhenTrue); return; } } // learn from comparison between non-null and maybe-null, possibly updating maybe-null to non-null BoundExpression? operandComparedToNonNull = null; if (leftType.IsNotNull && rightType.MayBeNull) { operandComparedToNonNull = binary.Right; } else if (rightType.IsNotNull && leftType.MayBeNull) { operandComparedToNonNull = binary.Left; } if (operandComparedToNonNull != null) { switch (op) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThanOrEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: true); return; case BinaryOperatorKind.NotEqual: operandComparedToNonNull = SkipReferenceConversions(operandComparedToNonNull); splitAndLearnFromNonNullTest(operandComparedToNonNull, whenTrue: false); return; }; } void splitAndLearnFromNonNullTest(BoundExpression operandComparedToNonNull, bool whenTrue) { var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(operandComparedToNonNull, slotBuilder); if (slotBuilder.Count != 0) { Split(); ref LocalState stateToUpdate = ref whenTrue ? ref this.StateWhenTrue : ref this.StateWhenFalse; MarkSlotsAsNotNull(slotBuilder, ref stateToUpdate); } slotBuilder.Free(); } } protected override bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref LocalState shortCircuitState) { var result = base.VisitInterpolatedStringHandlerParts(node, usesBoolReturns, firstPartIsConditional, ref shortCircuitState); SetNotNullResult(node); return result; } protected override void VisitInterpolatedStringBinaryOperatorNode(BoundBinaryOperator node) { SetNotNullResult(node); } /// <summary> /// If we learn that the operand is non-null, we can infer that certain /// sub-expressions were also non-null. /// Get all nested conditional slots for those sub-expressions. For example in a?.b?.c we'll set a, b, and c. /// Only returns slots for tracked expressions. /// </summary> /// <remarks>https://github.com/dotnet/roslyn/issues/53397 This method should potentially be removed.</remarks> private void GetSlotsToMarkAsNotNullable(BoundExpression operand, ArrayBuilder<int> slotBuilder) { Debug.Assert(operand != null); var previousConditionalAccessSlot = _lastConditionalAccessSlot; try { while (true) { // Due to the nature of binding, if there are conditional access they will be at the top of the bound tree, // potentially with a conversion on top of it. We go through any conditional accesses, adding slots for the // conditional receivers if they have them. If we ever get to a receiver that MakeSlot doesn't return a slot // for, nothing underneath is trackable and we bail at that point. Example: // // a?.GetB()?.C // a is a field, GetB is a method, and C is a property // // The top of the tree is the a?.GetB() conditional call. We'll ask for a slot for a, and we'll get one because // fields have slots. The AccessExpression of the BoundConditionalAccess is another BoundConditionalAccess, this time // with a receiver of the GetB() BoundCall. Attempting to get a slot for this receiver will fail, and we'll // return an array with just the slot for a. int slot; switch (operand.Kind) { case BoundKind.Conversion: // https://github.com/dotnet/roslyn/issues/33879 Detect when conversion has a nullable operand operand = ((BoundConversion)operand).Operand; continue; case BoundKind.AsOperator: operand = ((BoundAsOperator)operand).Operand; continue; case BoundKind.ConditionalAccess: var conditional = (BoundConditionalAccess)operand; GetSlotsToMarkAsNotNullable(conditional.Receiver, slotBuilder); slot = MakeSlot(conditional.Receiver); if (slot > 0) { // We need to continue the walk regardless of whether the receiver should be updated. var receiverType = conditional.Receiver.Type!; if (receiverType.IsNullableType()) slot = GetNullableOfTValueSlot(receiverType, slot, out _); } if (slot > 0) { // When MakeSlot is called on the nested AccessExpression, it will recurse through receivers // until it gets to the BoundConditionalReceiver associated with this node. In our override // of MakeSlot, we substitute this slot when we encounter a BoundConditionalReceiver, and reset the // _lastConditionalAccess field. _lastConditionalAccessSlot = slot; operand = conditional.AccessExpression; continue; } // If there's no slot for this receiver, there cannot be another slot for any of the remaining // access expressions. break; default: // Attempt to create a slot for the current thing. If there were any more conditional accesses, // they would have been on top, so this is the last thing we need to specially handle. // https://github.com/dotnet/roslyn/issues/33879 When we handle unconditional access survival (ie after // c.D has been invoked, c must be nonnull or we've thrown a NullRef), revisit whether // we need more special handling here slot = MakeSlot(operand); if (slot > 0 && PossiblyNullableType(operand.Type)) { slotBuilder.Add(slot); } break; } return; } } finally { _lastConditionalAccessSlot = previousConditionalAccessSlot; } } private static bool PossiblyNullableType([NotNullWhen(true)] TypeSymbol? operandType) => operandType?.CanContainNull() == true; private static void MarkSlotsAsNotNull(ArrayBuilder<int> slots, ref LocalState stateToUpdate) { foreach (int slot in slots) { stateToUpdate[slot] = NullableFlowState.NotNull; } } private void LearnFromNonNullTest(BoundExpression expression, ref LocalState state) { if (expression.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { return; } } var slotBuilder = ArrayBuilder<int>.GetInstance(); GetSlotsToMarkAsNotNullable(expression, slotBuilder); MarkSlotsAsNotNull(slotBuilder, ref state); slotBuilder.Free(); } private void LearnFromNonNullTest(int slot, ref LocalState state) { state[slot] = NullableFlowState.NotNull; } private void LearnFromNullTest(BoundExpression expression, ref LocalState state) { // nothing to learn about a constant if (expression.ConstantValue != null) return; // We should not blindly strip conversions here. Tracked by https://github.com/dotnet/roslyn/issues/36164 var expressionWithoutConversion = RemoveConversion(expression, includeExplicitConversions: true).expression; var slot = MakeSlot(expressionWithoutConversion); // Since we know for sure the slot is null (we just tested it), we know that dependent slots are not // reachable and therefore can be treated as not null. However, we have not computed the proper // (inferred) type for the expression, so we cannot compute the correct symbols for the member slots here // (using the incorrect symbols would result in computing an incorrect default state for them). // Therefore we do not mark dependent slots not null. See https://github.com/dotnet/roslyn/issues/39624 LearnFromNullTest(slot, expressionWithoutConversion.Type, ref state, markDependentSlotsNotNull: false); } private void LearnFromNullTest(int slot, TypeSymbol? expressionType, ref LocalState state, bool markDependentSlotsNotNull) { if (slot > 0 && PossiblyNullableType(expressionType)) { if (state[slot] == NullableFlowState.NotNull) { // Note: We leave a MaybeDefault state as-is state[slot] = NullableFlowState.MaybeNull; } if (markDependentSlotsNotNull) { MarkDependentSlotsNotNull(slot, expressionType, ref state); } } } // If we know for sure that a slot contains a null value, then we know for sure that dependent slots // are "unreachable" so we might as well treat them as not null. That way when this state is merged // with another state, those dependent states won't pollute values from the other state. private void MarkDependentSlotsNotNull(int slot, TypeSymbol expressionType, ref LocalState state, int depth = 2) { if (depth <= 0) return; foreach (var member in getMembers(expressionType)) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var containingType = this._symbol?.ContainingType; if ((member is PropertySymbol { IsIndexedProperty: false } || member.Kind == SymbolKind.Field) && member.RequiresInstanceReceiver() && (containingType is null || AccessCheck.IsSymbolAccessible(member, containingType, ref discardedUseSiteInfo))) { int childSlot = GetOrCreateSlot(member, slot, forceSlotEvenIfEmpty: true, createIfMissing: false); if (childSlot > 0) { state[childSlot] = NullableFlowState.NotNull; MarkDependentSlotsNotNull(childSlot, member.GetTypeOrReturnType().Type, ref state, depth - 1); } } } static IEnumerable<Symbol> getMembers(TypeSymbol type) { // First, return the direct members foreach (var member in type.GetMembers()) yield return member; // All types inherit members from their effective bases for (NamedTypeSymbol baseType = effectiveBase(type); !(baseType is null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) foreach (var member in baseType.GetMembers()) yield return member; // Interfaces and type parameters inherit from their effective interfaces foreach (NamedTypeSymbol interfaceType in inheritedInterfaces(type)) foreach (var member in interfaceType.GetMembers()) yield return member; yield break; static NamedTypeSymbol effectiveBase(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.EffectiveBaseClassNoUseSiteDiagnostics, var t => t.BaseTypeNoUseSiteDiagnostics, }; static ImmutableArray<NamedTypeSymbol> inheritedInterfaces(TypeSymbol type) => type switch { TypeParameterSymbol tp => tp.AllEffectiveInterfacesNoUseSiteDiagnostics, { TypeKind: TypeKind.Interface } => type.AllInterfacesNoUseSiteDiagnostics, _ => ImmutableArray<NamedTypeSymbol>.Empty, }; } } private static BoundExpression SkipReferenceConversions(BoundExpression possiblyConversion) { while (possiblyConversion.Kind == BoundKind.Conversion) { var conversion = (BoundConversion)possiblyConversion; switch (conversion.ConversionKind) { case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: possiblyConversion = conversion.Operand; break; default: return possiblyConversion; } } return possiblyConversion; } public override BoundNode? VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; int leftSlot = MakeSlot(leftOperand); TypeWithAnnotations targetType = VisitLvalueWithAnnotations(leftOperand); var leftState = this.State.Clone(); LearnFromNonNullTest(leftOperand, ref leftState); LearnFromNullTest(leftOperand, ref this.State); if (node.IsNullableValueTypeAssignment) { targetType = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); } TypeWithState rightResult = VisitOptionalImplicitConversion(rightOperand, targetType, useLegacyWarnings: UseLegacyWarnings(leftOperand, targetType), trackMembers: false, AssignmentKind.Assignment); TrackNullableStateForAssignment(rightOperand, targetType, leftSlot, rightResult, MakeSlot(rightOperand)); Join(ref this.State, ref leftState); TypeWithState resultType = TypeWithState.Create(targetType.Type, rightResult.State); SetResultType(node, resultType); return null; } public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { Debug.Assert(!IsConditionalState); BoundExpression leftOperand = node.LeftOperand; BoundExpression rightOperand = node.RightOperand; if (IsConstantNull(leftOperand)) { VisitRvalue(leftOperand); Visit(rightOperand); var rightUnconditionalResult = ResultType; // Should be able to use rightResult for the result of the operator but // binding may have generated a different result type in the case of errors. SetResultType(node, TypeWithState.Create(node.Type, rightUnconditionalResult.State)); return null; } VisitPossibleConditionalAccess(leftOperand, out var whenNotNull); TypeWithState leftResult = ResultType; Unsplit(); LearnFromNullTest(leftOperand, ref this.State); bool leftIsConstant = leftOperand.ConstantValue != null; if (leftIsConstant) { SetUnreachable(); } Visit(rightOperand); TypeWithState rightResult = ResultType; Join(ref whenNotNull); var leftResultType = leftResult.Type; var rightResultType = rightResult.Type; var (resultType, leftState) = node.OperatorResultKind switch { BoundNullCoalescingOperatorResultKind.NoCommonType => (node.Type, NullableFlowState.NotNull), BoundNullCoalescingOperatorResultKind.LeftType => getLeftResultType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedType => getLeftResultType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightType => getResultStateWithRightType(leftResultType!, rightResultType!), BoundNullCoalescingOperatorResultKind.LeftUnwrappedRightType => getResultStateWithRightType(leftResultType!.StrippedType(), rightResultType!), BoundNullCoalescingOperatorResultKind.RightDynamicType => (rightResultType!, NullableFlowState.NotNull), _ => throw ExceptionUtilities.UnexpectedValue(node.OperatorResultKind), }; SetResultType(node, TypeWithState.Create(resultType, rightResult.State.Join(leftState))); return null; (TypeSymbol ResultType, NullableFlowState LeftState) getLeftResultType(TypeSymbol leftType, TypeSymbol rightType) { Debug.Assert(rightType is object); // If there was an identity conversion between the two operands (in short, if there // is no implicit conversion on the right operand), then check nullable conversions // in both directions since it's possible the right operand is the better result type. if ((node.RightOperand as BoundConversion)?.ExplicitCastInCode != false && GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: false) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); Debug.Assert(!conversion.IsUserDefined); return (leftType, NullableFlowState.NotNull); } (TypeSymbol ResultType, NullableFlowState LeftState) getResultStateWithRightType(TypeSymbol leftType, TypeSymbol rightType) { var conversion = GenerateConversionForConditionalOperator(node.LeftOperand, leftType, rightType, reportMismatch: true); if (conversion.IsUserDefined) { var conversionResult = VisitConversion( conversionOpt: null, node.LeftOperand, conversion, TypeWithAnnotations.Create(rightType), // When considering the conversion on the left node, it can only occur in the case where the underlying // execution returned non-null TypeWithState.Create(leftType, NullableFlowState.NotNull), checkConversion: false, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: false); Debug.Assert(conversionResult.Type is not null); return (conversionResult.Type!, conversionResult.State); } return (rightType, NullableFlowState.NotNull); } } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { var (operand, conversion) = RemoveConversion(node, includeExplicitConversions: true); if (operand is not BoundConditionalAccess access || !CanPropagateStateWhenNotNull(conversion)) { stateWhenNotNull = default; return false; } Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); if (node is BoundConversion boundConversion) { var operandType = ResultType; TypeWithAnnotations explicitType = boundConversion.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(boundConversion.Type); Debug.Assert(targetType.HasType); var result = VisitConversion(boundConversion, access, conversion, targetType, operandType, checkConversion: true, fromExplicitCast, useLegacyWarnings: true, assignmentKind: AssignmentKind.Assignment); SetResultType(boundConversion, result); } Debug.Assert(!IsConditionalState); return true; } /// <summary> /// Unconditionally visits an expression and returns the "state when not null" for the expression. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, out PossiblyConditionalState stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } // in case we *didn't* have a conditional access, the only thing we learn in the "state when not null" // is that the top-level expression was non-null. Visit(node); stateWhenNotNull = PossiblyConditionalState.Create(this); (node, _) = RemoveConversion(node, includeExplicitConversions: true); var slot = MakeSlot(node); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenTrue); LearnFromNonNullTest(slot, ref stateWhenNotNull.StateWhenFalse); } else { LearnFromNonNullTest(slot, ref stateWhenNotNull.State); } } return false; } private void VisitConditionalAccess(BoundConditionalAccess node, out PossiblyConditionalState stateWhenNotNull) { Debug.Assert(!IsConditionalState); var receiver = node.Receiver; // handle scenarios like `(a?.b)?.c()` VisitPossibleConditionalAccess(receiver, out stateWhenNotNull); Unsplit(); _currentConditionalReceiverVisitResult = _visitResult; var previousConditionalAccessSlot = _lastConditionalAccessSlot; if (receiver.ConstantValue is { IsNull: false }) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull VisitPossibleConditionalAccess(node.AccessExpression, out stateWhenNotNull); } else { var savedState = this.State.Clone(); if (IsConstantNull(receiver)) { SetUnreachable(); _lastConditionalAccessSlot = -1; } else { // In the when-null branch, the receiver is known to be maybe-null. // In the other branch, the receiver is known to be non-null. LearnFromNullTest(receiver, ref savedState); makeAndAdjustReceiverSlot(receiver); SetPossiblyConditionalState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); VisitRvalue(innerCondAccess.Receiver); _currentConditionalReceiverVisitResult = _visitResult; makeAndAdjustReceiverSlot(innerCondAccess.Receiver); // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); Visit(expr); expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { // The resulting nullability of each nested conditional access is the same as the resulting nullability of the rightmost access. SetAnalyzedNullability(innerCondAccess, _visitResult); expr = innerCondAccess.AccessExpression; } Debug.Assert(expr is BoundExpression); var slot = MakeSlot(expr); if (slot > -1) { if (IsConditionalState) { LearnFromNonNullTest(slot, ref StateWhenTrue); LearnFromNonNullTest(slot, ref StateWhenFalse); } else { LearnFromNonNullTest(slot, ref State); } } stateWhenNotNull = PossiblyConditionalState.Create(this); Unsplit(); Join(ref this.State, ref savedState); } var accessTypeWithAnnotations = LvalueResultType; TypeSymbol accessType = accessTypeWithAnnotations.Type; var oldType = node.Type; var resultType = oldType.IsVoidType() || oldType.IsErrorType() ? oldType : oldType.IsNullableType() && !accessType.IsNullableType() ? MakeNullableOf(accessTypeWithAnnotations) : accessType; // Per LDM 2019-02-13 decision, the result of a conditional access "may be null" even if // both the receiver and right-hand-side are believed not to be null. SetResultType(node, TypeWithState.Create(resultType, NullableFlowState.MaybeDefault)); _currentConditionalReceiverVisitResult = default; _lastConditionalAccessSlot = previousConditionalAccessSlot; void makeAndAdjustReceiverSlot(BoundExpression receiver) { var slot = MakeSlot(receiver); if (slot > -1) LearnFromNonNullTest(slot, ref State); // given `a?.b()`, when `a` is a nullable value type, // the conditional receiver for `?.b()` must be linked to `a.Value`, not to `a`. if (slot > 0 && receiver.Type?.IsNullableType() == true) slot = GetNullableOfTValueSlot(receiver.Type, slot, out _); _lastConditionalAccessSlot = slot; } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, out _); return null; } protected override BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isRef, BoundExpression condition, BoundExpression originalConsequence, BoundExpression originalAlternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; TypeWithState consequenceRValue; TypeWithState alternativeRValue; if (isRef) { TypeWithAnnotations consequenceLValue; TypeWithAnnotations alternativeLValue; (consequenceLValue, consequenceRValue) = visitConditionalRefOperand(consequenceState, originalConsequence); consequenceState = this.State; (alternativeLValue, alternativeRValue) = visitConditionalRefOperand(alternativeState, originalAlternative); Join(ref this.State, ref consequenceState); TypeSymbol? refResultType = node.Type?.SetUnknownNullabilityForReferenceTypes(); if (IsNullabilityMismatch(consequenceLValue, alternativeLValue)) { // l-value types must match ReportNullabilityMismatchInAssignment(node.Syntax, consequenceLValue, alternativeLValue); } else if (!node.HasErrors) { refResultType = consequenceRValue.Type!.MergeEquivalentTypes(alternativeRValue.Type, VarianceKind.None); } var lValueAnnotation = consequenceLValue.NullableAnnotation.EnsureCompatible(alternativeLValue.NullableAnnotation); var rValueState = consequenceRValue.State.Join(alternativeRValue.State); SetResult(node, TypeWithState.Create(refResultType, rValueState), TypeWithAnnotations.Create(refResultType, lValueAnnotation)); return null; } (var consequence, var consequenceConversion, consequenceRValue) = visitConditionalOperand(consequenceState, originalConsequence); var consequenceConditionalState = PossiblyConditionalState.Create(this); consequenceState = CloneAndUnsplit(ref consequenceConditionalState); var consequenceEndReachable = consequenceState.Reachable; (var alternative, var alternativeConversion, alternativeRValue) = visitConditionalOperand(alternativeState, originalAlternative); var alternativeConditionalState = PossiblyConditionalState.Create(this); alternativeState = CloneAndUnsplit(ref alternativeConditionalState); var alternativeEndReachable = alternativeState.Reachable; SetPossiblyConditionalState(in consequenceConditionalState); Join(ref alternativeConditionalState); TypeSymbol? resultType; bool wasTargetTyped = node is BoundConditionalOperator { WasTargetTyped: true }; if (node.HasErrors || wasTargetTyped) { resultType = null; } else { // Determine nested nullability using BestTypeInferrer. // If a branch is unreachable, we could use the nested nullability of the other // branch, but that requires using the nullability of the branch as it applies to the // target type. For instance, the result of the conditional in the following should // be `IEnumerable<object>` not `object[]`: // object[] a = ...; // IEnumerable<object?> b = ...; // var c = true ? a : b; BoundExpression consequencePlaceholder = CreatePlaceholderIfNecessary(consequence, consequenceRValue.ToTypeWithAnnotations(compilation)); BoundExpression alternativePlaceholder = CreatePlaceholderIfNecessary(alternative, alternativeRValue.ToTypeWithAnnotations(compilation)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; resultType = BestTypeInferrer.InferBestTypeForConditionalOperator(consequencePlaceholder, alternativePlaceholder, _conversions, out _, ref discardedUseSiteInfo); } resultType ??= node.Type?.SetUnknownNullabilityForReferenceTypes(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // This can happen when we're inferring the return type of a lambda. For this case, we don't need to do any work, // the unconverted conditional operator can't contribute info. The conversion that should be on top of this // can add or remove nullability, and nested nodes aren't being publicly exposed by the semantic model. Debug.Assert(node is BoundUnconvertedConditionalOperator); Debug.Assert(_returnTypesOpt is not null); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); TypeWithState convertedConsequenceResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalConsequence, consequence, consequenceConversion, resultTypeWithAnnotations, consequenceRValue, consequenceState, consequenceEndReachable); TypeWithState convertedAlternativeResult = ConvertConditionalOperandOrSwitchExpressionArmResult( originalAlternative, alternative, alternativeConversion, resultTypeWithAnnotations, alternativeRValue, alternativeState, alternativeEndReachable); resultState = convertedConsequenceResult.State.Join(convertedAlternativeResult.State); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (BoundExpression, Conversion, TypeWithState) visitConditionalOperand(LocalState state, BoundExpression operand) { Conversion conversion; SetState(state); Debug.Assert(!isRef); BoundExpression operandNoConversion; (operandNoConversion, conversion) = RemoveConversion(operand, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(operand, operandNoConversion); Visit(operandNoConversion); return (operandNoConversion, conversion, ResultType); } (TypeWithAnnotations LValueType, TypeWithState RValueType) visitConditionalRefOperand(LocalState state, BoundExpression operand) { SetState(state); Debug.Assert(isRef); TypeWithAnnotations lValueType = VisitLvalueWithAnnotations(operand); return (lValueType, ResultType); } } private TypeWithState ConvertConditionalOperandOrSwitchExpressionArmResult( BoundExpression node, BoundExpression operand, Conversion conversion, TypeWithAnnotations targetType, TypeWithState operandType, LocalState state, bool isReachable) { var savedState = this.State; this.State = state; bool previousDisabledDiagnostics = _disableDiagnostics; // If the node is not reachable, then we're only visiting to get // nullability information for the public API, and not to produce diagnostics. // Disable diagnostics, and return default for the resulting state // to indicate that warnings were suppressed. if (!isReachable) { _disableDiagnostics = true; } var resultType = VisitConversion( GetConversionIfApplicable(node, operand), operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false); if (!isReachable) { resultType = default; _disableDiagnostics = previousDisabledDiagnostics; } this.State = savedState; return resultType; } private bool IsReachable() => this.IsConditionalState ? (this.StateWhenTrue.Reachable || this.StateWhenFalse.Reachable) : this.State.Reachable; /// <summary> /// Placeholders are bound expressions with type and state. /// But for typeless expressions (such as `null` or `(null, null)` we hold onto the original bound expression, /// as it will be useful for conversions from expression. /// </summary> private static BoundExpression CreatePlaceholderIfNecessary(BoundExpression expr, TypeWithAnnotations type) { return !type.HasType ? expr : new BoundExpressionWithNullability(expr.Syntax, expr, type.NullableAnnotation, type.Type); } public override BoundNode? VisitConditionalReceiver(BoundConditionalReceiver node) { var rvalueType = _currentConditionalReceiverVisitResult.RValueType.Type; if (rvalueType?.IsNullableType() == true) { rvalueType = rvalueType.GetNullableUnderlyingType(); } SetResultType(node, TypeWithState.Create(rvalueType, NullableFlowState.NotNull)); return null; } public override BoundNode? VisitCall(BoundCall node) { // Note: we analyze even omitted calls TypeWithState receiverType = VisitCallReceiver(node); ReinferMethodAndVisitArguments(node, receiverType); return null; } private void ReinferMethodAndVisitArguments(BoundCall node, TypeWithState receiverType) { var method = node.Method; ImmutableArray<RefKind> refKindsOpt = node.ArgumentRefKindsOpt; if (!receiverType.HasNullType) { // Update method based on inferred receiver type. method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } ImmutableArray<VisitArgumentResult> results; bool returnNotNull; (method, results, returnNotNull) = VisitArguments(node, node.Arguments, refKindsOpt, method!.Parameters, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod, method); ApplyMemberPostConditions(node.ReceiverOpt, method); LearnFromEqualsMethod(method, node, receiverType, results); var returnState = GetReturnTypeWithState(method); if (returnNotNull) { returnState = returnState.WithNotNullState(); } SetResult(node, returnState, method.ReturnTypeWithAnnotations); SetUpdatedSymbol(node, node.Method, method); } private void LearnFromEqualsMethod(MethodSymbol method, BoundCall node, TypeWithState receiverType, ImmutableArray<VisitArgumentResult> results) { // easy out var parameterCount = method.ParameterCount; var arguments = node.Arguments; if (node.HasErrors || (parameterCount != 1 && parameterCount != 2) || parameterCount != arguments.Length || method.MethodKind != MethodKind.Ordinary || method.ReturnType.SpecialType != SpecialType.System_Boolean || (method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__Equals).Name && method.Name != SpecialMembers.GetDescriptor(SpecialMember.System_Object__ReferenceEquals).Name && !anyOverriddenMethodHasExplicitImplementation(method))) { return; } var isStaticEqualsMethod = method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__EqualsObjectObject)) || method.Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals)); if (isStaticEqualsMethod || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_Collections_Generic_IEqualityComparer_T__Equals)) { Debug.Assert(arguments.Length == 2); learnFromEqualsMethodArguments(arguments[0], results[0].RValueType, arguments[1], results[1].RValueType); return; } var isObjectEqualsMethodOrOverride = method.GetLeastOverriddenMethod(accessingTypeOpt: null) .Equals(compilation.GetSpecialTypeMember(SpecialMember.System_Object__Equals)); if (node.ReceiverOpt is BoundExpression receiver && (isObjectEqualsMethodOrOverride || isWellKnownEqualityMethodOrImplementation(compilation, method, receiverType.Type, WellKnownMember.System_IEquatable_T__Equals))) { Debug.Assert(arguments.Length == 1); learnFromEqualsMethodArguments(receiver, receiverType, arguments[0], results[0].RValueType); return; } static bool anyOverriddenMethodHasExplicitImplementation(MethodSymbol method) { for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.IsExplicitInterfaceImplementation) { return true; } } return false; } static bool isWellKnownEqualityMethodOrImplementation(CSharpCompilation compilation, MethodSymbol method, TypeSymbol? receiverType, WellKnownMember wellKnownMember) { var wellKnownMethod = (MethodSymbol?)compilation.GetWellKnownTypeMember(wellKnownMember); if (wellKnownMethod is null || receiverType is null) { return false; } var wellKnownType = wellKnownMethod.ContainingType; var parameterType = method.Parameters[0].TypeWithAnnotations; var constructedType = wellKnownType.Construct(ImmutableArray.Create(parameterType)); var constructedMethod = wellKnownMethod.AsMember(constructedType); // FindImplementationForInterfaceMember doesn't check if this method is itself the interface method we're looking for if (constructedMethod.Equals(method)) { return true; } // check whether 'method', when called on this receiver, is an implementation of 'constructedMethod'. for (var baseType = receiverType; baseType is object && method is object; baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var implementationMethod = baseType.FindImplementationForInterfaceMember(constructedMethod); if (implementationMethod is null) { // we know no base type will implement this interface member either return false; } if (implementationMethod.ContainingType.IsInterface) { // this method cannot be called directly from source because an interface can only explicitly implement a method from its base interface. return false; } // could be calling an override of a method that implements the interface method for (var overriddenMethod = method; overriddenMethod is object; overriddenMethod = overriddenMethod.OverriddenMethod) { if (overriddenMethod.Equals(implementationMethod)) { return true; } } // the Equals method being called isn't the method that implements the interface method in this type. // it could be a method that implements the interface on a base type, so check again with the base type of 'implementationMethod.ContainingType' // e.g. in this hierarchy: // class A -> B -> C -> D // method virtual B.Equals -> override D.Equals // // we would potentially check: // 1. D.Equals when called on D, then B.Equals when called on D // 2. B.Equals when called on C // 3. B.Equals when called on B // 4. give up when checking A, since B.Equals is not overriding anything in A // we know that implementationMethod.ContainingType is the same type or a base type of 'baseType', // and that the implementation method will be the same between 'baseType' and 'implementationMethod.ContainingType'. // we step through the intermediate bases in order to skip unnecessary override methods. while (!baseType.Equals(implementationMethod.ContainingType) && method is object) { if (baseType.Equals(method.ContainingType)) { // since we're about to move on to the base of 'method.ContainingType', // we know the implementation could only be an overridden method of 'method'. method = method.OverriddenMethod; } baseType = baseType.BaseTypeNoUseSiteDiagnostics; // the implementation method must be contained in this 'baseType' or one of its bases. Debug.Assert(baseType is object); } // now 'baseType == implementationMethod.ContainingType', so if 'method' is // contained in that same type we should advance 'method' one more time. if (method is object && baseType.Equals(method.ContainingType)) { method = method.OverriddenMethod; } } return false; } void learnFromEqualsMethodArguments(BoundExpression left, TypeWithState leftType, BoundExpression right, TypeWithState rightType) { // comparing anything to a null literal gives maybe-null when true and not-null when false // comparing a maybe-null to a not-null gives us not-null when true, nothing learned when false if (left.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(right, ref StateWhenTrue); LearnFromNonNullTest(right, ref StateWhenFalse); } else if (right.ConstantValue?.IsNull == true) { Split(); LearnFromNullTest(left, ref StateWhenTrue); LearnFromNonNullTest(left, ref StateWhenFalse); } else if (leftType.MayBeNull && rightType.IsNotNull) { Split(); LearnFromNonNullTest(left, ref StateWhenTrue); } else if (rightType.MayBeNull && leftType.IsNotNull) { Split(); LearnFromNonNullTest(right, ref StateWhenTrue); } } } private bool IsCompareExchangeMethod(MethodSymbol? method) { if (method is null) { return false; } return method.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange), SymbolEqualityComparer.ConsiderEverything.CompareKind) || method.OriginalDefinition.Equals(compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T), SymbolEqualityComparer.ConsiderEverything.CompareKind); } private readonly struct CompareExchangeInfo { public readonly ImmutableArray<BoundExpression> Arguments; public readonly ImmutableArray<VisitArgumentResult> Results; public readonly ImmutableArray<int> ArgsToParamsOpt; public CompareExchangeInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> results, ImmutableArray<int> argsToParamsOpt) { Arguments = arguments; Results = results; ArgsToParamsOpt = argsToParamsOpt; } public bool IsDefault => Arguments.IsDefault || Results.IsDefault; } private NullableFlowState LearnFromCompareExchangeMethod(in CompareExchangeInfo compareExchangeInfo) { Debug.Assert(!compareExchangeInfo.IsDefault); // In general a call to CompareExchange of the form: // // Interlocked.CompareExchange(ref location, value, comparand); // // will be analyzed similarly to the following: // // if (location == comparand) // { // location = value; // } if (compareExchangeInfo.Arguments.Length != 3) { // This can occur if CompareExchange has optional arguments. // Since none of the main runtimes have optional arguments, // we bail to avoid an exception but don't bother actually calculating the FlowState. return NullableFlowState.NotNull; } var argsToParamsOpt = compareExchangeInfo.ArgsToParamsOpt; Debug.Assert(argsToParamsOpt is { IsDefault: true } or { Length: 3 }); var (comparandIndex, valueIndex, locationIndex) = argsToParamsOpt.IsDefault ? (2, 1, 0) : (argsToParamsOpt.IndexOf(2), argsToParamsOpt.IndexOf(1), argsToParamsOpt.IndexOf(0)); var comparand = compareExchangeInfo.Arguments[comparandIndex]; var valueFlowState = compareExchangeInfo.Results[valueIndex].RValueType.State; if (comparand.ConstantValue?.IsNull == true) { // If location contained a null, then the write `location = value` definitely occurred } else { var locationFlowState = compareExchangeInfo.Results[locationIndex].RValueType.State; // A write may have occurred valueFlowState = valueFlowState.Join(locationFlowState); } return valueFlowState; } private TypeWithState VisitCallReceiver(BoundCall node) { var receiverOpt = node.ReceiverOpt; TypeWithState receiverType = default; if (receiverOpt != null) { receiverType = VisitRvalueWithState(receiverOpt); // methods which are members of Nullable<T> (ex: ToString, GetHashCode) can be invoked on null receiver. // However, inherited methods (ex: GetType) are invoked on a boxed value (since base types are reference types) // and therefore in those cases nullable receivers should be checked for nullness. bool checkNullableValueType = false; var type = receiverType.Type; var method = node.Method; if (method.RequiresInstanceReceiver && type?.IsNullableType() == true && method.ContainingType.IsReferenceType) { checkNullableValueType = true; } else if (method.OriginalDefinition == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { // call to get_Value may not occur directly in source, but may be inserted as a result of premature lowering. // One example where we do it is foreach with nullables. // The reason is Dev10 compatibility (see: UnwrapCollectionExpressionIfNullable in ForEachLoopBinder.cs) // Regardless of the reasons, we know that the method does not tolerate nulls. checkNullableValueType = true; } // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType); } return receiverType; } private TypeWithState GetReturnTypeWithState(MethodSymbol method) { return TypeWithState.Create(method.ReturnTypeWithAnnotations, GetRValueAnnotations(method)); } private FlowAnalysisAnnotations GetRValueAnnotations(Symbol? symbol) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = symbol.GetFlowAnalysisAnnotations(); return annotations & (FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull); } private FlowAnalysisAnnotations GetParameterAnnotations(ParameterSymbol parameter) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) return IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : parameter.FlowAnalysisAnnotations; } /// <summary> /// Fix a TypeWithAnnotations based on Allow/DisallowNull annotations prior to a conversion or assignment. /// Note this does not work for nullable value types, so an additional check with <see cref="CheckDisallowedNullAssignment"/> may be required. /// </summary> private static TypeWithAnnotations ApplyLValueAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations flowAnalysisAnnotations) { if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.DisallowNull) == FlowAnalysisAnnotations.DisallowNull) { return declaredType.AsNotAnnotated(); } else if ((flowAnalysisAnnotations & FlowAnalysisAnnotations.AllowNull) == FlowAnalysisAnnotations.AllowNull) { return declaredType.AsAnnotated(); } return declaredType; } /// <summary> /// Update the null-state based on MaybeNull/NotNull /// </summary> private static TypeWithState ApplyUnconditionalAnnotations(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } return typeWithState; } private static TypeWithAnnotations ApplyUnconditionalAnnotations(TypeWithAnnotations declaredType, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) == FlowAnalysisAnnotations.MaybeNull) { return declaredType.AsAnnotated(); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { return declaredType.AsNotAnnotated(); } return declaredType; } // https://github.com/dotnet/roslyn/issues/29863 Record in the node whether type // arguments were implicit, to allow for cases where the syntax is not an // invocation (such as a synthesized call from a query interpretation). private static bool HasImplicitTypeArguments(BoundNode node) { if (node is BoundCollectionElementInitializer { AddMethod: { TypeArgumentsWithAnnotations: { IsEmpty: false } } }) { return true; } if (node is BoundForEachStatement { EnumeratorInfoOpt: { GetEnumeratorInfo: { Method: { TypeArgumentsWithAnnotations: { IsEmpty: false } } } } }) { return true; } var syntax = node.Syntax; if (syntax.Kind() != SyntaxKind.InvocationExpression) { // Unexpected syntax kind. return false; } return HasImplicitTypeArguments(((InvocationExpressionSyntax)syntax).Expression); } private static bool HasImplicitTypeArguments(SyntaxNode syntax) { var nameSyntax = Binder.GetNameSyntax(syntax, out _); if (nameSyntax == null) { // Unexpected syntax kind. return false; } nameSyntax = nameSyntax.GetUnqualifiedName(); return nameSyntax.Kind() != SyntaxKind.GenericName; } protected override void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { // Callers should be using VisitArguments overload below. throw ExceptionUtilities.Unreachable; } private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol? method, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod) { return VisitArguments(node, arguments, refKindsOpt, method is null ? default : method.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod, method); } private ImmutableArray<VisitArgumentResult> VisitArguments( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, PropertySymbol? property, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { return VisitArguments(node, arguments, refKindsOpt, property is null ? default : property.Parameters, argsToParamsOpt, defaultArguments, expanded, invokedAsExtensionMethod: false).results; } /// <summary> /// If you pass in a method symbol, its type arguments will be re-inferred and the re-inferred method will be returned. /// </summary> private (MethodSymbol? method, ImmutableArray<VisitArgumentResult> results, bool returnNotNull) VisitArguments( BoundNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded, bool invokedAsExtensionMethod, MethodSymbol? method = null) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // Re-infer method type parameters if (method?.IsGenericMethod == true) { if (HasImplicitTypeArguments(node)) { method = InferMethodTypeArguments(method, GetArgumentsForMethodTypeInference(results, argumentsNoConversions), refKindsOpt, argsToParamsOpt, expanded); parametersOpt = method.Parameters; } if (ConstraintsHelper.RequiresChecking(method)) { var syntax = node.Syntax; CheckMethodConstraints( syntax switch { InvocationExpressionSyntax { Expression: var expression } => expression, ForEachStatementSyntax { Expression: var expression } => expression, _ => syntax }, method); } } bool parameterHasNotNullIfNotNull = !IsAnalyzingAttribute && !parametersOpt.IsDefault && parametersOpt.Any(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentNoConversion; if (argument is not BoundConversion && argumentNoConversion is BoundLambda lambda) { Debug.Assert(node.HasErrors); Debug.Assert((object)argument == argumentNoConversion); // 'VisitConversion' only visits a lambda when the lambda has an AnonymousFunction conversion. // This lambda doesn't have a conversion, so we need to visit it here. VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); continue; } (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { // If this assert fails, we are missing necessary info to visit the // conversion of a target typed conditional or switch. Debug.Assert(argumentNoConversion is not (BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) && _conditionalInfoForConversionOpt?.ContainsKey(argumentNoConversion) is null or false); // If this assert fails, it means we failed to visit a lambda for error recovery above. Debug.Assert(argumentNoConversion is not BoundLambda); continue; } // We disable diagnostics when: // 1. the containing call has errors (to reduce cascading diagnostics) // 2. on implicit default arguments (since that's really only an issue with the declaration) var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= node.HasErrors || defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } if (node is BoundCall { Method: { OriginalDefinition: LocalFunctionSymbol localFunction } }) { VisitLocalFunctionUse(localFunction); } if (!node.HasErrors && !parametersOpt.IsDefault) { // For CompareExchange method we need more context to determine the state of outbound assignment CompareExchangeInfo compareExchangeInfo = IsCompareExchangeMethod(method) ? new CompareExchangeInfo(arguments, results, argsToParamsOpt) : default; // Visit outbound assignments and post-conditions // Note: the state may get split in this step for (int i = 0; i < arguments.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } VisitArgumentOutboundAssignmentsAndPostConditions( arguments[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], notNullParametersBuilder, (!compareExchangeInfo.IsDefault && parameter.Ordinal == 0) ? compareExchangeInfo : default); } } else { for (int i = 0; i < arguments.Length; i++) { // We can hit this case when dynamic methods are involved, or when there are errors. In either case we have no information, // so just assume that the conversions have the same nullability as the underlying result var argument = arguments[i]; var result = results[i]; var argumentNoConversion = argumentsNoConversions[i]; TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState.Create(argument.Type, result.RValueType.State), argument as BoundConversion, argumentNoConversion); } } if (!IsAnalyzingAttribute && method is object && (method.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn) { SetUnreachable(); } notNullParametersBuilder?.Free(); return (method, results, shouldReturnNotNull); } private void ApplyMemberPostConditions(BoundExpression? receiverOpt, MethodSymbol? method) { if (method is null) { return; } int receiverSlot = method.IsStatic ? 0 : receiverOpt is null ? -1 : MakeSlot(receiverOpt); if (receiverSlot < 0) { return; } ApplyMemberPostConditions(receiverSlot, method); } private void ApplyMemberPostConditions(int receiverSlot, MethodSymbol method) { Debug.Assert(receiverSlot >= 0); do { var type = method.ContainingType; var notNullMembers = method.NotNullMembers; var notNullWhenTrueMembers = method.NotNullWhenTrueMembers; var notNullWhenFalseMembers = method.NotNullWhenFalseMembers; if (IsConditionalState) { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullMembers, ref StateWhenFalse); } else { applyMemberPostConditions(receiverSlot, type, notNullMembers, ref State); } if (!notNullWhenTrueMembers.IsEmpty || !notNullWhenFalseMembers.IsEmpty) { Split(); applyMemberPostConditions(receiverSlot, type, notNullWhenTrueMembers, ref StateWhenTrue); applyMemberPostConditions(receiverSlot, type, notNullWhenFalseMembers, ref StateWhenFalse); } method = method.OverriddenMethod; } while (method != null); void applyMemberPostConditions(int receiverSlot, TypeSymbol type, ImmutableArray<string> members, ref LocalState state) { if (members.IsEmpty) { return; } foreach (var memberName in members) { markMembersAsNotNull(receiverSlot, type, memberName, ref state); } } void markMembersAsNotNull(int receiverSlot, TypeSymbol type, string memberName, ref LocalState state) { foreach (Symbol member in type.GetMembers(memberName)) { if (member.IsStatic) { receiverSlot = 0; } switch (member.Kind) { case SymbolKind.Field: case SymbolKind.Property: if (GetOrCreateSlot(member, receiverSlot) is int memberSlot && memberSlot > 0) { state[memberSlot] = NullableFlowState.NotNull; } break; case SymbolKind.Event: case SymbolKind.Method: break; } } } } private ImmutableArray<VisitArgumentResult> VisitArgumentsEvaluate( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } private VisitArgumentResult VisitArgumentEvaluate(BoundExpression argument, RefKind refKind, FlowAnalysisAnnotations annotations) { Debug.Assert(!IsConditionalState); var savedState = (argument.Kind == BoundKind.Lambda) ? this.State.Clone() : default(Optional<LocalState>); // Note: DoesNotReturnIf is ineffective on ref/out parameters switch (refKind) { case RefKind.Ref: Visit(argument); Unsplit(); break; case RefKind.None: case RefKind.In: switch (annotations & (FlowAnalysisAnnotations.DoesNotReturnIfTrue | FlowAnalysisAnnotations.DoesNotReturnIfFalse)) { case FlowAnalysisAnnotations.DoesNotReturnIfTrue: Visit(argument); if (IsConditionalState) { SetState(StateWhenFalse); } break; case FlowAnalysisAnnotations.DoesNotReturnIfFalse: Visit(argument); if (IsConditionalState) { SetState(StateWhenTrue); } break; default: VisitRvalue(argument); break; } break; case RefKind.Out: // As far as we can tell, there is no scenario relevant to nullability analysis // where splitting an L-value (for instance with a ref conditional) would affect the result. Visit(argument); // We'll want to use the l-value type, rather than the result type, for method re-inference UseLvalueOnly(argument); break; } Debug.Assert(!IsConditionalState); return new VisitArgumentResult(_visitResult, savedState); } /// <summary> /// Verifies that an argument's nullability is compatible with its parameter's on the way in. /// </summary> private void VisitArgumentConversionAndInboundAssignmentsAndPreConditions( BoundConversion? conversionOpt, BoundExpression argumentNoConversion, Conversion conversion, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, bool extensionMethodThisArgument) { Debug.Assert(!this.IsConditionalState); // Note: we allow for some variance in `in` and `out` cases. Unlike in binding, we're not // limited by CLR constraints. var resultType = result.RValueType; switch (refKind) { case RefKind.None: case RefKind.In: { // Note: for lambda arguments, they will be converted in the context/state we saved for that argument if (conversion is { Kind: ConversionKind.ImplicitUserDefined }) { var argumentResultType = resultType.Type; conversion = GenerateConversion(_conversions, argumentNoConversion, argumentResultType, parameterType.Type, fromExplicitCast: false, extensionMethodThisArgument: false); if (!conversion.Exists && !argumentNoConversion.IsSuppressed) { Debug.Assert(argumentResultType is not null); ReportNullabilityMismatchInArgument(argumentNoConversion.Syntax, argumentResultType, parameter, parameterType.Type, forOutput: false); } } var stateAfterConversion = VisitConversion( conversionOpt: conversionOpt, conversionOperand: argumentNoConversion, conversion: conversion, targetTypeWithNullability: ApplyLValueAnnotations(parameterType, parameterAnnotations), operandType: resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter, extensionMethodThisArgument: extensionMethodThisArgument, stateForLambda: result.StateForLambda); // If the parameter has annotations, we perform an additional check for nullable value types if (CheckDisallowedNullAssignment(stateAfterConversion, parameterAnnotations, argumentNoConversion.Syntax.Location)) { LearnFromNonNullTest(argumentNoConversion, ref State); } SetResultType(argumentNoConversion, stateAfterConversion, updateAnalyzedNullability: false); } break; case RefKind.Ref: if (!argumentNoConversion.IsSuppressed) { var lvalueResultType = result.LValueType; if (IsNullabilityMismatch(lvalueResultType.Type, parameterType.Type)) { // declared types must match, ignoring top-level nullability ReportNullabilityMismatchInRefArgument(argumentNoConversion, argumentType: lvalueResultType.Type, parameter, parameterType.Type); } else { // types match, but state would let a null in ReportNullableAssignmentIfNecessary(argumentNoConversion, ApplyLValueAnnotations(parameterType, parameterAnnotations), resultType, useLegacyWarnings: false); // If the parameter has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, parameterAnnotations, argumentNoConversion.Syntax.Location); } } break; case RefKind.Out: break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } Debug.Assert(!this.IsConditionalState); } /// <summary>Returns <see langword="true"/> if this is an assignment forbidden by DisallowNullAttribute, otherwise <see langword="false"/>.</summary> private bool CheckDisallowedNullAssignment(TypeWithState state, FlowAnalysisAnnotations annotations, Location location, BoundExpression? boundValueOpt = null) { if (boundValueOpt is { WasCompilerGenerated: true }) { // We need to skip `return backingField;` in auto-prop getters return false; } // We do this extra check for types whose non-nullable version cannot be represented if (IsDisallowedNullAssignment(state, annotations)) { ReportDiagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, location); return true; } return false; } private static bool IsDisallowedNullAssignment(TypeWithState valueState, FlowAnalysisAnnotations targetAnnotations) { return ((targetAnnotations & FlowAnalysisAnnotations.DisallowNull) != 0) && hasNoNonNullableCounterpart(valueState.Type) && valueState.MayBeNull; static bool hasNoNonNullableCounterpart(TypeSymbol? type) { if (type is null) { return false; } // Some types that could receive a maybe-null value have a NotNull counterpart: // [NotNull]string? -> string // [NotNull]string -> string // [NotNull]TClass -> TClass // [NotNull]TClass? -> TClass // // While others don't: // [NotNull]int? -> X // [NotNull]TNullable -> X // [NotNull]TStruct? -> X // [NotNull]TOpen -> X return (type.Kind == SymbolKind.TypeParameter && !type.IsReferenceType) || type.IsNullableTypeOrTypeParameter(); } } /// <summary> /// Verifies that outbound assignments (from parameter to argument) are safe and /// tracks those assignments (or learns from post-condition attributes) /// </summary> private void VisitArgumentOutboundAssignmentsAndPostConditions( BoundExpression argument, RefKind refKind, ParameterSymbol parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, VisitArgumentResult result, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, CompareExchangeInfo compareExchangeInfoOpt) { // Note: the state may be conditional if a previous argument involved a conditional post-condition // The WhenTrue/False states correspond to the invocation returning true/false switch (refKind) { case RefKind.None: case RefKind.In: { // learn from post-conditions [Maybe/NotNull, Maybe/NotNullWhen] without using an assignment learnFromPostConditions(argument, parameterType, parameterAnnotations); } break; case RefKind.Ref: { // assign from a fictional value from the parameter to the argument. parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); if (!compareExchangeInfoOpt.IsDefault) { var adjustedState = LearnFromCompareExchangeMethod(in compareExchangeInfoOpt); parameterWithState = TypeWithState.Create(parameterType.Type, adjustedState); } var parameterValue = new BoundParameter(argument.Syntax, parameter); var lValueType = result.LValueType; trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // check whether parameter would unsafely let a null out in the worse case if (!argument.IsSuppressed) { var leftAnnotations = GetLValueAnnotations(argument); ReportNullableAssignmentIfNecessary( parameterValue, targetType: ApplyLValueAnnotations(lValueType, leftAnnotations), valueType: applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations), UseLegacyWarnings(argument, result.LValueType)); } } break; case RefKind.Out: { // compute the fictional parameter state parameterAnnotations = notNullBasedOnParameters(parameterAnnotations, notNullParametersOpt, parameter); var parameterWithState = TypeWithState.Create(parameterType, parameterAnnotations); // Adjust parameter state if MaybeNull or MaybeNullWhen are present (for `var` type and for assignment warnings) var worstCaseParameterWithState = applyPostConditionsUnconditionally(parameterWithState, parameterAnnotations); var declaredType = result.LValueType; var leftAnnotations = GetLValueAnnotations(argument); var lValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (argument is BoundLocal local && local.DeclarationKind == BoundLocalDeclarationKind.WithInferredType) { var varType = worstCaseParameterWithState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(local.LocalSymbol, varType); lValueType = varType; } else if (argument is BoundDiscardExpression discard) { SetAnalyzedNullability(discard, new VisitResult(parameterWithState, parameterWithState.ToTypeWithAnnotations(compilation)), isLvalue: true); } // track state by assigning from a fictional value from the parameter to the argument. var parameterValue = new BoundParameter(argument.Syntax, parameter); // If the argument type has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(parameterWithState, leftAnnotations, argument.Syntax.Location); AdjustSetValue(argument, ref parameterWithState); trackNullableStateForAssignment(parameterValue, lValueType, MakeSlot(argument), parameterWithState, argument.IsSuppressed, parameterAnnotations); // report warnings if parameter would unsafely let a null out in the worst case if (!argument.IsSuppressed) { ReportNullableAssignmentIfNecessary(parameterValue, lValueType, worstCaseParameterWithState, UseLegacyWarnings(argument, result.LValueType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (!_conversions.HasIdentityOrImplicitReferenceConversion(parameterType.Type, lValueType.Type, ref discardedUseSiteInfo)) { ReportNullabilityMismatchInArgument(argument.Syntax, lValueType.Type, parameter, parameterType.Type, forOutput: true); } } } break; default: throw ExceptionUtilities.UnexpectedValue(refKind); } FlowAnalysisAnnotations notNullBasedOnParameters(FlowAnalysisAnnotations parameterAnnotations, ArrayBuilder<ParameterSymbol>? notNullParametersOpt, ParameterSymbol parameter) { if (!IsAnalyzingAttribute && notNullParametersOpt is object) { var notNullIfParameterNotNull = parameter.NotNullIfParameterNotNull; if (!notNullIfParameterNotNull.IsEmpty) { foreach (var notNullParameter in notNullParametersOpt) { if (notNullIfParameterNotNull.Contains(notNullParameter.Name)) { return FlowAnalysisAnnotations.NotNull; } } } } return parameterAnnotations; } void trackNullableStateForAssignment(BoundExpression parameterValue, TypeWithAnnotations lValueType, int targetSlot, TypeWithState parameterWithState, bool isSuppressed, FlowAnalysisAnnotations parameterAnnotations) { if (!IsConditionalState && !hasConditionalPostCondition(parameterAnnotations)) { TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, parameterWithState.WithSuppression(isSuppressed)); } else { Split(); var originalWhenFalse = StateWhenFalse.Clone(); SetState(StateWhenTrue); // Note: the suppression applies over the post-condition attributes TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenTrue(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); var newWhenTrue = State.Clone(); SetState(originalWhenFalse); TrackNullableStateForAssignment(parameterValue, lValueType, targetSlot, applyPostConditionsWhenFalse(parameterWithState, parameterAnnotations).WithSuppression(isSuppressed)); Debug.Assert(!IsConditionalState); SetConditionalState(newWhenTrue, whenFalse: State); } } static bool hasConditionalPostCondition(FlowAnalysisAnnotations annotations) { return (((annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0)) || (((annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0) ^ ((annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0)); } static TypeWithState applyPostConditionsUnconditionally(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { if ((annotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } if ((annotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNull return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenTrue(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenTrue = (annotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && !(maybeNullWhenFalse && notNullWhenTrue)) { // [MaybeNull, NotNullWhen(true)] means [MaybeNullWhen(false)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenTrue) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } static TypeWithState applyPostConditionsWhenFalse(TypeWithState typeWithState, FlowAnalysisAnnotations annotations) { bool notNullWhenFalse = (annotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; bool maybeNullWhenTrue = (annotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (annotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenFalse && !(maybeNullWhenTrue && notNullWhenFalse)) { // [MaybeNull, NotNullWhen(false)] means [MaybeNullWhen(true)] return TypeWithState.Create(typeWithState.Type, NullableFlowState.MaybeDefault); } else if (notNullWhenFalse) { return TypeWithState.Create(typeWithState.Type, NullableFlowState.NotNull); } return typeWithState; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations) { // Note: NotNull = NotNullWhen(true) + NotNullWhen(false) bool notNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenTrue) != 0; bool notNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.NotNullWhenFalse) != 0; // Note: MaybeNull = MaybeNullWhen(true) + MaybeNullWhen(false) bool maybeNullWhenTrue = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenTrue) != 0; bool maybeNullWhenFalse = (parameterAnnotations & FlowAnalysisAnnotations.MaybeNullWhenFalse) != 0; if (maybeNullWhenTrue && maybeNullWhenFalse && !IsConditionalState && !(notNullWhenTrue && notNullWhenFalse)) { LearnFromNullTest(argument, ref State); } else if (notNullWhenTrue && notNullWhenFalse && !IsConditionalState && !(maybeNullWhenTrue || maybeNullWhenFalse)) { LearnFromNonNullTest(argument, ref State); } else if (notNullWhenTrue || notNullWhenFalse || maybeNullWhenTrue || maybeNullWhenFalse) { Split(); if (notNullWhenTrue) { LearnFromNonNullTest(argument, ref StateWhenTrue); } if (notNullWhenFalse) { LearnFromNonNullTest(argument, ref StateWhenFalse); } if (maybeNullWhenTrue) { LearnFromNullTest(argument, ref StateWhenTrue); } if (maybeNullWhenFalse) { LearnFromNullTest(argument, ref StateWhenFalse); } } } } private (ImmutableArray<BoundExpression> arguments, ImmutableArray<Conversion> conversions) RemoveArgumentConversions( ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { int n = arguments.Length; var conversions = default(ImmutableArray<Conversion>); if (n > 0) { var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(n); var conversionsBuilder = ArrayBuilder<Conversion>.GetInstance(n); bool includedConversion = false; for (int i = 0; i < n; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); var argument = arguments[i]; var conversion = Conversion.Identity; if (refKind == RefKind.None) { var before = argument; (argument, conversion) = RemoveConversion(argument, includeExplicitConversions: false); if (argument != before) { SnapshotWalkerThroughConversionGroup(before, argument); includedConversion = true; } } argumentsBuilder.Add(argument); conversionsBuilder.Add(conversion); } if (includedConversion) { arguments = argumentsBuilder.ToImmutable(); conversions = conversionsBuilder.ToImmutable(); } argumentsBuilder.Free(); conversionsBuilder.Free(); } return (arguments, conversions); } private static VariableState GetVariableState(Variables variables, LocalState localState) { Debug.Assert(variables.Id == localState.Id); return new VariableState(variables.CreateSnapshot(), localState.CreateSnapshot()); } private (ParameterSymbol? Parameter, TypeWithAnnotations Type, FlowAnalysisAnnotations Annotations, bool isExpandedParamsArgument) GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { if (parametersOpt.IsDefault) { return default; } var parameter = Binder.GetCorrespondingParameter(argumentOrdinal, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { Debug.Assert(!expanded); return default; } var type = parameter.TypeWithAnnotations; if (expanded && parameter.Ordinal == parametersOpt.Length - 1 && type.IsSZArray()) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; return (parameter, type, FlowAnalysisAnnotations.None, isExpandedParamsArgument: true); } return (parameter, type, GetParameterAnnotations(parameter), isExpandedParamsArgument: false); } private MethodSymbol InferMethodTypeArguments( MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<int> argsToParamsOpt, bool expanded) { Debug.Assert(method.IsGenericMethod); // https://github.com/dotnet/roslyn/issues/27961 OverloadResolution.IsMemberApplicableInNormalForm and // IsMemberApplicableInExpandedForm use the least overridden method. We need to do the same here. var definition = method.ConstructedFrom; var refKinds = ArrayBuilder<RefKind>.GetInstance(); if (argumentRefKindsOpt != null) { refKinds.AddRange(argumentRefKindsOpt); } // https://github.com/dotnet/roslyn/issues/27961 Do we really need OverloadResolution.GetEffectiveParameterTypes? // Aren't we doing roughly the same calculations in GetCorrespondingParameter? OverloadResolution.GetEffectiveParameterTypes( definition, arguments.Length, argsToParamsOpt, refKinds, isMethodGroupConversion: false, // https://github.com/dotnet/roslyn/issues/27961 `allowRefOmittedArguments` should be // false for constructors and several other cases (see Binder use). Should we // capture the original value in the BoundCall? allowRefOmittedArguments: true, binder: _binder, expanded: expanded, parameterTypes: out ImmutableArray<TypeWithAnnotations> parameterTypes, parameterRefKinds: out ImmutableArray<RefKind> parameterRefKinds); refKinds.Free(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var result = MethodTypeInferrer.Infer( _binder, _conversions, definition.TypeParameters, definition.ContainingType, parameterTypes, parameterRefKinds, arguments, ref discardedUseSiteInfo, new MethodInferenceExtensions(this)); if (!result.Success) { return method; } return definition.Construct(result.InferredTypeArguments); } private sealed class MethodInferenceExtensions : MethodTypeInferrer.Extensions { private readonly NullableWalker _walker; internal MethodInferenceExtensions(NullableWalker walker) { _walker = walker; } internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType(), GetNullableAnnotation(expr)); } /// <summary> /// Return top-level nullability for the expression. This method should be called on a limited /// set of expressions only. It should not be called on expressions tracked by flow analysis /// other than <see cref="BoundKind.ExpressionWithNullability"/> which is an expression /// specifically created in NullableWalker to represent the flow analysis state. /// </summary> private static NullableAnnotation GetNullableAnnotation(BoundExpression expr) { switch (expr.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: case BoundKind.Literal: return expr.ConstantValue == ConstantValue.NotAvailable || !expr.ConstantValue.IsNull || expr.IsSuppressed ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: return NullableAnnotation.NotAnnotated; default: Debug.Assert(false); // unexpected value return NullableAnnotation.Oblivious; } } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { if (_walker.TryGetMethodGroupReceiverNullability(group.ReceiverOpt, out TypeWithState receiverType)) { if (!method.IsStatic) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } } return method.ReturnTypeWithAnnotations; } } private ImmutableArray<BoundExpression> GetArgumentsForMethodTypeInference(ImmutableArray<VisitArgumentResult> argumentResults, ImmutableArray<BoundExpression> arguments) { // https://github.com/dotnet/roslyn/issues/27961 MethodTypeInferrer.Infer relies // on the BoundExpressions for tuple element types and method groups. // By using a generic BoundValuePlaceholder, we're losing inference in those cases. // https://github.com/dotnet/roslyn/issues/27961 Inference should be based on // unconverted arguments. Consider cases such as `default`, lambdas, tuples. int n = argumentResults.Length; var builder = ArrayBuilder<BoundExpression>.GetInstance(n); for (int i = 0; i < n; i++) { var visitArgumentResult = argumentResults[i]; var lambdaState = visitArgumentResult.StateForLambda; // Note: for `out` arguments, the argument result contains the declaration type (see `VisitArgumentEvaluate`) var argumentResult = visitArgumentResult.RValueType.ToTypeWithAnnotations(compilation); builder.Add(getArgumentForMethodTypeInference(arguments[i], argumentResult, lambdaState)); } return builder.ToImmutableAndFree(); BoundExpression getArgumentForMethodTypeInference(BoundExpression argument, TypeWithAnnotations argumentType, Optional<LocalState> lambdaState) { if (argument.Kind == BoundKind.Lambda) { Debug.Assert(lambdaState.HasValue); // MethodTypeInferrer must infer nullability for lambdas based on the nullability // from flow analysis rather than the declared nullability. To allow that, we need // to re-bind lambdas in MethodTypeInferrer. return getUnboundLambda((BoundLambda)argument, GetVariableState(_variables, lambdaState.Value)); } if (!argumentType.HasType) { return argument; } if (argument is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // target-typed contexts don't contribute to nullability return new BoundExpressionWithNullability(argument.Syntax, argument, NullableAnnotation.Oblivious, type: null); } return new BoundExpressionWithNullability(argument.Syntax, argument, argumentType.NullableAnnotation, argumentType.Type); } static UnboundLambda getUnboundLambda(BoundLambda expr, VariableState variableState) { return expr.UnboundLambda.WithNullableState(variableState); } } private void CheckMethodConstraints(SyntaxNode syntax, MethodSymbol method) { if (_disableDiagnostics) { return; } var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var nullabilityBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; ConstraintsHelper.CheckMethodConstraints( method, new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), diagnosticsBuilder, nullabilityBuilder, ref useSiteDiagnosticsBuilder); foreach (var pair in nullabilityBuilder) { if (pair.UseSiteInfo.DiagnosticInfo is object) { Diagnostics.Add(pair.UseSiteInfo.DiagnosticInfo, syntax.Location); } } useSiteDiagnosticsBuilder?.Free(); nullabilityBuilder.Free(); diagnosticsBuilder.Free(); } /// <summary> /// Returns the expression without the top-most conversion plus the conversion. /// If the expression is not a conversion, returns the original expression plus /// the Identity conversion. If `includeExplicitConversions` is true, implicit and /// explicit conversions are considered. If `includeExplicitConversions` is false /// only implicit conversions are considered and if the expression is an explicit /// conversion, the expression is returned as is, with the Identity conversion. /// (Currently, the only visit method that passes `includeExplicitConversions: true` /// is VisitConversion. All other callers are handling implicit conversions only.) /// </summary> private static (BoundExpression expression, Conversion conversion) RemoveConversion(BoundExpression expr, bool includeExplicitConversions) { ConversionGroup? group = null; while (true) { if (expr.Kind != BoundKind.Conversion) { break; } var conversion = (BoundConversion)expr; if (group != conversion.ConversionGroupOpt && group != null) { // E.g.: (C)(B)a break; } group = conversion.ConversionGroupOpt; Debug.Assert(group != null || !conversion.ExplicitCastInCode); // Explicit conversions should include a group. if (!includeExplicitConversions && group?.IsExplicitConversion == true) { return (expr, Conversion.Identity); } expr = conversion.Operand; if (group == null) { // Ungrouped conversion should not be followed by another ungrouped // conversion. Otherwise, the conversions should have been grouped. // https://github.com/dotnet/roslyn/issues/34919 This assertion does not always hold true for // enum initializers //Debug.Assert(expr.Kind != BoundKind.Conversion || // ((BoundConversion)expr).ConversionGroupOpt != null || // ((BoundConversion)expr).ConversionKind == ConversionKind.NoConversion); return (expr, conversion.Conversion); } } return (expr, group?.Conversion ?? Conversion.Identity); } // See Binder.BindNullCoalescingOperator for initial binding. private Conversion GenerateConversionForConditionalOperator(BoundExpression sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool reportMismatch) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); bool canConvertNestedNullability = conversion.Exists; if (!canConvertNestedNullability && reportMismatch && !sourceExpression.IsSuppressed) { ReportNullabilityMismatchInAssignment(sourceExpression.Syntax, GetTypeAsDiagnosticArgument(sourceType), destinationType); } return conversion; } private static Conversion GenerateConversion(Conversions conversions, BoundExpression? sourceExpression, TypeSymbol? sourceType, TypeSymbol destinationType, bool fromExplicitCast, bool extensionMethodThisArgument) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool useExpression = sourceType is null || UseExpressionForConversion(sourceExpression); if (extensionMethodThisArgument) { return conversions.ClassifyImplicitExtensionMethodThisArgConversion( useExpression ? sourceExpression : null, sourceType, destinationType, ref discardedUseSiteInfo); } return useExpression ? (fromExplicitCast ? conversions.ClassifyConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo)); } /// <summary> /// Returns true if the expression should be used as the source when calculating /// a conversion from this expression, rather than using the type (with nullability) /// calculated by visiting this expression. Typically, that means expressions that /// do not have an explicit type but there are several other cases as well. /// (See expressions handled in ClassifyImplicitBuiltInConversionFromExpression.) /// </summary> private static bool UseExpressionForConversion([NotNullWhen(true)] BoundExpression? value) { if (value is null) { return false; } if (value.Type is null || value.Type.IsDynamic() || value.ConstantValue != null) { return true; } switch (value.Kind) { case BoundKind.InterpolatedString: return true; default: return false; } } /// <summary> /// Adjust declared type based on inferred nullability at the point of reference. /// </summary> private TypeWithState GetAdjustedResult(TypeWithState type, int slot) { if (this.State.HasValue(slot)) { NullableFlowState state = this.State[slot]; return TypeWithState.Create(type.Type, state); } return type; } /// <summary> /// Gets the corresponding member for a symbol from initial binding to match an updated receiver type in NullableWalker. /// For instance, this will map from List&lt;string~&gt;.Add(string~) to List&lt;string?&gt;.Add(string?) in the following example: /// <example> /// string s = null; /// var list = new[] { s }.ToList(); /// list.Add(null); /// </example> /// </summary> private static Symbol AsMemberOfType(TypeSymbol? type, Symbol symbol) { Debug.Assert((object)symbol != null); var containingType = type as NamedTypeSymbol; if (containingType is null || containingType.IsErrorType() || symbol is ErrorMethodSymbol) { return symbol; } if (symbol.Kind == SymbolKind.Method) { if (((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { // https://github.com/dotnet/roslyn/issues/27233 Handle type substitution for local functions. return symbol; } } if (symbol is TupleElementFieldSymbol or TupleErrorFieldSymbol) { return symbol.SymbolAsMember(containingType); } var symbolContainer = symbol.ContainingType; if (symbolContainer.IsAnonymousType) { int? memberIndex = symbol.Kind == SymbolKind.Property ? symbol.MemberIndexOpt : null; if (!memberIndex.HasValue) { return symbol; } return AnonymousTypeManager.GetAnonymousTypeProperty(containingType, memberIndex.GetValueOrDefault()); } if (!symbolContainer.IsGenericType) { Debug.Assert(symbol.ContainingType.IsDefinition); return symbol; } if (!containingType.IsGenericType) { return symbol; } if (symbolContainer.IsInterface) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } foreach (var @interface in containingType.AllInterfacesNoUseSiteDiagnostics) { if (tryAsMemberOfSingleType(@interface, out result)) { return result; } } } else { while (true) { if (tryAsMemberOfSingleType(containingType, out var result)) { return result; } containingType = containingType.BaseTypeNoUseSiteDiagnostics; if ((object)containingType == null) { break; } } } Debug.Assert(false); // If this assert fails, add an appropriate test. return symbol; bool tryAsMemberOfSingleType(NamedTypeSymbol singleType, [NotNullWhen(true)] out Symbol? result) { if (!singleType.Equals(symbolContainer, TypeCompareKind.AllIgnoreOptions)) { result = null; return false; } var symbolDef = symbol.OriginalDefinition; result = symbolDef.SymbolAsMember(singleType); if (result is MethodSymbol resultMethod && resultMethod.IsGenericMethod) { result = resultMethod.Construct(((MethodSymbol)symbol).TypeArgumentsWithAnnotations); } return true; } } public override BoundNode? VisitConversion(BoundConversion node) { // https://github.com/dotnet/roslyn/issues/35732: Assert VisitConversion is only used for explicit conversions. //Debug.Assert(node.ExplicitCastInCode); //Debug.Assert(node.ConversionGroupOpt != null); //Debug.Assert(node.ConversionGroupOpt.ExplicitType.HasType); TypeWithAnnotations explicitType = node.ConversionGroupOpt?.ExplicitType ?? default; bool fromExplicitCast = explicitType.HasType; TypeWithAnnotations targetType = fromExplicitCast ? explicitType : TypeWithAnnotations.Create(node.Type); Debug.Assert(targetType.HasType); (BoundExpression operand, Conversion conversion) = RemoveConversion(node, includeExplicitConversions: true); SnapshotWalkerThroughConversionGroup(node, operand); TypeWithState operandType = VisitRvalueWithState(operand); SetResultType(node, VisitConversion( node, operand, conversion, targetType, operandType, checkConversion: true, fromExplicitCast: fromExplicitCast, useLegacyWarnings: fromExplicitCast, AssignmentKind.Assignment, reportTopLevelWarnings: fromExplicitCast, reportRemainingWarnings: true, trackMembers: true)); return null; } /// <summary> /// Visit an expression. If an explicit target type is provided, the expression is converted /// to that type. This method should be called whenever an expression may contain /// an implicit conversion, even if that conversion was omitted from the bound tree, /// so the conversion can be re-classified with nullability. /// </summary> private TypeWithState VisitOptionalImplicitConversion(BoundExpression expr, TypeWithAnnotations targetTypeOpt, bool useLegacyWarnings, bool trackMembers, AssignmentKind assignmentKind) { if (!targetTypeOpt.HasType) { return VisitRvalueWithState(expr); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // If an explicit conversion was used in place of an implicit conversion, the explicit // conversion was created by initial binding after reporting "error CS0266: // Cannot implicitly convert type '...' to '...'. An explicit conversion exists ...". // Since an error was reported, we don't need to report nested warnings as well. bool reportNestedWarnings = !conversion.IsExplicit; var resultType = VisitConversion( GetConversionIfApplicable(expr, operand), operand, conversion, targetTypeOpt, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: useLegacyWarnings, assignmentKind, reportTopLevelWarnings: true, reportRemainingWarnings: reportNestedWarnings, trackMembers: trackMembers); return resultType; } private static bool AreNullableAndUnderlyingTypes([NotNullWhen(true)] TypeSymbol? nullableTypeOpt, [NotNullWhen(true)] TypeSymbol? underlyingTypeOpt, out TypeWithAnnotations underlyingTypeWithAnnotations) { if (nullableTypeOpt?.IsNullableType() == true && underlyingTypeOpt?.IsNullableType() == false) { var typeArg = nullableTypeOpt.GetNullableUnderlyingTypeWithAnnotations(); if (typeArg.Type.Equals(underlyingTypeOpt, TypeCompareKind.AllIgnoreOptions)) { underlyingTypeWithAnnotations = typeArg; return true; } } underlyingTypeWithAnnotations = default; return false; } public override BoundNode? VisitTupleLiteral(BoundTupleLiteral node) { VisitTupleExpression(node); return null; } public override BoundNode? VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { Debug.Assert(!IsConditionalState); var savedState = this.State.Clone(); // Visit the source tuple so that the semantic model can correctly report nullability for it // Disable diagnostics, as we don't want to duplicate any that are produced by visiting the converted literal below VisitWithoutDiagnostics(node.SourceTuple); this.SetState(savedState); VisitTupleExpression(node); return null; } private void VisitTupleExpression(BoundTupleExpression node) { var arguments = node.Arguments; ImmutableArray<TypeWithState> elementTypes = arguments.SelectAsArray((a, w) => w.VisitRvalueWithState(a), this); ImmutableArray<TypeWithAnnotations> elementTypesWithAnnotations = elementTypes.SelectAsArray(a => a.ToTypeWithAnnotations(compilation)); var tupleOpt = (NamedTypeSymbol?)node.Type; if (tupleOpt is null) { SetResultType(node, TypeWithState.Create(null, NullableFlowState.NotNull)); } else { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; TrackNullableStateOfTupleElements(slot, tupleOpt, arguments, elementTypes, argsToParamsOpt: default, useRestField: false); } tupleOpt = tupleOpt.WithElementTypes(elementTypesWithAnnotations); if (!_disableDiagnostics) { var locations = tupleOpt.TupleElements.SelectAsArray((element, location) => element.Locations.FirstOrDefault() ?? location, node.Syntax.Location); tupleOpt.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, _conversions, includeNullability: true, node.Syntax.Location, diagnostics: null), typeSyntax: node.Syntax, locations, nullabilityDiagnosticsOpt: new BindingDiagnosticBag(Diagnostics)); } SetResultType(node, TypeWithState.Create(tupleOpt, NullableFlowState.NotNull)); } } /// <summary> /// Set the nullability of tuple elements for tuples at the point of construction. /// If <paramref name="useRestField"/> is true, the tuple was constructed with an explicit /// 'new ValueTuple' call, in which case the 8-th element, if any, represents the 'Rest' field. /// </summary> private void TrackNullableStateOfTupleElements( int slot, NamedTypeSymbol tupleType, ImmutableArray<BoundExpression> values, ImmutableArray<TypeWithState> types, ImmutableArray<int> argsToParamsOpt, bool useRestField) { Debug.Assert(tupleType.IsTupleType); Debug.Assert(values.Length == types.Length); Debug.Assert(values.Length == (useRestField ? Math.Min(tupleType.TupleElements.Length, NamedTypeSymbol.ValueTupleRestPosition) : tupleType.TupleElements.Length)); if (slot > 0) { var tupleElements = tupleType.TupleElements; int n = values.Length; if (useRestField) { n = Math.Min(n, NamedTypeSymbol.ValueTupleRestPosition - 1); } for (int i = 0; i < n; i++) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(i); trackState(values[argOrdinal], tupleElements[i], types[argOrdinal]); } if (useRestField && values.Length == NamedTypeSymbol.ValueTupleRestPosition && tupleType.GetMembers(NamedTypeSymbol.ValueTupleRestFieldName).FirstOrDefault() is FieldSymbol restField) { var argOrdinal = GetArgumentOrdinalFromParameterOrdinal(NamedTypeSymbol.ValueTupleRestPosition - 1); trackState(values[argOrdinal], restField, types[argOrdinal]); } } void trackState(BoundExpression value, FieldSymbol field, TypeWithState valueType) { int targetSlot = GetOrCreateSlot(field, slot); TrackNullableStateForAssignment(value, field.TypeWithAnnotations, targetSlot, valueType, MakeSlot(value)); } int GetArgumentOrdinalFromParameterOrdinal(int parameterOrdinal) { var index = argsToParamsOpt.IsDefault ? parameterOrdinal : argsToParamsOpt.IndexOf(parameterOrdinal); Debug.Assert(index != -1); return index; } } private void TrackNullableStateOfNullableValue(int containingSlot, TypeSymbol containingType, BoundExpression? value, TypeWithState valueType, int valueSlot) { Debug.Assert(containingType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T); Debug.Assert(containingSlot > 0); Debug.Assert(valueSlot > 0); int targetSlot = GetNullableOfTValueSlot(containingType, containingSlot, out Symbol? symbol); if (targetSlot > 0) { TrackNullableStateForAssignment(value, symbol!.GetTypeOrReturnType(), targetSlot, valueType, valueSlot); } } private void TrackNullableStateOfTupleConversion( BoundConversion? conversionOpt, BoundExpression convertedNode, Conversion conversion, TypeSymbol targetType, TypeSymbol operandType, int slot, int valueSlot, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings) { Debug.Assert(conversion.Kind == ConversionKind.ImplicitTuple || conversion.Kind == ConversionKind.ExplicitTuple); Debug.Assert(slot > 0); Debug.Assert(valueSlot > 0); var valueTuple = operandType as NamedTypeSymbol; if (valueTuple is null || !valueTuple.IsTupleType) { return; } var conversions = conversion.UnderlyingConversions; var targetElements = ((NamedTypeSymbol)targetType).TupleElements; var valueElements = valueTuple.TupleElements; int n = valueElements.Length; for (int i = 0; i < n; i++) { trackConvertedValue(targetElements[i], conversions[i], valueElements[i]); } void trackConvertedValue(FieldSymbol targetField, Conversion conversion, FieldSymbol valueField) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: case ConversionKind.Boxing: case ConversionKind.Unboxing: InheritNullableStateOfMember(slot, valueSlot, valueField, isDefaultValue: false, skipSlot: slot); break; case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, convertedNode, conversion, targetField.Type, valueField.Type, targetFieldSlot, valueFieldSlot, assignmentKind, parameterOpt, reportWarnings); } } } break; case ConversionKind.ImplicitNullable: case ConversionKind.ExplicitNullable: // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (AreNullableAndUnderlyingTypes(targetField.Type, valueField.Type, out _)) { int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = NullableFlowState.NotNull; int valueFieldSlot = GetOrCreateSlot(valueField, valueSlot); if (valueFieldSlot > 0) { TrackNullableStateOfNullableValue(targetFieldSlot, targetField.Type, null, valueField.TypeWithAnnotations.ToTypeWithState(), valueFieldSlot); } } } break; case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: { var convertedType = VisitUserDefinedConversion( conversionOpt, convertedNode, conversion, targetField.TypeWithAnnotations, valueField.TypeWithAnnotations.ToTypeWithState(), useLegacyWarnings: false, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: reportWarnings, diagnosticLocation: (conversionOpt ?? convertedNode).Syntax.GetLocation()); int targetFieldSlot = GetOrCreateSlot(targetField, slot); if (targetFieldSlot > 0) { this.State[targetFieldSlot] = convertedType.State; } } break; default: break; } } } public override BoundNode? VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { base.VisitTupleBinaryOperator(node); SetNotNullResult(node); return null; } private void ReportNullabilityMismatchWithTargetDelegate(Location location, TypeSymbol targetType, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool invokedAsExtensionMethod) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, targetInvokeMethod, sourceInvokeMethod, new BindingDiagnosticBag(Diagnostics), reportBadDelegateReturn, reportBadDelegateParameter, extraArgument: (targetType, location), invokedAsExtensionMethod: invokedAsExtensionMethod); void reportBadDelegateReturn(BindingDiagnosticBag bag, MethodSymbol targetInvokeMethod, MethodSymbol sourceInvokeMethod, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, arg.location, new FormattedSymbol(sourceInvokeMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), arg.targetType); } void reportBadDelegateParameter(BindingDiagnosticBag bag, MethodSymbol sourceInvokeMethod, MethodSymbol targetInvokeMethod, ParameterSymbol parameter, bool topLevel, (TypeSymbol targetType, Location location) arg) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, arg.location, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter), arg.targetType); } } private void ReportNullabilityMismatchWithTargetDelegate(Location location, NamedTypeSymbol delegateType, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // Parameter nullability is expected to match exactly. This corresponds to the behavior of initial binding. // Action<string> x = (object o) => { }; // error CS1661: Cannot convert lambda expression to delegate type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<object> y = (object? o) => { }; // warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'Action<object>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// if one should be passed. /// </summary> private static BoundConversion? GetConversionIfApplicable(BoundExpression? conversionOpt, BoundExpression convertedNode) { Debug.Assert(conversionOpt is null || convertedNode == conversionOpt // Note that convertedNode itself can be a BoundConversion, so we do this check explicitly // because the below calls to RemoveConversion could potentially strip that conversion. || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: false).expression || convertedNode == RemoveConversion(conversionOpt, includeExplicitConversions: true).expression); return conversionOpt == convertedNode ? null : (BoundConversion?)conversionOpt; } /// <summary> /// Apply the conversion to the type of the operand and return the resulting type. /// If the operand does not have an explicit type, the operand expression is used. /// </summary> /// <param name="checkConversion"> /// If <see langword="true"/>, the incoming conversion is assumed to be from binding /// and will be re-calculated, this time considering nullability. /// Note that the conversion calculation considers nested nullability only. /// The caller is responsible for checking the top-level nullability of /// the type returned by this method. /// </param> /// <param name="trackMembers"> /// If <see langword="true"/>, the nullability of any members of the operand /// will be copied to the converted result when possible. /// </param> /// <param name="useLegacyWarnings"> /// If <see langword="true"/>, indicates that the "non-safety" diagnostic <see cref="ErrorCode.WRN_ConvertingNullableToNonNullable"/> /// should be given for an invalid conversion. /// </param> private TypeWithState VisitConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool checkConversion, bool fromExplicitCast, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt = null, bool reportTopLevelWarnings = true, bool reportRemainingWarnings = true, bool extensionMethodThisArgument = false, Optional<LocalState> stateForLambda = default, bool trackMembers = false, Location? diagnosticLocationOpt = null) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != null); NullableFlowState resultState = NullableFlowState.NotNull; bool canConvertNestedNullability = true; bool isSuppressed = false; diagnosticLocationOpt ??= (conversionOpt ?? conversionOperand).Syntax.GetLocation(); if (conversionOperand.IsSuppressed == true) { reportTopLevelWarnings = false; reportRemainingWarnings = false; isSuppressed = true; } #nullable disable TypeSymbol targetType = targetTypeWithNullability.Type; switch (conversion.Kind) { case ConversionKind.MethodGroup: { var group = conversionOperand as BoundMethodGroup; var (invokeSignature, parameters) = getDelegateOrFunctionPointerInfo(targetType); var method = conversion.Method; if (group != null) { if (method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } method = CheckMethodGroupReceiverNullability(group, parameters, method, conversion.IsExtensionMethod); } if (reportRemainingWarnings && invokeSignature != null) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, targetType, invokeSignature, method, conversion.IsExtensionMethod); } } resultState = NullableFlowState.NotNull; break; static (MethodSymbol invokeSignature, ImmutableArray<ParameterSymbol>) getDelegateOrFunctionPointerInfo(TypeSymbol targetType) => targetType switch { NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { Parameters: { } parameters } signature } => (signature, parameters), FunctionPointerTypeSymbol { Signature: { Parameters: { } parameters } signature } => (signature, parameters), _ => (null, ImmutableArray<ParameterSymbol>.Empty), }; case ConversionKind.AnonymousFunction: if (conversionOperand is BoundLambda lambda) { var delegateType = targetType.GetDelegateType(); VisitLambda(lambda, delegateType, stateForLambda); if (reportRemainingWarnings) { ReportNullabilityMismatchWithTargetDelegate(diagnosticLocationOpt, delegateType, lambda.UnboundLambda); } TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); return TypeWithState.Create(targetType, NullableFlowState.NotNull); } break; case ConversionKind.FunctionType: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedString: resultState = NullableFlowState.NotNull; break; case ConversionKind.InterpolatedStringHandler: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); break; case ConversionKind.ExplicitUserDefined: case ConversionKind.ImplicitUserDefined: return VisitUserDefinedConversion(conversionOpt, conversionOperand, conversion, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt); case ConversionKind.ExplicitDynamic: case ConversionKind.ImplicitDynamic: resultState = getConversionResultState(operandType); break; case ConversionKind.Boxing: resultState = getBoxingConversionResultState(targetTypeWithNullability, operandType); break; case ConversionKind.Unboxing: if (targetType.IsNonNullableValueType()) { if (!operandType.IsNotNull && reportRemainingWarnings) { ReportDiagnostic(ErrorCode.WRN_UnboxPossibleNull, diagnosticLocationOpt); } LearnFromNonNullTest(conversionOperand, ref State); } else { resultState = getUnboxingConversionResultState(operandType); } break; case ConversionKind.ImplicitThrow: resultState = NullableFlowState.NotNull; break; case ConversionKind.NoConversion: resultState = getConversionResultState(operandType); break; case ConversionKind.NullLiteral: case ConversionKind.DefaultLiteral: checkConversion = false; goto case ConversionKind.Identity; case ConversionKind.Identity: // If the operand is an explicit conversion, and this identity conversion // is converting to the same type including nullability, skip the conversion // to avoid reporting redundant warnings. Also check useLegacyWarnings // since that value was used when reporting warnings for the explicit cast. // Don't skip the node when it's a user-defined conversion, as identity conversions // on top of user-defined conversions means that we're coming in from VisitUserDefinedConversion // and that any warnings caught by this recursive call of VisitConversion won't be redundant. if (useLegacyWarnings && conversionOperand is BoundConversion operandConversion && !operandConversion.ConversionKind.IsUserDefinedConversion()) { var explicitType = operandConversion.ConversionGroupOpt?.ExplicitType; if (explicitType?.Equals(targetTypeWithNullability, TypeCompareKind.ConsiderEverything) == true) { TrackAnalyzedNullabilityThroughConversionGroup( calculateResultType(targetTypeWithNullability, fromExplicitCast, operandType.State, isSuppressed, targetType), conversionOpt, conversionOperand); return operandType; } } if (operandType.Type?.IsTupleType == true || conversionOperand.Kind == BoundKind.TupleLiteral) { goto case ConversionKind.ImplicitTuple; } goto case ConversionKind.ImplicitReference; case ConversionKind.ImplicitReference: case ConversionKind.ExplicitReference: // Inherit state from the operand. if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = conversion.IsReference ? getReferenceConversionResultState(targetTypeWithNullability, operandType) : operandType.State; break; case ConversionKind.ImplicitNullable: if (trackMembers) { Debug.Assert(conversionOperand != null); if (AreNullableAndUnderlyingTypes(targetType, operandType.Type, out TypeWithAnnotations underlyingType)) { // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int containingSlot = GetOrCreatePlaceholderSlot(conversionOpt); Debug.Assert(containingSlot > 0); TrackNullableStateOfNullableValue(containingSlot, targetType, conversionOperand, underlyingType.ToTypeWithState(), valueSlot); } } } if (checkConversion) { conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = operandType.State; break; case ConversionKind.ExplicitNullable: if (operandType.Type?.IsNullableType() == true && !targetType.IsNullableType()) { // Explicit conversion of Nullable<T> to T is equivalent to Nullable<T>.Value. if (reportTopLevelWarnings && operandType.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, diagnosticLocationOpt); } // Mark the value as not nullable, regardless of whether it was known to be nullable, // because the implied call to `.Value` will only succeed if not null. if (conversionOperand != null) { LearnFromNonNullTest(conversionOperand, ref State); } } goto case ConversionKind.ImplicitNullable; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ExplicitTupleLiteral: case ConversionKind.ExplicitTuple: if (trackMembers) { Debug.Assert(conversionOperand != null); switch (conversion.Kind) { case ConversionKind.ImplicitTuple: case ConversionKind.ExplicitTuple: int valueSlot = MakeSlot(conversionOperand); if (valueSlot > 0) { int slot = GetOrCreatePlaceholderSlot(conversionOpt); if (slot > 0) { TrackNullableStateOfTupleConversion(conversionOpt, conversionOperand, conversion, targetType, operandType.Type, slot, valueSlot, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings); } } break; } } if (checkConversion && !targetType.IsErrorType()) { // https://github.com/dotnet/roslyn/issues/29699: Report warnings for user-defined conversions on tuple elements. conversion = GenerateConversion(_conversions, conversionOperand, operandType.Type, targetType, fromExplicitCast, extensionMethodThisArgument); canConvertNestedNullability = conversion.Exists; } resultState = NullableFlowState.NotNull; break; case ConversionKind.Deconstruction: // Can reach here, with an error type, when the // Deconstruct method is missing or inaccessible. break; case ConversionKind.ExplicitEnumeration: // Can reach here, with an error type. break; default: Debug.Assert(targetType.IsValueType || targetType.IsErrorType()); break; } TypeWithState resultType = calculateResultType(targetTypeWithNullability, fromExplicitCast, resultState, isSuppressed, targetType); if (operandType.Type?.IsErrorType() != true && !targetType.IsErrorType()) { // Need to report all warnings that apply since the warnings can be suppressed individually. if (reportTopLevelWarnings) { ReportNullableAssignmentIfNecessary(conversionOperand, targetTypeWithNullability, resultType, useLegacyWarnings, assignmentKind, parameterOpt, diagnosticLocationOpt); } if (reportRemainingWarnings && !canConvertNestedNullability) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocationOpt, operandType.Type, parameterOpt, targetType, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocationOpt, GetTypeAsDiagnosticArgument(operandType.Type), targetType); } } } TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; #nullable enable static TypeWithState calculateResultType(TypeWithAnnotations targetTypeWithNullability, bool fromExplicitCast, NullableFlowState resultState, bool isSuppressed, TypeSymbol targetType) { if (isSuppressed) { resultState = NullableFlowState.NotNull; } else if (fromExplicitCast && targetTypeWithNullability.NullableAnnotation.IsAnnotated() && !targetType.IsNullableType()) { // An explicit cast to a nullable reference type introduces nullability resultState = targetType?.IsTypeParameterDisallowingAnnotationInCSharp8() == true ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } var resultType = TypeWithState.Create(targetType, resultState); return resultType; } static NullableFlowState getReferenceConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; switch (state) { case NullableFlowState.MaybeNull: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == true) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && dependsOnTypeParameter(typeParameter1, (TypeParameterSymbol)targetType.Type, NullableAnnotation.NotAnnotated, out var annotation)) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } break; case NullableFlowState.MaybeDefault: if (targetType.Type?.IsTypeParameterDisallowingAnnotationInCSharp8() == false) { return NullableFlowState.MaybeNull; } break; } return state; } // Converting to a less-derived type (object, interface, type parameter). // If the operand is MaybeNull, the result should be // MaybeNull (if the target type allows) or MaybeDefault otherwise. static NullableFlowState getBoxingConversionResultState(TypeWithAnnotations targetType, TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { var type = operandType.Type; if (type is null || !type.IsTypeParameterDisallowingAnnotationInCSharp8()) { return NullableFlowState.MaybeDefault; } else if (targetType.NullableAnnotation.IsNotAnnotated() && type is TypeParameterSymbol typeParameter1 && targetType.Type is TypeParameterSymbol typeParameter2) { bool dependsOn = dependsOnTypeParameter(typeParameter1, typeParameter2, NullableAnnotation.NotAnnotated, out var annotation); Debug.Assert(dependsOn); // If this case fails, add a corresponding test. if (dependsOn) { return (annotation == NullableAnnotation.Annotated) ? NullableFlowState.MaybeDefault : NullableFlowState.MaybeNull; } } } return state; } // Converting to a more-derived type (struct, class, type parameter). // If the operand is MaybeNull or MaybeDefault, the result should be // MaybeDefault. static NullableFlowState getUnboxingConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } static NullableFlowState getConversionResultState(TypeWithState operandType) { var state = operandType.State; if (state == NullableFlowState.MaybeNull) { return NullableFlowState.MaybeDefault; } return state; } // If type parameter 1 depends on type parameter 2 (that is, if type parameter 2 appears // in the constraint types of type parameter 1), returns the effective annotation on // type parameter 2 in the constraints of type parameter 1. static bool dependsOnTypeParameter(TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2, NullableAnnotation typeParameter1Annotation, out NullableAnnotation annotation) { if (typeParameter1.Equals(typeParameter2, TypeCompareKind.AllIgnoreOptions)) { annotation = typeParameter1Annotation; return true; } bool dependsOn = false; var combinedAnnotation = NullableAnnotation.Annotated; foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol constraintTypeParameter && dependsOnTypeParameter(constraintTypeParameter, typeParameter2, constraintType.NullableAnnotation, out var constraintAnnotation)) { dependsOn = true; combinedAnnotation = combinedAnnotation.Meet(constraintAnnotation); } } if (dependsOn) { annotation = combinedAnnotation.Join(typeParameter1Annotation); return true; } annotation = default; return false; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } private TypeWithState VisitUserDefinedConversion( BoundConversion? conversionOpt, BoundExpression conversionOperand, Conversion conversion, TypeWithAnnotations targetTypeWithNullability, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportTopLevelWarnings, bool reportRemainingWarnings, Location diagnosticLocation) { Debug.Assert(!IsConditionalState); Debug.Assert(conversionOperand != null); Debug.Assert(targetTypeWithNullability.HasType); Debug.Assert(diagnosticLocation != null); Debug.Assert(conversion.Kind == ConversionKind.ExplicitUserDefined || conversion.Kind == ConversionKind.ImplicitUserDefined); TypeSymbol targetType = targetTypeWithNullability.Type; // cf. Binder.CreateUserDefinedConversion if (!conversion.IsValid) { var resultType = TypeWithState.Create(targetType, NullableFlowState.NotNull); TrackAnalyzedNullabilityThroughConversionGroup(resultType, conversionOpt, conversionOperand); return resultType; } // operand -> conversion "from" type // May be distinct from method parameter type for Nullable<T>. operandType = VisitConversion( conversionOpt, conversionOperand, conversion.UserDefinedFromConversion, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.FromType), operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings, reportRemainingWarnings, diagnosticLocationOpt: diagnosticLocation); // Update method based on operandType: see https://github.com/dotnet/roslyn/issues/29605. // (see NullableReferenceTypesTests.ImplicitConversions_07). var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount == 1); Debug.Assert(operandType.Type is object); var parameter = method.Parameters[0]; var parameterAnnotations = GetParameterAnnotations(parameter); var parameterType = ApplyLValueAnnotations(parameter.TypeWithAnnotations, parameterAnnotations); TypeWithState underlyingOperandType = default; bool isLiftedConversion = false; if (operandType.Type.IsNullableType() && !parameterType.IsNullableType()) { var underlyingOperandTypeWithAnnotations = operandType.Type.GetNullableUnderlyingTypeWithAnnotations(); underlyingOperandType = underlyingOperandTypeWithAnnotations.ToTypeWithState(); isLiftedConversion = parameterType.Equals(underlyingOperandTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); } // conversion "from" type -> method parameter type NullableFlowState operandState = operandType.State; Location operandLocation = conversionOperand.Syntax.GetLocation(); _ = ClassifyAndVisitConversion( conversionOperand, parameterType, isLiftedConversion ? underlyingOperandType : operandType, useLegacyWarnings, AssignmentKind.Argument, parameterOpt: parameter, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // in the case of a lifted conversion, we assume that the call to the operator occurs only if the argument is not-null if (!isLiftedConversion && CheckDisallowedNullAssignment(operandType, parameterAnnotations, conversionOperand.Syntax.Location)) { LearnFromNonNullTest(conversionOperand, ref State); } // method parameter type -> method return type var methodReturnType = method.ReturnTypeWithAnnotations; operandType = GetLiftedReturnTypeIfNecessary(isLiftedConversion, methodReturnType, operandState); if (!isLiftedConversion || operandState.IsNotNull()) { var returnNotNull = operandState.IsNotNull() && method.ReturnNotNullIfParameterNotNull.Contains(parameter.Name); if (returnNotNull) { operandType = operandType.WithNotNullState(); } else { operandType = ApplyUnconditionalAnnotations(operandType, GetRValueAnnotations(method)); } } // method return type -> conversion "to" type // May be distinct from method return type for Nullable<T>. operandType = ClassifyAndVisitConversion( conversionOperand, TypeWithAnnotations.Create(conversion.BestUserDefinedConversionAnalysis!.ToType), operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: false, diagnosticLocation: operandLocation); // conversion "to" type -> final type // We should only pass fromExplicitCast here. Given the following example: // // class A { public static explicit operator C(A a) => throw null!; } // class C // { // void M() => var c = (C?)new A(); // } // // This final conversion from the method return type "C" to the cast type "C?" is // where we will need to ensure that this is counted as an explicit cast, so that // the resulting operandType is nullable if that was introduced via cast. operandType = ClassifyAndVisitConversion( conversionOpt ?? conversionOperand, targetTypeWithNullability, operandType, useLegacyWarnings, assignmentKind, parameterOpt, reportWarnings: reportRemainingWarnings, fromExplicitCast: conversionOpt?.ExplicitCastInCode ?? false, diagnosticLocation); TrackAnalyzedNullabilityThroughConversionGroup(operandType, conversionOpt, conversionOperand); return operandType; } private void SnapshotWalkerThroughConversionGroup(BoundExpression conversionExpression, BoundExpression convertedNode) { if (_snapshotBuilderOpt is null) { return; } var conversionOpt = conversionExpression as BoundConversion; var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode && conversionOpt.Syntax.SpanStart != convertedNode.Syntax.SpanStart) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); TakeIncrementalSnapshot(conversionOpt); conversionOpt = conversionOpt.Operand as BoundConversion; } } private void TrackAnalyzedNullabilityThroughConversionGroup(TypeWithState resultType, BoundConversion? conversionOpt, BoundExpression convertedNode) { var visitResult = new VisitResult(resultType, resultType.ToTypeWithAnnotations(compilation)); var conversionGroup = conversionOpt?.ConversionGroupOpt; while (conversionOpt != null && conversionOpt != convertedNode) { Debug.Assert(conversionOpt.ConversionGroupOpt == conversionGroup); visitResult = withType(visitResult, conversionOpt.Type); SetAnalyzedNullability(conversionOpt, visitResult); conversionOpt = conversionOpt.Operand as BoundConversion; } static VisitResult withType(VisitResult visitResult, TypeSymbol newType) => new VisitResult(TypeWithState.Create(newType, visitResult.RValueType.State), TypeWithAnnotations.Create(newType, visitResult.LValueType.NullableAnnotation)); } /// <summary> /// Return the return type for a lifted operator, given the nullability state of its operands. /// </summary> private TypeWithState GetLiftedReturnType(TypeWithAnnotations returnType, NullableFlowState operandState) { bool typeNeedsLifting = returnType.Type.IsNonNullableValueType(); TypeSymbol type = typeNeedsLifting ? MakeNullableOf(returnType) : returnType.Type; NullableFlowState state = returnType.ToTypeWithState().State.Join(operandState); return TypeWithState.Create(type, state); } private static TypeWithState GetNullableUnderlyingTypeIfNecessary(bool isLifted, TypeWithState typeWithState) { if (isLifted) { var type = typeWithState.Type; if (type?.IsNullableType() == true) { return type.GetNullableUnderlyingTypeWithAnnotations().ToTypeWithState(); } } return typeWithState; } private TypeWithState GetLiftedReturnTypeIfNecessary(bool isLifted, TypeWithAnnotations returnType, NullableFlowState operandState) { return isLifted ? GetLiftedReturnType(returnType, operandState) : returnType.ToTypeWithState(); } private TypeSymbol MakeNullableOf(TypeWithAnnotations underlying) { return compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(ImmutableArray.Create(underlying)); } private TypeWithState ClassifyAndVisitConversion( BoundExpression node, TypeWithAnnotations targetType, TypeWithState operandType, bool useLegacyWarnings, AssignmentKind assignmentKind, ParameterSymbol? parameterOpt, bool reportWarnings, bool fromExplicitCast, Location diagnosticLocation) { Debug.Assert(operandType.Type is object); Debug.Assert(diagnosticLocation != null); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyStandardConversion(null, operandType.Type, targetType.Type, ref discardedUseSiteInfo); if (reportWarnings && !conversion.Exists) { if (assignmentKind == AssignmentKind.Argument) { ReportNullabilityMismatchInArgument(diagnosticLocation, operandType.Type, parameterOpt, targetType.Type, forOutput: false); } else { ReportNullabilityMismatchInAssignment(diagnosticLocation, operandType.Type, targetType.Type); } } return VisitConversion( conversionOpt: null, conversionOperand: node, conversion, targetType, operandType, checkConversion: false, fromExplicitCast, useLegacyWarnings: useLegacyWarnings, assignmentKind, parameterOpt, reportTopLevelWarnings: reportWarnings, reportRemainingWarnings: !fromExplicitCast && reportWarnings, diagnosticLocationOpt: diagnosticLocation); } public override BoundNode? VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { Debug.Assert(node.Type.IsDelegateType()); if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod) { method = CheckMethodGroupReceiverNullability(group, delegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed && delegateType.DelegateInvokeMethod is { } delegateInvokeMethod && argType.DelegateInvokeMethod() is { } argInvokeMethod) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateInvokeMethod, argInvokeMethod, invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } public override BoundNode? VisitMethodGroup(BoundMethodGroup node) { Debug.Assert(!IsConditionalState); var receiverOpt = node.ReceiverOpt; if (receiverOpt != null) { VisitRvalue(receiverOpt); // Receiver nullability is checked when applying the method group conversion, // when we have a specific method, to avoid reporting null receiver warnings // for extension method delegates. Here, store the receiver state for that check. SetMethodGroupReceiverNullability(receiverOpt, ResultType); } SetNotNullResult(node); return null; } private bool TryGetMethodGroupReceiverNullability([NotNullWhen(true)] BoundExpression? receiverOpt, out TypeWithState type) { if (receiverOpt != null && _methodGroupReceiverMapOpt != null && _methodGroupReceiverMapOpt.TryGetValue(receiverOpt, out type)) { return true; } else { type = default; return false; } } private void SetMethodGroupReceiverNullability(BoundExpression receiver, TypeWithState type) { _methodGroupReceiverMapOpt ??= PooledDictionary<BoundExpression, TypeWithState>.GetInstance(); _methodGroupReceiverMapOpt[receiver] = type; } private MethodSymbol CheckMethodGroupReceiverNullability(BoundMethodGroup group, ImmutableArray<ParameterSymbol> parameters, MethodSymbol method, bool invokedAsExtensionMethod) { var receiverOpt = group.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { var syntax = group.Syntax; if (!invokedAsExtensionMethod) { method = (MethodSymbol)AsMemberOfType(receiverType.Type, method); } if (method.IsGenericMethod && HasImplicitTypeArguments(group.Syntax)) { var arguments = ArrayBuilder<BoundExpression>.GetInstance(); if (invokedAsExtensionMethod) { arguments.Add(CreatePlaceholderIfNecessary(receiverOpt, receiverType.ToTypeWithAnnotations(compilation))); } // Create placeholders for the arguments. (See Conversions.GetDelegateArguments() // which is used for that purpose in initial binding.) foreach (var parameter in parameters) { var parameterType = parameter.TypeWithAnnotations; arguments.Add(new BoundExpressionWithNullability(syntax, new BoundParameter(syntax, parameter), parameterType.NullableAnnotation, parameterType.Type)); } Debug.Assert(_binder is object); method = InferMethodTypeArguments(method, arguments.ToImmutableAndFree(), argumentRefKindsOpt: default, argsToParamsOpt: default, expanded: false); } if (invokedAsExtensionMethod) { CheckExtensionMethodThisNullability(receiverOpt, Conversion.Identity, method.Parameters[0], receiverType); } else { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } if (ConstraintsHelper.RequiresChecking(method)) { CheckMethodConstraints(syntax, method); } } return method; } public override BoundNode? VisitLambda(BoundLambda node) { // Note: actual lambda analysis happens after this call (primarily in VisitConversion). // Here we just indicate that a lambda expression produces a non-null value. SetNotNullResult(node); return null; } private void VisitLambda(BoundLambda node, NamedTypeSymbol? delegateTypeOpt, Optional<LocalState> initialState = default) { Debug.Assert(delegateTypeOpt?.IsDelegateType() != false); var delegateInvokeMethod = delegateTypeOpt?.DelegateInvokeMethod; UseDelegateInvokeParameterAndReturnTypes(node, delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType); if (useDelegateInvokeParameterTypes && _snapshotBuilderOpt is object) { SetUpdatedSymbol(node, node.Symbol, delegateTypeOpt!); } AnalyzeLocalFunctionOrLambda( node, node.Symbol, initialState.HasValue ? initialState.Value : State.Clone(), delegateInvokeMethod, useDelegateInvokeParameterTypes, useDelegateInvokeReturnType); } private static void UseDelegateInvokeParameterAndReturnTypes(BoundLambda lambda, MethodSymbol? delegateInvokeMethod, out bool useDelegateInvokeParameterTypes, out bool useDelegateInvokeReturnType) { if (delegateInvokeMethod is null) { useDelegateInvokeParameterTypes = false; useDelegateInvokeReturnType = false; } else { var unboundLambda = lambda.UnboundLambda; useDelegateInvokeParameterTypes = !unboundLambda.HasExplicitlyTypedParameterList; useDelegateInvokeReturnType = !unboundLambda.HasExplicitReturnType(out _, out _); } } public override BoundNode? VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. // Analyze the body to report any additional warnings. var lambda = node.BindForErrorRecovery(); VisitLambda(lambda, delegateTypeOpt: null); SetNotNullResult(node); return null; } public override BoundNode? VisitThisReference(BoundThisReference node) { VisitThisOrBaseReference(node); return null; } private void VisitThisOrBaseReference(BoundExpression node) { var rvalueResult = TypeWithState.Create(node.Type, NullableFlowState.NotNull); var lvalueResult = TypeWithAnnotations.Create(node.Type, NullableAnnotation.NotAnnotated); SetResult(node, rvalueResult, lvalueResult); } public override BoundNode? VisitParameter(BoundParameter node) { var parameter = node.ParameterSymbol; int slot = GetOrCreateSlot(parameter); var parameterType = GetDeclaredParameterResult(parameter); var typeWithState = GetParameterState(parameterType, parameter.FlowAnalysisAnnotations); SetResult(node, GetAdjustedResult(typeWithState, slot), parameterType); return null; } public override BoundNode? VisitAssignmentOperator(BoundAssignmentOperator node) { Debug.Assert(!IsConditionalState); var left = node.Left; switch (left) { // when binding initializers, we treat assignments to auto-properties or field-like events as direct assignments to the underlying field. // in order to track member state based on these initializers, we need to see the assignment in terms of the associated member case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: PropertySymbol autoProperty } } fieldAccess: left = new BoundPropertyAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, autoProperty, LookupResultKind.Viable, autoProperty.Type, fieldAccess.HasErrors); break; case BoundFieldAccess { ExpressionSymbol: FieldSymbol { AssociatedSymbol: EventSymbol @event } } fieldAccess: left = new BoundEventAccess(fieldAccess.Syntax, fieldAccess.ReceiverOpt, @event, isUsableAsField: true, LookupResultKind.Viable, @event.Type, fieldAccess.HasErrors); break; } var right = node.Right; VisitLValue(left); // we may enter a conditional state for error scenarios on the LHS. Unsplit(); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = ApplyLValueAnnotations(declaredType, leftAnnotations); if (left.Kind == BoundKind.EventAccess && ((BoundEventAccess)left).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to an Add method. (Note that assignment // of non-field-like events uses BoundEventAssignmentOperator // rather than BoundAssignmentOperator.) VisitRvalue(right); SetNotNullResult(node); } else { TypeWithState rightState; if (!node.IsRef) { var discarded = left is BoundDiscardExpression; rightState = VisitOptionalImplicitConversion(right, targetTypeOpt: discarded ? default : leftLValueType, UseLegacyWarnings(left, leftLValueType), trackMembers: true, AssignmentKind.Assignment); } else { rightState = VisitRefExpression(right, leftLValueType); } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(rightState, leftAnnotations, right.Syntax.Location); AdjustSetValue(left, ref rightState); TrackNullableStateForAssignment(right, leftLValueType, MakeSlot(left), rightState, MakeSlot(right)); if (left is BoundDiscardExpression) { var lvalueType = rightState.ToTypeWithAnnotations(compilation); SetResult(left, rightState, lvalueType, isLvalue: true); SetResult(node, rightState, lvalueType); } else { SetResult(node, TypeWithState.Create(leftLValueType.Type, rightState.State), leftLValueType); } } return null; } private bool IsPropertyOutputMoreStrictThanInput(PropertySymbol property) { var type = property.TypeWithAnnotations; var annotations = IsAnalyzingAttribute ? FlowAnalysisAnnotations.None : property.GetFlowAnalysisAnnotations(); var lValueType = ApplyLValueAnnotations(type, annotations); if (lValueType.NullableAnnotation.IsOblivious() || !lValueType.CanBeAssignedNull) { return false; } var rValueType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), annotations); return rValueType.IsNotNull; } /// <summary> /// When the allowed output of a property/indexer is not-null but the allowed input is maybe-null, we store a not-null value instead. /// This way, assignment of a legal input value results in a legal output value. /// This adjustment doesn't apply to oblivious properties/indexers. /// </summary> private void AdjustSetValue(BoundExpression left, ref TypeWithState rightState) { var property = left switch { BoundPropertyAccess propAccess => propAccess.PropertySymbol, BoundIndexerAccess indexerAccess => indexerAccess.Indexer, _ => null }; if (property is not null && IsPropertyOutputMoreStrictThanInput(property)) { rightState = rightState.WithNotNullState(); } } private FlowAnalysisAnnotations GetLValueAnnotations(BoundExpression expr) { // Annotations are ignored when binding an attribute to avoid cycles. (Members used // in attributes are error scenarios, so missing warnings should not be important.) if (IsAnalyzingAttribute) { return FlowAnalysisAnnotations.None; } var annotations = expr switch { BoundPropertyAccess property => property.PropertySymbol.GetFlowAnalysisAnnotations(), BoundIndexerAccess indexer => indexer.Indexer.GetFlowAnalysisAnnotations(), BoundFieldAccess field => getFieldAnnotations(field.FieldSymbol), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } private static FlowAnalysisAnnotations ToInwardAnnotations(FlowAnalysisAnnotations outwardAnnotations) { var annotations = FlowAnalysisAnnotations.None; if ((outwardAnnotations & FlowAnalysisAnnotations.MaybeNull) != 0) { // MaybeNull and MaybeNullWhen count as MaybeNull annotations |= FlowAnalysisAnnotations.AllowNull; } if ((outwardAnnotations & FlowAnalysisAnnotations.NotNull) == FlowAnalysisAnnotations.NotNull) { // NotNullWhenTrue and NotNullWhenFalse don't count on their own. Only NotNull (ie. both flags) matters. annotations |= FlowAnalysisAnnotations.DisallowNull; } return annotations; } private static bool UseLegacyWarnings(BoundExpression expr, TypeWithAnnotations exprType) { switch (expr.Kind) { case BoundKind.Local: return expr.GetRefKind() == RefKind.None; case BoundKind.Parameter: RefKind kind = ((BoundParameter)expr).ParameterSymbol.RefKind; return kind == RefKind.None; default: return false; } } public override BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return VisitDeconstructionAssignmentOperator(node, rightResultOpt: null); } private BoundNode? VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node, TypeWithState? rightResultOpt) { var previousDisableNullabilityAnalysis = _disableNullabilityAnalysis; _disableNullabilityAnalysis = true; var left = node.Left; var right = node.Right; var variables = GetDeconstructionAssignmentVariables(left); if (node.HasErrors) { // In the case of errors, simply visit the right as an r-value to update // any nullability state even though deconstruction is skipped. VisitRvalue(right.Operand); } else { VisitDeconstructionArguments(variables, right.Conversion, right.Operand, rightResultOpt); } variables.FreeAll(v => v.NestedVariables); // https://github.com/dotnet/roslyn/issues/33011: Result type should be inferred and the constraints should // be re-verified. Even though the standard tuple type has no constraints we support that scenario. Constraints_78 // has a test for this case that should start failing when this is fixed. SetNotNullResult(node); _disableNullabilityAnalysis = previousDisableNullabilityAnalysis; return null; } private void VisitDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt = null) { Debug.Assert(conversion.Kind == ConversionKind.Deconstruction); if (!conversion.DeconstructionInfo.IsDefault) { VisitDeconstructMethodArguments(variables, conversion, right, rightResultOpt); } else { VisitTupleDeconstructionArguments(variables, conversion.UnderlyingConversions, right); } } private void VisitDeconstructMethodArguments(ArrayBuilder<DeconstructionVariable> variables, Conversion conversion, BoundExpression right, TypeWithState? rightResultOpt) { VisitRvalue(right); // If we were passed an explicit right result, use that rather than the visited result if (rightResultOpt.HasValue) { SetResultType(right, rightResultOpt.Value); } var rightResult = ResultType; var invocation = conversion.DeconstructionInfo.Invocation as BoundCall; var deconstructMethod = invocation?.Method; if (deconstructMethod is object) { Debug.Assert(invocation is object); Debug.Assert(rightResult.Type is object); int n = variables.Count; if (!invocation.InvokedAsExtensionMethod) { _ = CheckPossibleNullReceiver(right); // update the deconstruct method with any inferred type parameters of the containing type if (deconstructMethod.OriginalDefinition != deconstructMethod) { deconstructMethod = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } else { if (deconstructMethod.IsGenericMethod) { // re-infer the deconstruct parameters based on the 'this' parameter ArrayBuilder<BoundExpression> placeholderArgs = ArrayBuilder<BoundExpression>.GetInstance(n + 1); placeholderArgs.Add(CreatePlaceholderIfNecessary(right, rightResult.ToTypeWithAnnotations(compilation))); for (int i = 0; i < n; i++) { placeholderArgs.Add(new BoundExpressionWithNullability(variables[i].Expression.Syntax, variables[i].Expression, NullableAnnotation.Oblivious, conversion.DeconstructionInfo.OutputPlaceholders[i].Type)); } deconstructMethod = InferMethodTypeArguments(deconstructMethod, placeholderArgs.ToImmutableAndFree(), invocation.ArgumentRefKindsOpt, invocation.ArgsToParamsOpt, invocation.Expanded); // check the constraints remain valid with the re-inferred parameter types if (ConstraintsHelper.RequiresChecking(deconstructMethod)) { CheckMethodConstraints(invocation.Syntax, deconstructMethod); } } } var parameters = deconstructMethod.Parameters; int offset = invocation.InvokedAsExtensionMethod ? 1 : 0; Debug.Assert(parameters.Length - offset == n); if (invocation.InvokedAsExtensionMethod) { // Check nullability for `this` parameter var argConversion = RemoveConversion(invocation.Arguments[0], includeExplicitConversions: false).conversion; CheckExtensionMethodThisNullability(right, argConversion, deconstructMethod.Parameters[0], rightResult); } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var underlyingConversion = conversion.UnderlyingConversions[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { var nestedRight = CreatePlaceholderIfNecessary(invocation.Arguments[i + offset], parameter.TypeWithAnnotations); VisitDeconstructionArguments(nestedVariables, underlyingConversion, right: nestedRight); } else { VisitArgumentConversionAndInboundAssignmentsAndPreConditions(conversionOpt: null, variable.Expression, underlyingConversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), extensionMethodThisArgument: false); } } for (int i = 0; i < n; i++) { var variable = variables[i]; var parameter = parameters[i + offset]; var nestedVariables = variable.NestedVariables; if (nestedVariables == null) { VisitArgumentOutboundAssignmentsAndPostConditions( variable.Expression, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetRValueAnnotations(parameter), new VisitArgumentResult(new VisitResult(variable.Type.ToTypeWithState(), variable.Type), stateForLambda: default), notNullParametersOpt: null, compareExchangeInfoOpt: default); } } } } private void VisitTupleDeconstructionArguments(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; var rightPart = rightParts[i]; var nestedVariables = variable.NestedVariables; if (nestedVariables != null) { VisitDeconstructionArguments(nestedVariables, underlyingConversion, rightPart); } else { var lvalueType = variable.Type; var leftAnnotations = GetLValueAnnotations(variable.Expression); lvalueType = ApplyLValueAnnotations(lvalueType, leftAnnotations); TypeWithState operandType; TypeWithState valueType; int valueSlot; if (underlyingConversion.IsIdentity) { if (variable.Expression is BoundLocal { DeclarationKind: BoundLocalDeclarationKind.WithInferredType } local) { // when the LHS is a var declaration, we can just visit the right part to infer the type valueType = operandType = VisitRvalueWithState(rightPart); _variables.SetType(local.LocalSymbol, operandType.ToAnnotatedTypeWithAnnotations(compilation)); } else { operandType = default; valueType = VisitOptionalImplicitConversion(rightPart, lvalueType, useLegacyWarnings: true, trackMembers: true, AssignmentKind.Assignment); } valueSlot = MakeSlot(rightPart); } else { operandType = VisitRvalueWithState(rightPart); valueType = VisitConversion( conversionOpt: null, rightPart, underlyingConversion, lvalueType, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: true, AssignmentKind.Assignment, reportTopLevelWarnings: true, reportRemainingWarnings: true, trackMembers: false); valueSlot = -1; } // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(valueType, leftAnnotations, right.Syntax.Location); int targetSlot = MakeSlot(variable.Expression); AdjustSetValue(variable.Expression, ref valueType); TrackNullableStateForAssignment(rightPart, lvalueType, targetSlot, valueType, valueSlot); // Conversion of T to Nullable<T> is equivalent to new Nullable<T>(t). if (targetSlot > 0 && underlyingConversion.Kind == ConversionKind.ImplicitNullable && AreNullableAndUnderlyingTypes(lvalueType.Type, operandType.Type, out TypeWithAnnotations underlyingType)) { valueSlot = MakeSlot(rightPart); if (valueSlot > 0) { var valueBeforeNullableWrapping = TypeWithState.Create(underlyingType.Type, NullableFlowState.NotNull); TrackNullableStateOfNullableValue(targetSlot, lvalueType.Type, rightPart, valueBeforeNullableWrapping, valueSlot); } } } } } private readonly struct DeconstructionVariable { internal readonly BoundExpression Expression; internal readonly TypeWithAnnotations Type; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal DeconstructionVariable(BoundExpression expression, TypeWithAnnotations type) { Expression = expression; Type = type; NestedVariables = null; } internal DeconstructionVariable(BoundExpression expression, ArrayBuilder<DeconstructionVariable> nestedVariables) { Expression = expression; Type = default; NestedVariables = nestedVariables; } } private ArrayBuilder<DeconstructionVariable> GetDeconstructionAssignmentVariables(BoundTupleExpression tuple) { var arguments = tuple.Arguments; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(arguments.Length); foreach (var argument in arguments) { builder.Add(getDeconstructionAssignmentVariable(argument)); } return builder; DeconstructionVariable getDeconstructionAssignmentVariable(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return new DeconstructionVariable(expr, GetDeconstructionAssignmentVariables((BoundTupleExpression)expr)); default: VisitLValue(expr); return new DeconstructionVariable(expr, LvalueResultType); } } } /// <summary> /// Return the sub-expressions for the righthand side of a deconstruction /// assignment. cf. LocalRewriter.GetRightParts. /// </summary> private ImmutableArray<BoundExpression> GetDeconstructionRightParts(BoundExpression expr) { switch (expr.Kind) { case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return ((BoundTupleExpression)expr).Arguments; case BoundKind.Conversion: { var conv = (BoundConversion)expr; switch (conv.ConversionKind) { case ConversionKind.Identity: case ConversionKind.ImplicitTupleLiteral: return GetDeconstructionRightParts(conv.Operand); } } break; } if (expr.Type is NamedTypeSymbol { IsTupleType: true } tupleType) { // https://github.com/dotnet/roslyn/issues/33011: Should include conversion.UnderlyingConversions[i]. // For instance, Boxing conversions (see Deconstruction_ImplicitBoxingConversion_02) and // ImplicitNullable conversions (see Deconstruction_ImplicitNullableConversion_02). var fields = tupleType.TupleElements; return fields.SelectAsArray((f, e) => (BoundExpression)new BoundFieldAccess(e.Syntax, e, f, constantValueOpt: null), expr); } throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitIncrementOperator(BoundIncrementOperator node) { Debug.Assert(!IsConditionalState); var operandType = VisitRvalueWithState(node.Operand); var operandLvalue = LvalueResultType; bool setResult = false; if (this.State.Reachable) { // https://github.com/dotnet/roslyn/issues/29961 Update increment method based on operand type. MethodSymbol? incrementOperator = (node.OperatorKind.IsUserDefined() && node.MethodOpt?.ParameterCount == 1) ? node.MethodOpt : null; TypeWithAnnotations targetTypeOfOperandConversion; AssignmentKind assignmentKind = AssignmentKind.Assignment; ParameterSymbol? parameter = null; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 // https://github.com/dotnet/roslyn/issues/29961 Update conversion method based on operand type. if (node.OperandConversion.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.OperandConversion.Method.ReturnTypeWithAnnotations; } else if (incrementOperator is object) { targetTypeOfOperandConversion = incrementOperator.Parameters[0].TypeWithAnnotations; assignmentKind = AssignmentKind.Argument; parameter = incrementOperator.Parameters[0]; } else { // Either a built-in increment, or an error case. targetTypeOfOperandConversion = default; } TypeWithState resultOfOperandConversionType; if (targetTypeOfOperandConversion.HasType) { // https://github.com/dotnet/roslyn/issues/29961 Should something special be done for targetTypeOfOperandConversion for lifted case? resultOfOperandConversionType = VisitConversion( conversionOpt: null, node.Operand, node.OperandConversion, targetTypeOfOperandConversion, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind, parameter, reportTopLevelWarnings: true, reportRemainingWarnings: true); } else { resultOfOperandConversionType = operandType; } TypeWithState resultOfIncrementType; if (incrementOperator is null) { resultOfIncrementType = resultOfOperandConversionType; } else { resultOfIncrementType = incrementOperator.ReturnTypeWithAnnotations.ToTypeWithState(); } var operandTypeWithAnnotations = operandType.ToTypeWithAnnotations(compilation); resultOfIncrementType = VisitConversion( conversionOpt: null, node, node.ResultConversion, operandTypeWithAnnotations, resultOfIncrementType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // https://github.com/dotnet/roslyn/issues/29961 Check node.Type.IsErrorType() instead? if (!node.HasErrors) { var op = node.OperatorKind.Operator(); TypeWithState resultType = (op == UnaryOperatorKind.PrefixIncrement || op == UnaryOperatorKind.PrefixDecrement) ? resultOfIncrementType : operandType; SetResultType(node, resultType); setResult = true; TrackNullableStateForAssignment(node, targetType: operandLvalue, targetSlot: MakeSlot(node.Operand), valueType: resultOfIncrementType); } } if (!setResult) { SetNotNullResult(node); } return null; } public override BoundNode? VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { var left = node.Left; var right = node.Right; Visit(left); TypeWithAnnotations declaredType = LvalueResultType; TypeWithAnnotations leftLValueType = declaredType; TypeWithState leftResultType = ResultType; Debug.Assert(!IsConditionalState); TypeWithState leftOnRightType = GetAdjustedResult(leftResultType, MakeSlot(node.Left)); // https://github.com/dotnet/roslyn/issues/29962 Update operator based on inferred argument types. if ((object)node.Operator.LeftType != null) { // https://github.com/dotnet/roslyn/issues/29962 Ignoring top-level nullability of operator left parameter. leftOnRightType = VisitConversion( conversionOpt: null, node.Left, node.LeftConversion, TypeWithAnnotations.Create(node.Operator.LeftType), leftOnRightType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment, reportTopLevelWarnings: false, reportRemainingWarnings: true); } else { leftOnRightType = default; } TypeWithState resultType; TypeWithState rightType = VisitRvalueWithState(right); if ((object)node.Operator.ReturnType != null) { if (node.Operator.Kind.IsUserDefined() && (object)node.Operator.Method != null && node.Operator.Method.ParameterCount == 2) { MethodSymbol method = node.Operator.Method; VisitArguments(node, ImmutableArray.Create(node.Left, right), method.ParameterRefKinds, method.Parameters, argsToParamsOpt: default, defaultArguments: default, expanded: true, invokedAsExtensionMethod: false, method); } resultType = InferResultNullability(node.Operator.Kind, node.Operator.Method, node.Operator.ReturnType, leftOnRightType, rightType); FlowAnalysisAnnotations leftAnnotations = GetLValueAnnotations(node.Left); leftLValueType = ApplyLValueAnnotations(leftLValueType, leftAnnotations); resultType = VisitConversion( conversionOpt: null, node, node.FinalConversion, leftLValueType, resultType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); // If the LHS has annotations, we perform an additional check for nullable value types CheckDisallowedNullAssignment(resultType, leftAnnotations, node.Syntax.Location); } else { resultType = TypeWithState.Create(node.Type, NullableFlowState.NotNull); } AdjustSetValue(left, ref resultType); TrackNullableStateForAssignment(node, leftLValueType, MakeSlot(node.Left), resultType); SetResultType(node, resultType); return null; } public override BoundNode? VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { var initializer = node.Expression; if (initializer.Kind == BoundKind.AddressOfOperator) { initializer = ((BoundAddressOfOperator)initializer).Operand; } VisitRvalue(initializer); if (node.Expression.Kind == BoundKind.AddressOfOperator) { SetResultType(node.Expression, TypeWithState.Create(node.Expression.Type, ResultType.State)); } SetNotNullResult(node); return null; } public override BoundNode? VisitAddressOfOperator(BoundAddressOfOperator node) { Visit(node.Operand); SetNotNullResult(node); return null; } private void ReportArgumentWarnings(BoundExpression argument, TypeWithState argumentType, ParameterSymbol parameter) { var paramType = parameter.TypeWithAnnotations; ReportNullableAssignmentIfNecessary(argument, paramType, argumentType, useLegacyWarnings: false, AssignmentKind.Argument, parameterOpt: parameter); if (argumentType.Type is { } argType && IsNullabilityMismatch(paramType.Type, argType)) { ReportNullabilityMismatchInArgument(argument.Syntax, argType, parameter, paramType.Type, forOutput: false); } } private void ReportNullabilityMismatchInRefArgument(BoundExpression argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, argument.Syntax, argumentType, parameterType, GetParameterAsDiagnosticArgument(parameter), GetContainingSymbolAsDiagnosticArgument(parameter)); } /// <summary> /// Report warning passing argument where nested nullability does not match /// parameter (e.g.: calling `void F(object[] o)` with `F(new[] { maybeNull })`). /// </summary> private void ReportNullabilityMismatchInArgument(SyntaxNode argument, TypeSymbol argumentType, ParameterSymbol parameter, TypeSymbol parameterType, bool forOutput) { ReportNullabilityMismatchInArgument(argument.GetLocation(), argumentType, parameter, parameterType, forOutput); } private void ReportNullabilityMismatchInArgument(Location argumentLocation, TypeSymbol argumentType, ParameterSymbol? parameterOpt, TypeSymbol parameterType, bool forOutput) { ReportDiagnostic(forOutput ? ErrorCode.WRN_NullabilityMismatchInArgumentForOutput : ErrorCode.WRN_NullabilityMismatchInArgument, argumentLocation, argumentType, parameterOpt?.Type.IsNonNullableValueType() == true && parameterType.IsNullableType() ? parameterOpt.Type : parameterType, // Compensate for operator lifting GetParameterAsDiagnosticArgument(parameterOpt), GetContainingSymbolAsDiagnosticArgument(parameterOpt)); } private TypeWithAnnotations GetDeclaredLocalResult(LocalSymbol local) { return _variables.TryGetType(local, out TypeWithAnnotations type) ? type : local.TypeWithAnnotations; } private TypeWithAnnotations GetDeclaredParameterResult(ParameterSymbol parameter) { return _variables.TryGetType(parameter, out TypeWithAnnotations type) ? type : parameter.TypeWithAnnotations; } public override BoundNode? VisitBaseReference(BoundBaseReference node) { VisitThisOrBaseReference(node); return null; } public override BoundNode? VisitFieldAccess(BoundFieldAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); SetUpdatedSymbol(node, node.FieldSymbol, updatedSymbol); return null; } public override BoundNode? VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; var updatedMember = VisitMemberAccess(node, node.ReceiverOpt, property); if (!IsAnalyzingAttribute) { if (_expressionIsRead) { ApplyMemberPostConditions(node.ReceiverOpt, property.GetMethod); } else { ApplyMemberPostConditions(node.ReceiverOpt, property.SetMethod); } } SetUpdatedSymbol(node, property, updatedMember); return null; } public override BoundNode? VisitIndexerAccess(BoundIndexerAccess node) { var receiverOpt = node.ReceiverOpt; var receiverType = VisitRvalueWithState(receiverOpt).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); var indexer = node.Indexer; if (receiverType is object) { // Update indexer based on inferred receiver type. indexer = (PropertySymbol)AsMemberOfType(receiverType, indexer); } VisitArguments(node, node.Arguments, node.ArgumentRefKindsOpt, indexer, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded); var resultType = ApplyUnconditionalAnnotations(indexer.TypeWithAnnotations.ToTypeWithState(), GetRValueAnnotations(indexer)); SetResult(node, resultType, indexer.TypeWithAnnotations); SetUpdatedSymbol(node, node.Indexer, indexer); return null; } public override BoundNode? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).Type; // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); return null; } public override BoundNode? VisitEventAccess(BoundEventAccess node) { var updatedSymbol = VisitMemberAccess(node, node.ReceiverOpt, node.EventSymbol); SetUpdatedSymbol(node, node.EventSymbol, updatedSymbol); return null; } private Symbol VisitMemberAccess(BoundExpression node, BoundExpression? receiverOpt, Symbol member) { Debug.Assert(!IsConditionalState); var receiverType = (receiverOpt != null) ? VisitRvalueWithState(receiverOpt) : default; SpecialMember? nullableOfTMember = null; if (member.RequiresInstanceReceiver()) { member = AsMemberOfType(receiverType.Type, member); nullableOfTMember = GetNullableOfTMember(member); // https://github.com/dotnet/roslyn/issues/30598: For l-values, mark receiver as not null // after RHS has been visited, and only if the receiver has not changed. bool skipReceiverNullCheck = nullableOfTMember != SpecialMember.System_Nullable_T_get_Value; _ = CheckPossibleNullReceiver(receiverOpt, checkNullableValueType: !skipReceiverNullCheck); } var type = member.GetTypeOrReturnType(); var memberAnnotations = GetRValueAnnotations(member); var resultType = ApplyUnconditionalAnnotations(type.ToTypeWithState(), memberAnnotations); // We are supposed to track information for the node. Use whatever we managed to // accumulate so far. if (PossiblyNullableType(resultType.Type)) { int slot = MakeMemberSlot(receiverOpt, member); if (this.State.HasValue(slot)) { var state = this.State[slot]; resultType = TypeWithState.Create(resultType.Type, state); } } Debug.Assert(!IsConditionalState); if (nullableOfTMember == SpecialMember.System_Nullable_T_get_HasValue && !(receiverOpt is null)) { int containingSlot = MakeSlot(receiverOpt); if (containingSlot > 0) { Split(); this.StateWhenTrue[containingSlot] = NullableFlowState.NotNull; } } SetResult(node, resultType, type); return member; } private SpecialMember? GetNullableOfTMember(Symbol member) { if (member.Kind == SymbolKind.Property) { var getMethod = ((PropertySymbol)member.OriginalDefinition).GetMethod; if ((object)getMethod != null && getMethod.ContainingType.SpecialType == SpecialType.System_Nullable_T) { if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value)) { return SpecialMember.System_Nullable_T_get_Value; } if (getMethod == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue)) { return SpecialMember.System_Nullable_T_get_HasValue; } } } return null; } private int GetNullableOfTValueSlot(TypeSymbol containingType, int containingSlot, out Symbol? valueProperty, bool forceSlotEvenIfEmpty = false) { Debug.Assert(containingType.IsNullableType()); Debug.Assert(TypeSymbol.Equals(NominalSlotType(containingSlot), containingType, TypeCompareKind.ConsiderEverything2)); var getValue = (MethodSymbol)compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value); valueProperty = getValue?.AsMember((NamedTypeSymbol)containingType)?.AssociatedSymbol; return (valueProperty is null) ? -1 : GetOrCreateSlot(valueProperty, containingSlot, forceSlotEvenIfEmpty: forceSlotEvenIfEmpty); } protected override void VisitForEachExpression(BoundForEachStatement node) { if (node.Expression.Kind != BoundKind.Conversion) { // If we're in this scenario, there was a binding error, and we should suppress any further warnings. Debug.Assert(node.HasErrors); VisitRvalue(node.Expression); return; } var (expr, conversion) = RemoveConversion(node.Expression, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(node.Expression, expr); // There are 7 ways that a foreach can be created: // 1. The collection type is an array type. For this, initial binding will generate an implicit reference conversion to // IEnumerable, and we do not need to do any reinferring of enumerators here. // 2. The collection type is dynamic. For this we do the same as 1. // 3. The collection type implements the GetEnumerator pattern. For this, there is an identity conversion. Because // this identity conversion uses nested types from initial binding, we cannot trust them and must instead use // the type of the expression returned from VisitResult to reinfer the enumerator information. // 4. The collection type implements IEnumerable<T>. Only a few cases can hit this without being caught by number 3, // such as a type with a private implementation of IEnumerable<T>, or a type parameter constrained to that type. // In these cases, there will be an implicit conversion to IEnumerable<T>, but this will use types from // initial binding. For this scenario, we need to look through the list of implemented interfaces on the type and // find the version of IEnumerable<T> that it has after nullable analysis, as type substitution could have changed // nested nullability of type parameters. See ForEach_22 for a concrete example of this. // 5. The collection type implements IEnumerable (non-generic). Because this version isn't generic, we don't need to // do any reinference, and the existing conversion can stand as is. // 6. The target framework's System.String doesn't implement IEnumerable. This is a compat case: System.String normally // does implement IEnumerable, but there are certain target frameworks where this isn't the case. The compiler will // still emit code for foreach in these scenarios. // 7. The collection type implements the GetEnumerator pattern via an extension GetEnumerator. For this, there will be // conversion to the parameter of the extension method. // 8. Some binding error occurred, and some other error has already been reported. Usually this doesn't have any kind // of conversion on top, but if there was an explicit conversion in code then we could get past the initial check // for a BoundConversion node. var resultTypeWithState = VisitRvalueWithState(expr); var resultType = resultTypeWithState.Type; Debug.Assert(resultType is object); SetAnalyzedNullability(expr, _visitResult); TypeWithAnnotations targetTypeWithAnnotations; MethodSymbol? reinferredGetEnumeratorMethod = null; if (node.EnumeratorInfoOpt?.GetEnumeratorInfo is { Method: { IsExtensionMethod: true, Parameters: var parameters } } enumeratorMethodInfo) { // this is case 7 // We do not need to do this same analysis for non-extension methods because they do not have generic parameters that // can be inferred from usage like extension methods can. We don't warn about default arguments at the call site, so // there's nothing that can be learned from the non-extension case. var (method, results, _) = VisitArguments( node, enumeratorMethodInfo.Arguments, refKindsOpt: default, parameters, argsToParamsOpt: enumeratorMethodInfo.ArgsToParamsOpt, defaultArguments: enumeratorMethodInfo.DefaultArguments, expanded: false, invokedAsExtensionMethod: true, enumeratorMethodInfo.Method); targetTypeWithAnnotations = results[0].LValueType; reinferredGetEnumeratorMethod = method; } else if (conversion.IsIdentity || (conversion.Kind == ConversionKind.ExplicitReference && resultType.SpecialType == SpecialType.System_String)) { // This is case 3 or 6. targetTypeWithAnnotations = resultTypeWithState.ToTypeWithAnnotations(compilation); } else if (conversion.IsImplicit) { bool isAsync = node.AwaitOpt != null; if (node.Expression.Type!.SpecialType == SpecialType.System_Collections_IEnumerable) { // If this is a conversion to IEnumerable (non-generic), nothing to do. This is cases 1, 2, and 5. targetTypeWithAnnotations = TypeWithAnnotations.Create(node.Expression.Type); } else if (ForEachLoopBinder.IsIEnumerableT(node.Expression.Type.OriginalDefinition, isAsync, compilation)) { // This is case 4. We need to look for the IEnumerable<T> that this reinferred expression implements, // so that we pick up any nested type substitutions that could have occurred. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; targetTypeWithAnnotations = TypeWithAnnotations.Create(ForEachLoopBinder.GetIEnumerableOfT(resultType, isAsync, compilation, ref discardedUseSiteInfo, out bool foundMultiple)); Debug.Assert(!foundMultiple); Debug.Assert(targetTypeWithAnnotations.HasType); } else { // This is case 8. There was not a successful binding, as a successful binding will _always_ generate one of the // above conversions. Just return, as we want to suppress further errors. return; } } else { // This is also case 8. return; } var convertedResult = VisitConversion( GetConversionIfApplicable(node.Expression, expr), expr, conversion, targetTypeWithAnnotations, resultTypeWithState, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Assignment); bool reportedDiagnostic = node.EnumeratorInfoOpt?.GetEnumeratorInfo.Method is { IsExtensionMethod: true } ? false : CheckPossibleNullReceiver(expr); SetAnalyzedNullability(node.Expression, new VisitResult(convertedResult, convertedResult.ToTypeWithAnnotations(compilation))); TypeWithState currentPropertyGetterTypeWithState; if (node.EnumeratorInfoOpt is null) { currentPropertyGetterTypeWithState = default; } else if (resultType is ArrayTypeSymbol arrayType) { // Even though arrays use the IEnumerator pattern, we use the array element type as the foreach target type, so // directly get our source type from there instead of doing method reinference. currentPropertyGetterTypeWithState = arrayType.ElementTypeWithAnnotations.ToTypeWithState(); } else if (resultType.SpecialType == SpecialType.System_String) { // There are frameworks where System.String does not implement IEnumerable, but we still lower it to a for loop // using the indexer over the individual characters anyway. So the type must be not annotated char. currentPropertyGetterTypeWithState = TypeWithAnnotations.Create(node.EnumeratorInfoOpt.ElementType, NullableAnnotation.NotAnnotated).ToTypeWithState(); } else { // Reinfer the return type of the node.Expression.GetEnumerator().Current property, so that if // the collection changed nested generic types we pick up those changes. reinferredGetEnumeratorMethod ??= (MethodSymbol)AsMemberOfType(convertedResult.Type, node.EnumeratorInfoOpt.GetEnumeratorInfo.Method); var enumeratorReturnType = GetReturnTypeWithState(reinferredGetEnumeratorMethod); if (enumeratorReturnType.State != NullableFlowState.NotNull) { if (!reportedDiagnostic && !(node.Expression is BoundConversion { Operand: { IsSuppressed: true } })) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, expr.Syntax.GetLocation()); } } var currentPropertyGetter = (MethodSymbol)AsMemberOfType(enumeratorReturnType.Type, node.EnumeratorInfoOpt.CurrentPropertyGetter); currentPropertyGetterTypeWithState = ApplyUnconditionalAnnotations( currentPropertyGetter.ReturnTypeWithAnnotations.ToTypeWithState(), currentPropertyGetter.ReturnTypeFlowAnalysisAnnotations); // Analyze `await MoveNextAsync()` if (node.AwaitOpt is { AwaitableInstancePlaceholder: BoundAwaitableValuePlaceholder moveNextPlaceholder } awaitMoveNextInfo) { var moveNextAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, node.EnumeratorInfoOpt.MoveNextInfo.Method); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(moveNextPlaceholder); } // Analyze `await DisposeAsync()` if (node.EnumeratorInfoOpt is { NeedsDisposal: true, DisposeAwaitableInfo: BoundAwaitableInfo awaitDisposalInfo }) { var disposalPlaceholder = awaitDisposalInfo.AwaitableInstancePlaceholder; bool addedPlaceholder = false; if (node.EnumeratorInfoOpt.PatternDisposeInfo is { Method: var originalDisposeMethod }) // no statically known Dispose method if doing a runtime check { Debug.Assert(disposalPlaceholder is not null); var disposeAsyncMethod = (MethodSymbol)AsMemberOfType(reinferredGetEnumeratorMethod.ReturnType, originalDisposeMethod); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(disposalPlaceholder!); } } } SetResultType(expression: null, currentPropertyGetterTypeWithState); } public override void VisitForEachIterationVariables(BoundForEachStatement node) { // ResultType should have been set by VisitForEachExpression, called just before this. var sourceState = node.EnumeratorInfoOpt == null ? default : ResultType; TypeWithAnnotations sourceType = sourceState.ToTypeWithAnnotations(compilation); #pragma warning disable IDE0055 // Fix formatting var variableLocation = node.Syntax switch { ForEachStatementSyntax statement => statement.Identifier.GetLocation(), ForEachVariableStatementSyntax variableStatement => variableStatement.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Syntax) }; #pragma warning restore IDE0055 // Fix formatting if (node.DeconstructionOpt is object) { var assignment = node.DeconstructionOpt.DeconstructionAssignment; // Visit the assignment as a deconstruction with an explicit type VisitDeconstructionAssignmentOperator(assignment, sourceState.HasNullType ? (TypeWithState?)null : sourceState); // https://github.com/dotnet/roslyn/issues/35010: if the iteration variable is a tuple deconstruction, we need to put something in the tree Visit(node.IterationVariableType); } else { Visit(node.IterationVariableType); foreach (var iterationVariable in node.IterationVariables) { var state = NullableFlowState.NotNull; if (!sourceState.HasNullType) { TypeWithAnnotations destinationType = iterationVariable.TypeWithAnnotations; TypeWithState result = sourceState; TypeWithState resultForType = sourceState; if (iterationVariable.IsRef) { // foreach (ref DestinationType variable in collection) if (IsNullabilityMismatch(sourceType, destinationType)) { var foreachSyntax = (ForEachStatementSyntax)node.Syntax; ReportNullabilityMismatchInAssignment(foreachSyntax.Type, sourceType, destinationType); } } else if (iterationVariable is SourceLocalSymbol { IsVar: true }) { // foreach (var variable in collection) destinationType = sourceState.ToAnnotatedTypeWithAnnotations(compilation); _variables.SetType(iterationVariable, destinationType); resultForType = destinationType.ToTypeWithState(); } else { // foreach (DestinationType variable in collection) // and asynchronous variants var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion conversion = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; result = VisitConversion( conversionOpt: null, conversionOperand: node.IterationVariableType, conversion, destinationType, sourceState, checkConversion: true, fromExplicitCast: !conversion.IsImplicit, useLegacyWarnings: true, AssignmentKind.ForEachIterationVariable, reportTopLevelWarnings: true, reportRemainingWarnings: true, diagnosticLocationOpt: variableLocation); } // In non-error cases we'll only run this loop a single time. In error cases we'll set the nullability of the VariableType multiple times, but at least end up with something SetAnalyzedNullability(node.IterationVariableType, new VisitResult(resultForType, destinationType), isLvalue: true); state = result.State; } int slot = GetOrCreateSlot(iterationVariable); if (slot > 0) { this.State[slot] = state; } } } } public override BoundNode? VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { var result = base.VisitFromEndIndexExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitObjectInitializerMember(BoundObjectInitializerMember node) { // Should be handled by VisitObjectCreationExpression. throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { SetNotNullResult(node); return null; } public override BoundNode? VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { // https://github.com/dotnet/roslyn/issues/35042, we need to implement similar workarounds for object, collection, and dynamic initializers. if (child is BoundLambda lambda) { TakeIncrementalSnapshot(lambda); VisitLambda(lambda, delegateTypeOpt: null); VisitRvalueEpilogue(lambda); } else { VisitRvalue(child as BoundExpression); } } var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return null; } public override BoundNode? VisitTypeExpression(BoundTypeExpression node) { var result = base.VisitTypeExpression(node); if (node.BoundContainingTypeOpt != null) { VisitTypeExpression(node.BoundContainingTypeOpt); } SetNotNullResult(node); return result; } public override BoundNode? VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // These should not appear after initial binding except in error cases. var result = base.VisitTypeOrValueExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitUnaryOperator(BoundUnaryOperator node) { Debug.Assert(!IsConditionalState); TypeWithState resultType; switch (node.OperatorKind) { case UnaryOperatorKind.BoolLogicalNegation: Visit(node.Operand); if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicTrue: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); resultType = adjustForLifting(ResultType); break; case UnaryOperatorKind.DynamicLogicalNegation: // We cannot use VisitCondition, because the operand is not of type bool. // Yet we want to keep the result split if it was split. So we simply visit. Visit(node.Operand); // If the state is split, the result is `bool` at runtime and we invert it here. if (IsConditionalState) SetConditionalState(StateWhenFalse, StateWhenTrue); resultType = adjustForLifting(ResultType); break; default: if (node.OperatorKind.IsUserDefined() && node.MethodOpt is MethodSymbol method && method.ParameterCount == 1) { var (operand, conversion) = RemoveConversion(node.Operand, includeExplicitConversions: false); VisitRvalue(operand); var operandResult = ResultType; bool isLifted = node.OperatorKind.IsLifted(); var operandType = GetNullableUnderlyingTypeIfNecessary(isLifted, operandResult); // Update method based on inferred operand type. method = (MethodSymbol)AsMemberOfType(operandType.Type!.StrippedType(), method); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var parameter = method.Parameters[0]; _ = VisitConversion( node.Operand as BoundConversion, operand, conversion, parameter.TypeWithAnnotations, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, assignmentKind: AssignmentKind.Argument, parameterOpt: parameter); resultType = GetLiftedReturnTypeIfNecessary(isLifted, method.ReturnTypeWithAnnotations, operandResult.State); SetUpdatedSymbol(node, node.MethodOpt, method); } else { VisitRvalue(node.Operand); resultType = adjustForLifting(ResultType); } break; } SetResultType(node, resultType); return null; TypeWithState adjustForLifting(TypeWithState argumentResult) => TypeWithState.Create(node.Type, node.OperatorKind.IsLifted() ? argumentResult.State : NullableFlowState.NotNull); } public override BoundNode? VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { var result = base.VisitPointerIndirectionOperator(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitPointerElementAccess(BoundPointerElementAccess node) { var result = base.VisitPointerElementAccess(node); var type = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, type); return result; } public override BoundNode? VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); SetNotNullResult(node); return null; } public override BoundNode? VisitMakeRefOperator(BoundMakeRefOperator node) { var result = base.VisitMakeRefOperator(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRefValueOperator(BoundRefValueOperator node) { var result = base.VisitRefValueOperator(node); var type = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetLvalueResultType(node, type); return result; } private TypeWithState InferResultNullability(BoundUserDefinedConditionalLogicalOperator node) { if (node.OperatorKind.IsLifted()) { // https://github.com/dotnet/roslyn/issues/33879 Conversions: Lifted operator // Should this use the updated flow type and state? How should it compute nullability? return TypeWithState.Create(node.Type, NullableFlowState.NotNull); } // Update method based on inferred operand types: see https://github.com/dotnet/roslyn/issues/29605. // Analyze operator result properly (honoring [Maybe|NotNull] and [Maybe|NotNullWhen] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if ((object)node.LogicalOperator != null && node.LogicalOperator.ParameterCount == 2) { return GetReturnTypeWithState(node.LogicalOperator); } else { return default; } } protected override void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression node, BoundExpression right, bool isAnd, bool isBool, ref LocalState leftTrue, ref LocalState leftFalse) { Debug.Assert(!IsConditionalState); TypeWithState leftType = ResultType; // https://github.com/dotnet/roslyn/issues/29605 Update operator methods based on inferred operand types. MethodSymbol? logicalOperator = null; MethodSymbol? trueFalseOperator = null; BoundExpression? left = null; switch (node.Kind) { case BoundKind.BinaryOperator: Debug.Assert(!((BoundBinaryOperator)node).OperatorKind.IsUserDefined()); break; case BoundKind.UserDefinedConditionalLogicalOperator: var binary = (BoundUserDefinedConditionalLogicalOperator)node; if (binary.LogicalOperator != null && binary.LogicalOperator.ParameterCount == 2) { logicalOperator = binary.LogicalOperator; left = binary.Left; trueFalseOperator = isAnd ? binary.FalseOperator : binary.TrueOperator; if ((object)trueFalseOperator != null && trueFalseOperator.ParameterCount != 1) { trueFalseOperator = null; } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } Debug.Assert(trueFalseOperator is null || logicalOperator is object); Debug.Assert(logicalOperator is null || left is object); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 if (trueFalseOperator is object) { ReportArgumentWarnings(left!, leftType, trueFalseOperator.Parameters[0]); } if (logicalOperator is object) { ReportArgumentWarnings(left!, leftType, logicalOperator.Parameters[0]); } Visit(right); TypeWithState rightType = ResultType; SetResultType(node, InferResultNullabilityOfBinaryLogicalOperator(node, leftType, rightType)); if (logicalOperator is object) { ReportArgumentWarnings(right, rightType, logicalOperator.Parameters[1]); } AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(node, right, isAnd, isBool, ref leftTrue, ref leftFalse); } private TypeWithState InferResultNullabilityOfBinaryLogicalOperator(BoundExpression node, TypeWithState leftType, TypeWithState rightType) { return node switch { BoundBinaryOperator binary => InferResultNullability(binary.OperatorKind, binary.Method, binary.Type, leftType, rightType), BoundUserDefinedConditionalLogicalOperator userDefined => InferResultNullability(userDefined), _ => throw ExceptionUtilities.UnexpectedValue(node) }; } public override BoundNode? VisitAwaitExpression(BoundAwaitExpression node) { var result = base.VisitAwaitExpression(node); var awaitableInfo = node.AwaitableInfo; var placeholder = awaitableInfo.AwaitableInstancePlaceholder; Debug.Assert(placeholder is object); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(placeholder); if (node.Type.IsValueType || node.HasErrors || awaitableInfo.GetResult is null) { SetNotNullResult(node); } else { // It is possible for the awaiter type returned from GetAwaiter to not be a named type. e.g. it could be a type parameter. // Proper handling of this is additional work which only benefits a very uncommon scenario, // so we will just use the originally bound GetResult method in this case. var getResult = awaitableInfo.GetResult; var reinferredGetResult = _visitResult.RValueType.Type is NamedTypeSymbol taskAwaiterType ? getResult.OriginalDefinition.AsMember(taskAwaiterType) : getResult; SetResultType(node, reinferredGetResult.ReturnTypeWithAnnotations.ToTypeWithState()); } return result; } public override BoundNode? VisitTypeOfOperator(BoundTypeOfOperator node) { var result = base.VisitTypeOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitMethodInfo(BoundMethodInfo node) { var result = base.VisitMethodInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitFieldInfo(BoundFieldInfo node) { var result = base.VisitFieldInfo(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { // Can occur in error scenarios and lambda scenarios var result = base.VisitDefaultLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.MaybeDefault)); return result; } public override BoundNode? VisitDefaultExpression(BoundDefaultExpression node) { Debug.Assert(!this.IsConditionalState); var result = base.VisitDefaultExpression(node); TypeSymbol type = node.Type; if (EmptyStructTypeCache.IsTrackableStructType(type)) { int slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { this.State[slot] = NullableFlowState.NotNull; InheritNullableStateOfTrackableStruct(type, slot, valueSlot: -1, isDefaultValue: true); } } // https://github.com/dotnet/roslyn/issues/33344: this fails to produce an updated tuple type for a default expression // (should produce nullable element types for those elements that are of reference types) SetResultType(node, TypeWithState.ForType(type)); return result; } public override BoundNode? VisitIsOperator(BoundIsOperator node) { Debug.Assert(!this.IsConditionalState); var operand = node.Operand; var typeExpr = node.TargetType; VisitPossibleConditionalAccess(operand, out var conditionalStateWhenNotNull); Unsplit(); LocalState stateWhenNotNull; if (!conditionalStateWhenNotNull.IsConditionalState) { stateWhenNotNull = conditionalStateWhenNotNull.State; } else { stateWhenNotNull = conditionalStateWhenNotNull.StateWhenTrue; Join(ref stateWhenNotNull, ref conditionalStateWhenNotNull.StateWhenFalse); } Debug.Assert(node.Type.SpecialType == SpecialType.System_Boolean); SetConditionalState(stateWhenNotNull, State); if (typeExpr.Type?.SpecialType == SpecialType.System_Object) { LearnFromNullTest(operand, ref StateWhenFalse); } VisitTypeExpression(typeExpr); SetNotNullResult(node); return null; } public override BoundNode? VisitAsOperator(BoundAsOperator node) { var argumentType = VisitRvalueWithState(node.Operand); NullableFlowState resultState = NullableFlowState.NotNull; var type = node.Type; if (type.CanContainNull()) { switch (node.Conversion.Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitNullable: resultState = argumentType.State; break; default: resultState = NullableFlowState.MaybeDefault; break; } } VisitTypeExpression(node.TargetType); SetResultType(node, TypeWithState.Create(type, resultState)); return null; } public override BoundNode? VisitSizeOfOperator(BoundSizeOfOperator node) { var result = base.VisitSizeOfOperator(node); VisitTypeExpression(node.SourceType); SetNotNullResult(node); return result; } public override BoundNode? VisitArgList(BoundArgList node) { var result = base.VisitArgList(node); Debug.Assert(node.Type.SpecialType == SpecialType.System_RuntimeArgumentHandle); SetNotNullResult(node); return result; } public override BoundNode? VisitArgListOperator(BoundArgListOperator node) { VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type is null); SetNotNullResult(node); return null; } public override BoundNode? VisitLiteral(BoundLiteral node) { Debug.Assert(!IsConditionalState); var result = base.VisitLiteral(node); SetResultType(node, TypeWithState.Create(node.Type, node.Type?.CanContainNull() != false && node.ConstantValue?.IsNull == true ? NullableFlowState.MaybeDefault : NullableFlowState.NotNull)); return result; } public override BoundNode? VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var result = base.VisitPreviousSubmissionReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { var result = base.VisitHostObjectMemberReference(node); Debug.Assert(node.WasCompilerGenerated); SetNotNullResult(node); return result; } public override BoundNode? VisitPseudoVariable(BoundPseudoVariable node) { var result = base.VisitPseudoVariable(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeExpression(BoundRangeExpression node) { var result = base.VisitRangeExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitRangeVariable(BoundRangeVariable node) { VisitWithoutDiagnostics(node.Value); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Need to review this return null; } public override BoundNode? VisitLabel(BoundLabel node) { var result = base.VisitLabel(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); _ = CheckPossibleNullReceiver(receiver); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitDynamicInvocation(BoundDynamicInvocation node) { var expr = node.Expression; VisitRvalue(expr); // If the expression was a MethodGroup, check nullability of receiver. var receiverOpt = (expr as BoundMethodGroup)?.ReceiverOpt; if (TryGetMethodGroupReceiverNullability(receiverOpt, out TypeWithState receiverType)) { CheckPossibleNullReceiver(receiverOpt, receiverType, checkNullableValueType: false); } VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); Debug.Assert(node.Type.IsReferenceType); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } public override BoundNode? VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { var receiverOpt = node.ReceiverOpt; VisitRvalue(receiverOpt); Debug.Assert(!IsConditionalState); var @event = node.Event; if (!@event.IsStatic) { @event = (EventSymbol)AsMemberOfType(ResultType.Type, @event); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after arguments have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiverOpt); SetUpdatedSymbol(node, node.Event, @event); } VisitRvalue(node.Argument); // https://github.com/dotnet/roslyn/issues/31018: Check for delegate mismatch. if (node.Argument.ConstantValue?.IsNull != true && MakeMemberSlot(receiverOpt, @event) is > 0 and var memberSlot) { this.State[memberSlot] = node.IsAddition ? this.State[memberSlot].Meet(ResultType.State) : NullableFlowState.MaybeNull; } SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29969 Review whether this is the correct result return null; } public override BoundNode? VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { // Only reachable from bad expression. Otherwise handled in VisitObjectCreationExpression(). // https://github.com/dotnet/roslyn/issues/35042: Do we need to analyze child expressions anyway for the public API? SetNotNullResult(node); return null; } public override BoundNode? VisitImplicitReceiver(BoundImplicitReceiver node) { var result = base.VisitImplicitReceiver(node); SetNotNullResult(node); return result; } public override BoundNode? VisitAnonymousPropertyDeclaration(BoundAnonymousPropertyDeclaration node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); return null; } public override BoundNode? VisitArrayInitialization(BoundArrayInitialization node) { var result = base.VisitArrayInitialization(node); SetNotNullResult(node); return result; } private void SetUnknownResultNullability(BoundExpression expression) { SetResultType(expression, TypeWithState.Create(expression.Type, default)); } public override BoundNode? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } public override BoundNode? VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { var receiver = node.Receiver; VisitRvalue(receiver); // https://github.com/dotnet/roslyn/issues/30598: Mark receiver as not null // after indices have been visited, and only if the receiver has not changed. _ = CheckPossibleNullReceiver(receiver); VisitArgumentsEvaluate(node.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); Debug.Assert(node.Type.IsDynamic()); var result = TypeWithAnnotations.Create(node.Type, NullableAnnotation.Oblivious); SetLvalueResultType(node, result); return null; } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, bool checkNullableValueType = false) { return CheckPossibleNullReceiver(receiverOpt, ResultType, checkNullableValueType); } private bool CheckPossibleNullReceiver(BoundExpression? receiverOpt, TypeWithState resultType, bool checkNullableValueType) { Debug.Assert(!this.IsConditionalState); bool reportedDiagnostic = false; if (receiverOpt != null && this.State.Reachable) { var resultTypeSymbol = resultType.Type; if (resultTypeSymbol is null) { return false; } #if DEBUG Debug.Assert(receiverOpt.Type is null || AreCloseEnough(receiverOpt.Type, resultTypeSymbol)); #endif if (!ReportPossibleNullReceiverIfNeeded(resultTypeSymbol, resultType.State, checkNullableValueType, receiverOpt.Syntax, out reportedDiagnostic)) { return reportedDiagnostic; } LearnFromNonNullTest(receiverOpt, ref this.State); } return reportedDiagnostic; } // Returns false if the type wasn't interesting private bool ReportPossibleNullReceiverIfNeeded(TypeSymbol type, NullableFlowState state, bool checkNullableValueType, SyntaxNode syntax, out bool reportedDiagnostic) { reportedDiagnostic = false; if (state.MayBeNull()) { bool isValueType = type.IsValueType; if (isValueType && (!checkNullableValueType || !type.IsNullableTypeOrTypeParameter() || type.GetNullableUnderlyingType().IsErrorType())) { return false; } ReportDiagnostic(isValueType ? ErrorCode.WRN_NullableValueTypeMayBeNull : ErrorCode.WRN_NullReferenceReceiver, syntax); reportedDiagnostic = true; } return true; } private void CheckExtensionMethodThisNullability(BoundExpression expr, Conversion conversion, ParameterSymbol parameter, TypeWithState result) { VisitArgumentConversionAndInboundAssignmentsAndPreConditions( conversionOpt: null, expr, conversion, parameter.RefKind, parameter, parameter.TypeWithAnnotations, GetParameterAnnotations(parameter), new VisitArgumentResult(new VisitResult(result, result.ToTypeWithAnnotations(compilation)), stateForLambda: default), extensionMethodThisArgument: true); } private static bool IsNullabilityMismatch(TypeWithAnnotations type1, TypeWithAnnotations type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } public override BoundNode? VisitQueryClause(BoundQueryClause node) { var result = base.VisitQueryClause(node); SetNotNullResult(node); // https://github.com/dotnet/roslyn/issues/29863 Implement nullability analysis in LINQ queries return result; } public override BoundNode? VisitNameOfOperator(BoundNameOfOperator node) { var result = base.VisitNameOfOperator(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNamespaceExpression(BoundNamespaceExpression node) { var result = base.VisitNamespaceExpression(node); SetUnknownResultNullability(node); return result; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} public override BoundNode? VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // This is only involved with unbound lambdas or when visiting the source of a converted tuple literal var result = base.VisitUnconvertedInterpolatedString(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitStringInsert(BoundStringInsert node) { var result = base.VisitStringInsert(node); SetUnknownResultNullability(node); return result; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } public override BoundNode? VisitDiscardExpression(BoundDiscardExpression node) { var result = TypeWithAnnotations.Create(node.Type); var rValueType = TypeWithState.ForType(node.Type); SetResult(node, rValueType, result); return null; } public override BoundNode? VisitThrowExpression(BoundThrowExpression node) { VisitThrow(node.Expression); SetResultType(node, default); return null; } public override BoundNode? VisitThrowStatement(BoundThrowStatement node) { VisitThrow(node.ExpressionOpt); return null; } private void VisitThrow(BoundExpression? expr) { if (expr != null) { var result = VisitRvalueWithState(expr); // Cases: // null // null! // Other (typed) expression, including suppressed ones if (result.MayBeNull) { ReportDiagnostic(ErrorCode.WRN_ThrowPossibleNull, expr.Syntax); } } SetUnreachable(); } public override BoundNode? VisitYieldReturnStatement(BoundYieldReturnStatement node) { BoundExpression expr = node.Expression; if (expr == null) { return null; } var method = (MethodSymbol)CurrentSymbol; TypeWithAnnotations elementType = InMethodBinder.GetIteratorElementTypeFromReturnType(compilation, RefKind.None, method.ReturnType, errorLocation: null, diagnostics: null); _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Return); return null; } protected override void VisitCatchBlock(BoundCatchBlock node, ref LocalState finallyState) { TakeIncrementalSnapshot(node); if (node.Locals.Length > 0) { LocalSymbol local = node.Locals[0]; if (local.DeclarationKind == LocalDeclarationKind.CatchVariable) { int slot = GetOrCreateSlot(local); if (slot > 0) this.State[slot] = NullableFlowState.NotNull; } } if (node.ExceptionSourceOpt != null) { VisitWithoutDiagnostics(node.ExceptionSourceOpt); } base.VisitCatchBlock(node, ref finallyState); } public override BoundNode? VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); _ = CheckPossibleNullReceiver(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode? VisitAttribute(BoundAttribute node) { VisitArguments(node, node.ConstructorArguments, ImmutableArray<RefKind>.Empty, node.Constructor, argsToParamsOpt: node.ConstructorArgumentsToParamsOpt, defaultArguments: default, expanded: node.ConstructorExpanded, invokedAsExtensionMethod: false); foreach (var assignment in node.NamedArguments) { Visit(assignment); } SetNotNullResult(node); return null; } public override BoundNode? VisitExpressionWithNullability(BoundExpressionWithNullability node) { var typeWithAnnotations = TypeWithAnnotations.Create(node.Type, node.NullableAnnotation); SetResult(node.Expression, typeWithAnnotations.ToTypeWithState(), typeWithAnnotations); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } public override BoundNode? VisitAwaitableInfo(BoundAwaitableInfo node) { Visit(node.AwaitableInstancePlaceholder); Visit(node.GetAwaiter); return null; } public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { _ = Visit(node.InvokedExpression); Debug.Assert(ResultType is TypeWithState { Type: FunctionPointerTypeSymbol { }, State: NullableFlowState.NotNull }); _ = VisitArguments( node, node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature, argsToParamsOpt: default, defaultArguments: default, expanded: false, invokedAsExtensionMethod: false); var returnTypeWithAnnotations = node.FunctionPointer.Signature.ReturnTypeWithAnnotations; SetResult(node, returnTypeWithAnnotations.ToTypeWithState(), returnTypeWithAnnotations); return null; } protected override string Dump(LocalState state) { return state.Dump(_variables); } protected override bool Meet(ref LocalState self, ref LocalState other) { if (!self.Reachable) return false; if (!other.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Meet(in other); } protected override bool Join(ref LocalState self, ref LocalState other) { if (!other.Reachable) return false; if (!self.Reachable) { self = other.Clone(); return true; } Normalize(ref self); Normalize(ref other); return self.Join(in other); } private void Join(ref PossiblyConditionalState other) { var otherIsConditional = other.IsConditionalState; if (otherIsConditional) { Split(); } if (IsConditionalState) { Join(ref StateWhenTrue, ref otherIsConditional ? ref other.StateWhenTrue : ref other.State); Join(ref StateWhenFalse, ref otherIsConditional ? ref other.StateWhenFalse : ref other.State); } else { Debug.Assert(!otherIsConditional); Join(ref State, ref other.State); } } private LocalState CloneAndUnsplit(ref PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { return conditionalState.State.Clone(); } var state = conditionalState.StateWhenTrue.Clone(); Join(ref state, ref conditionalState.StateWhenFalse); return state; } private void SetPossiblyConditionalState(in PossiblyConditionalState conditionalState) { if (!conditionalState.IsConditionalState) { SetState(conditionalState.State); } else { SetConditionalState(conditionalState.StateWhenTrue, conditionalState.StateWhenFalse); } } internal sealed class LocalStateSnapshot { internal readonly int Id; internal readonly LocalStateSnapshot? Container; internal readonly BitVector State; internal LocalStateSnapshot(int id, LocalStateSnapshot? container, BitVector state) { Id = id; Container = container; State = state; } } /// <summary> /// A bit array containing the nullability of variables associated with a method scope. If the method is a /// nested function (a lambda or a local function), there is a reference to the corresponding instance for /// the containing method scope. The instances in the chain are associated with a corresponding /// <see cref="Variables"/> chain, and the <see cref="Id"/> field in this type matches <see cref="Variables.Id"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LocalState : ILocalDataFlowState { private sealed class Boxed { internal LocalState Value; internal Boxed(LocalState value) { Value = value; } } internal readonly int Id; private readonly Boxed? _container; // The representation of a state is a bit vector with two bits per slot: // (false, false) => NotNull, (false, true) => MaybeNull, (true, true) => MaybeDefault. // Slot 0 is used to represent whether the state is reachable (true) or not. private BitVector _state; private LocalState(int id, Boxed? container, BitVector state) { Id = id; _container = container; _state = state; } internal static LocalState Create(LocalStateSnapshot snapshot) { var container = snapshot.Container is null ? null : new Boxed(Create(snapshot.Container)); return new LocalState(snapshot.Id, container, snapshot.State.Clone()); } internal LocalStateSnapshot CreateSnapshot() { return new LocalStateSnapshot(Id, _container?.Value.CreateSnapshot(), _state.Clone()); } public bool Reachable => _state[0]; public bool NormalizeToBottom => false; public static LocalState ReachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: true); } public static LocalState UnreachableState(Variables variables) { return CreateReachableOrUnreachableState(variables, reachable: false); } private static LocalState CreateReachableOrUnreachableState(Variables variables, bool reachable) { var container = variables.Container is null ? null : new Boxed(CreateReachableOrUnreachableState(variables.Container, reachable)); int capacity = reachable ? variables.NextAvailableIndex : 1; return new LocalState(variables.Id, container, CreateBitVector(capacity, reachable)); } public LocalState CreateNestedMethodState(Variables variables) { Debug.Assert(Id == variables.Container!.Id); return new LocalState(variables.Id, container: new Boxed(this), CreateBitVector(capacity: variables.NextAvailableIndex, reachable: true)); } private static BitVector CreateBitVector(int capacity, bool reachable) { if (capacity < 1) capacity = 1; BitVector state = BitVector.Create(capacity * 2); state[0] = reachable; return state; } private int Capacity => _state.Capacity / 2; private void EnsureCapacity(int capacity) { _state.EnsureCapacity(capacity * 2); } public bool HasVariable(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasVariable(id, index); } private bool HasVariable(int id, int index) { if (Id > id) { return _container!.Value.HasValue(id, index); } else { return Id == id; } } public bool HasValue(int slot) { if (slot <= 0) { return false; } (int id, int index) = Variables.DeconstructSlot(slot); return HasValue(id, index); } private bool HasValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.HasValue(id, index); } else { return index < Capacity; } } public void Normalize(NullableWalker walker, Variables variables) { if (Id != variables.Id) { Debug.Assert(Id < variables.Id); Normalize(walker, variables.Container!); } else { _container?.Value.Normalize(walker, variables.Container!); int start = Capacity; EnsureCapacity(variables.NextAvailableIndex); Populate(walker, start); } } public void PopulateAll(NullableWalker walker) { _container?.Value.PopulateAll(walker); Populate(walker, start: 1); } private void Populate(NullableWalker walker, int start) { int capacity = Capacity; for (int index = start; index < capacity; index++) { int slot = Variables.ConstructSlot(Id, index); SetValue(Id, index, walker.GetDefaultState(ref this, slot)); } } public NullableFlowState this[int slot] { get { (int id, int index) = Variables.DeconstructSlot(slot); return GetValue(id, index); } set { (int id, int index) = Variables.DeconstructSlot(slot); SetValue(id, index, value); } } private NullableFlowState GetValue(int id, int index) { if (Id != id) { Debug.Assert(Id > id); return _container!.Value.GetValue(id, index); } else { if (index < Capacity && this.Reachable) { index *= 2; var result = (_state[index + 1], _state[index]) switch { (false, false) => NullableFlowState.NotNull, (false, true) => NullableFlowState.MaybeNull, (true, false) => throw ExceptionUtilities.UnexpectedValue(index), (true, true) => NullableFlowState.MaybeDefault }; return result; } return NullableFlowState.NotNull; } } private void SetValue(int id, int index, NullableFlowState value) { if (Id != id) { Debug.Assert(Id > id); _container!.Value.SetValue(id, index, value); } else { // No states should be modified in unreachable code, as there is only one unreachable state. if (!this.Reachable) return; index *= 2; _state[index] = (value != NullableFlowState.NotNull); _state[index + 1] = (value == NullableFlowState.MaybeDefault); } } internal void ForEach<TArg>(Action<int, TArg> action, TArg arg) { _container?.Value.ForEach(action, arg); for (int index = 1; index < Capacity; index++) { action(Variables.ConstructSlot(Id, index), arg); } } internal LocalState GetStateForVariables(int id) { var state = this; while (state.Id != id) { state = state._container!.Value; } return state; } /// <summary> /// Produce a duplicate of this flow analysis state. /// </summary> /// <returns></returns> public LocalState Clone() { var container = _container is null ? null : new Boxed(_container.Value.Clone()); return new LocalState(Id, container, _state.Clone()); } public bool Join(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Join(in other._container!.Value)) { result = true; } if (_state.UnionWith(in other._state)) { result = true; } return result; } public bool Meet(in LocalState other) { Debug.Assert(Id == other.Id); bool result = false; if (_container is { } && _container.Value.Meet(in other._container!.Value)) { result = true; } if (_state.IntersectWith(in other._state)) { result = true; } return result; } internal string GetDebuggerDisplay() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(" "); int n = Math.Min(Capacity, 8); for (int i = n - 1; i >= 0; i--) builder.Append(_state[i * 2] ? '?' : '!'); return pooledBuilder.ToStringAndFree(); } internal string Dump(Variables variables) { if (!this.Reachable) return "unreachable"; if (Id != variables.Id) return "invalid"; var builder = PooledStringBuilder.GetInstance(); Dump(builder, variables); return builder.ToStringAndFree(); } private void Dump(StringBuilder builder, Variables variables) { _container?.Value.Dump(builder, variables.Container!); for (int index = 1; index < Capacity; index++) { if (getName(Variables.ConstructSlot(Id, index)) is string name) { builder.Append(name); var annotation = GetValue(Id, index) switch { NullableFlowState.MaybeNull => "?", NullableFlowState.MaybeDefault => "??", _ => "!" }; builder.Append(annotation); } } string? getName(int slot) { VariableIdentifier id = variables[slot]; var name = id.Symbol.Name; int containingSlot = id.ContainingSlot; return containingSlot > 0 ? getName(containingSlot) + "." + name : name; } } } internal sealed class LocalFunctionState : AbstractLocalFunctionState { /// <summary> /// Defines the starting state used in the local function body to /// produce diagnostics and determine types. /// </summary> public LocalState StartingState; public LocalFunctionState(LocalState unreachableState) : base(unreachableState.Clone(), unreachableState.Clone()) { StartingState = unreachableState; } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) { var variables = (symbol.ContainingSymbol is MethodSymbol containingMethod ? _variables.GetVariablesForMethodScope(containingMethod) : null) ?? _variables.GetRootScope(); return new LocalFunctionState(LocalState.UnreachableState(variables)); } private sealed class NullabilityInfoTypeComparer : IEqualityComparer<(NullabilityInfo info, TypeSymbol? type)> { public static readonly NullabilityInfoTypeComparer Instance = new NullabilityInfoTypeComparer(); public bool Equals((NullabilityInfo info, TypeSymbol? type) x, (NullabilityInfo info, TypeSymbol? type) y) { return x.info.Equals(y.info) && Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(x.type, y.type); } public int GetHashCode((NullabilityInfo info, TypeSymbol? type) obj) { return obj.GetHashCode(); } } private sealed class ExpressionAndSymbolEqualityComparer : IEqualityComparer<(BoundNode? expr, Symbol symbol)> { internal static readonly ExpressionAndSymbolEqualityComparer Instance = new ExpressionAndSymbolEqualityComparer(); private ExpressionAndSymbolEqualityComparer() { } public bool Equals((BoundNode? expr, Symbol symbol) x, (BoundNode? expr, Symbol symbol) y) { RoslynDebug.Assert(x.symbol is object); RoslynDebug.Assert(y.symbol is object); // We specifically use reference equality for the symbols here because the BoundNode should be immutable. // We should be storing and retrieving the exact same instance of the symbol, not just an "equivalent" // symbol. return x.expr == y.expr && (object)x.symbol == y.symbol; } public int GetHashCode((BoundNode? expr, Symbol symbol) obj) { RoslynDebug.Assert(obj.symbol is object); return Hash.Combine(obj.expr, obj.symbol.GetHashCode()); } } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LoweredDynamicOperationFactory.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LoweredDynamicOperationFactory { private readonly SyntheticBoundNodeFactory _factory; private readonly int _methodOrdinal; private readonly int _localFunctionOrdinal; private NamedTypeSymbol? _currentDynamicCallSiteContainer; private int _callSiteIdDispenser; internal LoweredDynamicOperationFactory(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal = -1) { Debug.Assert(factory != null); _factory = factory; _methodOrdinal = methodOrdinal; _localFunctionOrdinal = localFunctionOrdinal; } public int MethodOrdinal => _methodOrdinal; // We could read the values of the following enums from metadata instead of hardcoding them here but // - they can never change since existing programs have the values inlined and would be broken if the values changed their meaning, // - if any new flags are added to the runtime binder the compiler will change as well to produce them. // The only scenario that is not supported by hardcoding the values is when a completely new Framework is created // that redefines these constants and is not supposed to run existing programs. /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags. /// </summary> [Flags] private enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 16, ConvertArrayIndex = 32, ResultIndexed = 64, ValueFromCompoundAssignment = 128, ResultDiscarded = 256, } /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags. /// </summary> [Flags] private enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 16, IsStaticType = 32, } internal LoweredDynamicOperation MakeDynamicConversion( BoundExpression loweredOperand, bool isExplicit, bool isArrayIndex, bool isChecked, TypeSymbol resultType) { _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; Debug.Assert(!isExplicit || !isArrayIndex); if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (isExplicit) { binderFlags |= CSharpBinderFlags.ConvertExplicit; } if (isArrayIndex) { binderFlags |= CSharpBinderFlags.ConvertArrayIndex; } var loweredArguments = ImmutableArray.Create(loweredOperand); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Convert, new[] { // flags: _factory.Literal((int)binderFlags), // target type: _factory.Typeof(resultType), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicUnaryOperator( UnaryOperatorKind operatorKind, BoundExpression loweredOperand, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } var loweredArguments = ImmutableArray.Create(loweredOperand); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType()), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicBinaryOperator( BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, bool isCompoundAssignment, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredLeft.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (operatorKind.IsLogical()) { binderFlags |= CSharpBinderFlags.BinaryOperationLogical; } var loweredArguments = ImmutableArray.Create<BoundExpression>(loweredLeft, loweredRight); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType(isCompoundAssignment)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicMemberInvocation( string name, BoundExpression loweredReceiver, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool hasImplicitReceiver, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; Debug.Assert(_factory.TopLevelMethod is { }); CSharpBinderFlags binderFlags = 0; if (hasImplicitReceiver && _factory.TopLevelMethod.RequiresInstanceReceiver) { binderFlags |= CSharpBinderFlags.InvokeSimpleName; } TypeSymbol resultType; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } RefKind receiverRefKind; bool receiverIsStaticType; if (loweredReceiver.Kind == BoundKind.TypeExpression) { loweredReceiver = _factory.Typeof(((BoundTypeExpression)loweredReceiver).Type); receiverRefKind = RefKind.None; receiverIsStaticType = true; } else { receiverRefKind = GetReceiverRefKind(loweredReceiver); receiverIsStaticType = false; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(name), // type arguments: typeArgumentsWithAnnotations.IsDefaultOrEmpty ? _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)) : _factory.ArrayOrEmpty(_factory.WellKnownType(WellKnownType.System_Type), _factory.TypeOfs(typeArgumentsWithAnnotations)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicEventAccessorInvocation( string accessorName, BoundExpression loweredReceiver, BoundExpression loweredHandler) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded; var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = AssemblySymbol.DynamicType; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(accessorName), // type arguments: _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredHandler) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredHandler, resultType); } internal LoweredDynamicOperation MakeDynamicInvocation( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; TypeSymbol resultType; CSharpBinderFlags binderFlags = 0; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Invoke, new[] { // flags: _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicConstructorInvocation( SyntaxNode syntax, TypeSymbol type, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = syntax; var loweredReceiver = _factory.Typeof(type); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, new[] { // flags: _factory.Literal(0), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverIsStaticType: true) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, type); } internal LoweredDynamicOperation MakeDynamicGetMember( BoundExpression loweredReceiver, string name, bool resultIndexed) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (resultIndexed) { binderFlags |= CSharpBinderFlags.ResultIndexed; } var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicSetMember( BoundExpression loweredReceiver, string name, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredArguments = ImmutableArray<BoundExpression>.Empty; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredRight, AssemblySymbol.DynamicType); } internal LoweredDynamicOperation MakeDynamicGetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = loweredReceiver.Syntax; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, new[] { // flags (unused): _factory.Literal((int)CSharpBinderFlags.None), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicSetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredReceiverRefKind = GetReceiverRefKind(loweredReceiver); var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, new[] { // flags (unused): _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, loweredReceiverRefKind, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, loweredReceiverRefKind, loweredArguments, refKinds, loweredRight, resultType); } internal LoweredDynamicOperation MakeDynamicIsEventTest(string name, BoundExpression loweredReceiver) { _factory.Syntax = loweredReceiver.Syntax; var resultType = _factory.SpecialType(SpecialType.System_Boolean); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, new[] { // flags (unused): _factory.Literal((int)0), // member name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<RefKind>), null, resultType); } private MethodSymbol GetArgumentInfoFactory() { return _factory.WellKnownMethod(WellKnownMember.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create); } private BoundExpression? MakeBinderConstruction(WellKnownMember factoryMethod, BoundExpression[] args) { var binderFactory = _factory.WellKnownMember(factoryMethod); if (binderFactory is null) { return null; } return _factory.Call(null, (MethodSymbol)binderFactory, args.AsImmutableOrNull()); } // If we have a struct calling object, then we need to pass it by ref, provided // that it was an Lvalue. For instance, // Struct s = ...; dynamic d = ...; // s.M(d); // becomes Site(ref s, d) // however // dynamic d = ...; // GetS().M(d); // becomes Site(GetS(), d) without ref on the target obj arg internal static RefKind GetReceiverRefKind(BoundExpression loweredReceiver) { Debug.Assert(loweredReceiver.Type is { }); if (!loweredReceiver.Type.IsValueType) { return RefKind.None; } switch (loweredReceiver.Kind) { case BoundKind.Local: case BoundKind.Parameter: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: return RefKind.Ref; case BoundKind.BaseReference: // base dynamic dispatch is not supported, an error has already been reported case BoundKind.TypeExpression: throw ExceptionUtilities.UnexpectedValue(loweredReceiver.Kind); } return RefKind.None; } internal BoundExpression MakeCallSiteArgumentInfos( MethodSymbol argumentInfoFactory, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames = default(ImmutableArray<string>), ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>), BoundExpression? loweredReceiver = null, RefKind receiverRefKind = RefKind.None, bool receiverIsStaticType = false, BoundExpression? loweredRight = null) { const string? NoName = null; Debug.Assert(argumentNames.IsDefaultOrEmpty || loweredArguments.Length == argumentNames.Length); Debug.Assert(refKinds.IsDefault || loweredArguments.Length == refKinds.Length); Debug.Assert(!receiverIsStaticType || receiverRefKind == RefKind.None); var infos = new BoundExpression[(loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0)]; int j = 0; if (loweredReceiver != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredReceiver, NoName, receiverRefKind, receiverIsStaticType); } for (int i = 0; i < loweredArguments.Length; i++) { infos[j++] = GetArgumentInfo( argumentInfoFactory, loweredArguments[i], argumentNames.IsDefaultOrEmpty ? NoName : argumentNames[i], refKinds.IsDefault ? RefKind.None : refKinds[i], isStaticType: false); } if (loweredRight != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredRight, NoName, RefKind.None, isStaticType: false); } return _factory.ArrayOrEmpty(argumentInfoFactory.ContainingType, infos); } internal LoweredDynamicOperation MakeDynamicOperation( BoundExpression? binderConstruction, BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(!loweredArguments.IsDefault); // get well-known types and members we need: NamedTypeSymbol? delegateTypeOverMethodTypeParameters = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType); NamedTypeSymbol callSiteTypeGeneric = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); MethodSymbol callSiteFactoryGeneric = _factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Create); FieldSymbol callSiteTargetFieldGeneric = (FieldSymbol)_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Target); MethodSymbol delegateInvoke; if (binderConstruction == null || delegateTypeOverMethodTypeParameters is null || delegateTypeOverMethodTypeParameters.IsErrorType() || (delegateInvoke = delegateTypeOverMethodTypeParameters.DelegateInvokeMethod) is null || callSiteTypeGeneric.IsErrorType() || callSiteFactoryGeneric is null || callSiteTargetFieldGeneric is null) { // CS1969: One or more types required to compile a dynamic expression cannot be found. // Dev11 reports it with source location for each dynamic operation, which results in many error messages. // The diagnostic that names the specific missing type or member has already been reported. _factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton); return LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType); } if (_currentDynamicCallSiteContainer is null) { _currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal, _localFunctionOrdinal); } var containerDef = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition; var methodToContainerTypeParametersMap = containerDef.TypeMap; ImmutableArray<LocalSymbol> temps = MakeTempsForDiscardArguments(ref loweredArguments); var callSiteType = callSiteTypeGeneric.Construct(new[] { delegateTypeOverMethodTypeParameters }); var callSiteFactoryMethod = callSiteFactoryGeneric.AsMember(callSiteType); var callSiteTargetField = callSiteTargetFieldGeneric.AsMember(callSiteType); var callSiteField = DefineCallSiteStorageSymbol(containerDef, delegateTypeOverMethodTypeParameters, methodToContainerTypeParametersMap); var callSiteFieldAccess = _factory.Field(null, callSiteField); var callSiteArguments = GetCallSiteArguments(callSiteFieldAccess, loweredReceiver, loweredArguments, loweredRight); var nullCallSite = _factory.Null(callSiteField.Type); var siteInitialization = _factory.Conditional( _factory.ObjectEqual(callSiteFieldAccess, nullCallSite), _factory.AssignmentExpression(callSiteFieldAccess, _factory.Call(null, callSiteFactoryMethod, binderConstruction)), nullCallSite, callSiteField.Type); var siteInvocation = _factory.Call( _factory.Field(callSiteFieldAccess, callSiteTargetField), delegateInvoke, callSiteArguments); return new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType, temps); } /// <summary> /// If there are any discards in the arguments, create locals for each, updates the arguments and /// returns the symbols that were created. /// Returns default if no discards found. /// </summary> private ImmutableArray<LocalSymbol> MakeTempsForDiscardArguments(ref ImmutableArray<BoundExpression> loweredArguments) { int discardCount = loweredArguments.Count(a => a.Kind == BoundKind.DiscardExpression); if (discardCount == 0) { return ImmutableArray<LocalSymbol>.Empty; } ArrayBuilder<LocalSymbol> temporariesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(discardCount); loweredArguments = _factory.MakeTempsForDiscardArguments(loweredArguments, temporariesBuilder); return temporariesBuilder.ToImmutableAndFree(); } private static NamedTypeSymbol CreateCallSiteContainer(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal) { Debug.Assert(factory.CompilationState.ModuleBuilderOpt is { }); Debug.Assert(factory.TopLevelMethod is { }); Debug.Assert(factory.CurrentFunction is { }); // We don't reuse call-sites during EnC. Each edit creates a new container and sites. int generation = factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var containerName = GeneratedNames.MakeDynamicCallSiteContainerName(methodOrdinal, localFunctionOrdinal, generation); var synthesizedContainer = new DynamicSiteContainer(containerName, factory.TopLevelMethod, factory.CurrentFunction); factory.AddNestedType(synthesizedContainer); if (!synthesizedContainer.TypeParameters.IsEmpty) { return synthesizedContainer.Construct(synthesizedContainer.ConstructedFromTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); } return synthesizedContainer; } internal FieldSymbol DefineCallSiteStorageSymbol(NamedTypeSymbol containerDefinition, NamedTypeSymbol delegateTypeOverMethodTypeParameters, TypeMap methodToContainerTypeParametersMap) { var fieldName = GeneratedNames.MakeDynamicCallSiteFieldName(_callSiteIdDispenser++); var delegateTypeOverContainerTypeParameters = methodToContainerTypeParametersMap.SubstituteNamedType(delegateTypeOverMethodTypeParameters); var callSiteType = _factory.Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); _factory.Diagnostics.ReportUseSite(callSiteType, _factory.Syntax); callSiteType = callSiteType.Construct(new[] { delegateTypeOverContainerTypeParameters }); var field = new SynthesizedFieldSymbol(containerDefinition, callSiteType, fieldName, isPublic: true, isStatic: true); _factory.AddField(containerDefinition, field); Debug.Assert(_currentDynamicCallSiteContainer is { }); return _currentDynamicCallSiteContainer.IsGenericType ? field.AsMember(_currentDynamicCallSiteContainer) : field; } internal NamedTypeSymbol? GetDelegateType( BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(refKinds.IsDefaultOrEmpty || refKinds.Length == loweredArguments.Length); var callSiteType = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite); if (callSiteType.IsErrorType()) { return null; } var delegateSignature = MakeCallSiteDelegateSignature(callSiteType, loweredReceiver, loweredArguments, loweredRight, resultType); bool returnsVoid = resultType.IsVoidType(); bool hasByRefs = receiverRefKind != RefKind.None || !refKinds.IsDefaultOrEmpty; if (!hasByRefs) { var wkDelegateType = returnsVoid ? WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: delegateSignature.Length) : WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: delegateSignature.Length - 1); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = _factory.Compilation.GetWellKnownType(wkDelegateType); if (!delegateType.HasUseSiteError) { _factory.Diagnostics.AddDependencies(delegateType); return delegateType.Construct(delegateSignature); } } } RefKindVector byRefs; if (hasByRefs) { byRefs = RefKindVector.Create(1 + (loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0) + (returnsVoid ? 0 : 1)); int j = 1; if (loweredReceiver != null) { byRefs[j++] = getRefKind(receiverRefKind); } if (!refKinds.IsDefault) { for (int i = 0; i < refKinds.Length; i++, j++) { byRefs[j] = getRefKind(refKinds[i]); } } if (!returnsVoid) { byRefs[j++] = RefKind.None; } } else { byRefs = default(RefKindVector); } int parameterCount = delegateSignature.Length - (returnsVoid ? 0 : 1); Debug.Assert(_factory.CompilationState.ModuleBuilderOpt is { }); int generation = _factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var synthesizedType = _factory.Compilation.AnonymousTypeManager.SynthesizeDelegate(parameterCount, byRefs, returnsVoid, generation); return synthesizedType.Construct(delegateSignature); // The distinction between by-ref kinds is ignored for dynamic call-sites. static RefKind getRefKind(RefKind refKind) => refKind == RefKind.None ? RefKind.None : RefKind.Ref; } private BoundExpression GetArgumentInfo( MethodSymbol argumentInfoFactory, BoundExpression boundArgument, string? name, RefKind refKind, bool isStaticType) { CSharpArgumentInfoFlags flags = 0; if (isStaticType) { flags |= CSharpArgumentInfoFlags.IsStaticType; } if (name != null) { flags |= CSharpArgumentInfoFlags.NamedArgument; } Debug.Assert(refKind == RefKind.None || refKind == RefKind.Ref || refKind == RefKind.Out, "unexpected refKind in dynamic"); // by-ref type doesn't trigger dynamic dispatch and it can't be a null literal => set UseCompileTimeType if (refKind == RefKind.Out) { flags |= CSharpArgumentInfoFlags.IsOut | CSharpArgumentInfoFlags.UseCompileTimeType; } else if (refKind == RefKind.Ref) { flags |= CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.UseCompileTimeType; } var argType = boundArgument.Type; // Check "literal" constant. // What the runtime binder does with this LiteralConstant flag is just to create a constant, // which is a compelling enough reason to make sure that on the production end of the binder // data, we do the inverse (i.e., use the LiteralConstant flag whenever we encounter a constant // argument. // And in fact, the bug being fixed with this change is that the compiler will consider constants // for numeric and enum conversions even if they are not literals (such as, (1-1) --> enum), but // the runtime binder didn't. So we do need to set this flag whenever we see a constant. // But the complication is that null values lose their type when they get to the runtime binder, // and so we need a way to distinguish a null constant of any given type from the null literal. // The design is simple! We use UseCompileTimeType to determine whether we care about the type of // a null constant argument, so that the null literal gets "LiteralConstant" whereas every other // constant gets "LiteralConstant | UseCompileTimeType". Because obviously UseCompileTimeType is // wrong for the null literal. // We care, because we want to prevent this from working: // // const C x = null; // class C { public void M(SomeUnrelatedReferenceType x) { } } // ... // dynamic d = new C(); d.M(x); // This will pass a null constant and the type is gone! // // as well as the alternative where x is a const null of type object. if (boundArgument.ConstantValue != null) { flags |= CSharpArgumentInfoFlags.Constant; } // Check compile time type. // See also DynamicRewriter::GenerateCallingObjectFlags. if (argType is { } && !argType.IsDynamic()) { flags |= CSharpArgumentInfoFlags.UseCompileTimeType; } return _factory.Call(null, argumentInfoFactory, _factory.Literal((int)flags), _factory.Literal(name)); } private static ImmutableArray<BoundExpression> GetCallSiteArguments(BoundExpression callSiteFieldAccess, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right) { var result = new BoundExpression[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0)]; int j = 0; result[j++] = callSiteFieldAccess; if (receiver != null) { result[j++] = receiver; } arguments.CopyTo(result, j); j += arguments.Length; if (right != null) { result[j++] = right; } return result.AsImmutableOrNull(); } private TypeSymbol[] MakeCallSiteDelegateSignature(TypeSymbol callSiteType, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right, TypeSymbol resultType) { var systemObjectType = _factory.SpecialType(SpecialType.System_Object); var result = new TypeSymbol[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0) + (resultType.IsVoidType() ? 0 : 1)]; int j = 0; // CallSite: result[j++] = callSiteType; // receiver: if (receiver != null) { result[j++] = receiver.Type ?? systemObjectType; } // argument types: for (int i = 0; i < arguments.Length; i++) { result[j++] = arguments[i].Type ?? systemObjectType; } // right hand side of an assignment: if (right != null) { result[j++] = right.Type ?? systemObjectType; } // return type: if (j < result.Length) { result[j++] = resultType ?? systemObjectType; } 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LoweredDynamicOperationFactory { private readonly SyntheticBoundNodeFactory _factory; private readonly int _methodOrdinal; private readonly int _localFunctionOrdinal; private NamedTypeSymbol? _currentDynamicCallSiteContainer; private int _callSiteIdDispenser; internal LoweredDynamicOperationFactory(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal = -1) { Debug.Assert(factory != null); _factory = factory; _methodOrdinal = methodOrdinal; _localFunctionOrdinal = localFunctionOrdinal; } public int MethodOrdinal => _methodOrdinal; // We could read the values of the following enums from metadata instead of hardcoding them here but // - they can never change since existing programs have the values inlined and would be broken if the values changed their meaning, // - if any new flags are added to the runtime binder the compiler will change as well to produce them. // The only scenario that is not supported by hardcoding the values is when a completely new Framework is created // that redefines these constants and is not supposed to run existing programs. /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags. /// </summary> [Flags] private enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 16, ConvertArrayIndex = 32, ResultIndexed = 64, ValueFromCompoundAssignment = 128, ResultDiscarded = 256, } /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags. /// </summary> [Flags] private enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 16, IsStaticType = 32, } internal LoweredDynamicOperation MakeDynamicConversion( BoundExpression loweredOperand, bool isExplicit, bool isArrayIndex, bool isChecked, TypeSymbol resultType) { _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; Debug.Assert(!isExplicit || !isArrayIndex); if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (isExplicit) { binderFlags |= CSharpBinderFlags.ConvertExplicit; } if (isArrayIndex) { binderFlags |= CSharpBinderFlags.ConvertArrayIndex; } var loweredArguments = ImmutableArray.Create(loweredOperand); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Convert, new[] { // flags: _factory.Literal((int)binderFlags), // target type: _factory.Typeof(resultType), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicUnaryOperator( UnaryOperatorKind operatorKind, BoundExpression loweredOperand, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } var loweredArguments = ImmutableArray.Create(loweredOperand); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType()), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicBinaryOperator( BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, bool isCompoundAssignment, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredLeft.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (operatorKind.IsLogical()) { binderFlags |= CSharpBinderFlags.BinaryOperationLogical; } var loweredArguments = ImmutableArray.Create<BoundExpression>(loweredLeft, loweredRight); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType(isCompoundAssignment)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicMemberInvocation( string name, BoundExpression loweredReceiver, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool hasImplicitReceiver, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; Debug.Assert(_factory.TopLevelMethod is { }); CSharpBinderFlags binderFlags = 0; if (hasImplicitReceiver && _factory.TopLevelMethod.RequiresInstanceReceiver) { binderFlags |= CSharpBinderFlags.InvokeSimpleName; } TypeSymbol resultType; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } RefKind receiverRefKind; bool receiverIsStaticType; if (loweredReceiver.Kind == BoundKind.TypeExpression) { loweredReceiver = _factory.Typeof(((BoundTypeExpression)loweredReceiver).Type); receiverRefKind = RefKind.None; receiverIsStaticType = true; } else { receiverRefKind = GetReceiverRefKind(loweredReceiver); receiverIsStaticType = false; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(name), // type arguments: typeArgumentsWithAnnotations.IsDefaultOrEmpty ? _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)) : _factory.ArrayOrEmpty(_factory.WellKnownType(WellKnownType.System_Type), _factory.TypeOfs(typeArgumentsWithAnnotations)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicEventAccessorInvocation( string accessorName, BoundExpression loweredReceiver, BoundExpression loweredHandler) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded; var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = AssemblySymbol.DynamicType; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(accessorName), // type arguments: _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredHandler) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredHandler, resultType); } internal LoweredDynamicOperation MakeDynamicInvocation( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; TypeSymbol resultType; CSharpBinderFlags binderFlags = 0; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Invoke, new[] { // flags: _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicConstructorInvocation( SyntaxNode syntax, TypeSymbol type, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = syntax; var loweredReceiver = _factory.Typeof(type); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, new[] { // flags: _factory.Literal(0), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverIsStaticType: true) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, type); } internal LoweredDynamicOperation MakeDynamicGetMember( BoundExpression loweredReceiver, string name, bool resultIndexed) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (resultIndexed) { binderFlags |= CSharpBinderFlags.ResultIndexed; } var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicSetMember( BoundExpression loweredReceiver, string name, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredArguments = ImmutableArray<BoundExpression>.Empty; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredRight, AssemblySymbol.DynamicType); } internal LoweredDynamicOperation MakeDynamicGetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = loweredReceiver.Syntax; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, new[] { // flags (unused): _factory.Literal((int)CSharpBinderFlags.None), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicSetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredReceiverRefKind = GetReceiverRefKind(loweredReceiver); var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, new[] { // flags (unused): _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, loweredReceiverRefKind, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, loweredReceiverRefKind, loweredArguments, refKinds, loweredRight, resultType); } internal LoweredDynamicOperation MakeDynamicIsEventTest(string name, BoundExpression loweredReceiver) { _factory.Syntax = loweredReceiver.Syntax; var resultType = _factory.SpecialType(SpecialType.System_Boolean); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, new[] { // flags (unused): _factory.Literal((int)0), // member name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<RefKind>), null, resultType); } private MethodSymbol GetArgumentInfoFactory() { return _factory.WellKnownMethod(WellKnownMember.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create); } private BoundExpression? MakeBinderConstruction(WellKnownMember factoryMethod, BoundExpression[] args) { var binderFactory = _factory.WellKnownMember(factoryMethod); if (binderFactory is null) { return null; } return _factory.Call(null, (MethodSymbol)binderFactory, args.AsImmutableOrNull()); } // If we have a struct calling object, then we need to pass it by ref, provided // that it was an Lvalue. For instance, // Struct s = ...; dynamic d = ...; // s.M(d); // becomes Site(ref s, d) // however // dynamic d = ...; // GetS().M(d); // becomes Site(GetS(), d) without ref on the target obj arg internal static RefKind GetReceiverRefKind(BoundExpression loweredReceiver) { Debug.Assert(loweredReceiver.Type is { }); if (!loweredReceiver.Type.IsValueType) { return RefKind.None; } switch (loweredReceiver.Kind) { case BoundKind.Local: case BoundKind.Parameter: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: return RefKind.Ref; case BoundKind.BaseReference: // base dynamic dispatch is not supported, an error has already been reported case BoundKind.TypeExpression: throw ExceptionUtilities.UnexpectedValue(loweredReceiver.Kind); } return RefKind.None; } internal BoundExpression MakeCallSiteArgumentInfos( MethodSymbol argumentInfoFactory, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames = default(ImmutableArray<string>), ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>), BoundExpression? loweredReceiver = null, RefKind receiverRefKind = RefKind.None, bool receiverIsStaticType = false, BoundExpression? loweredRight = null) { const string? NoName = null; Debug.Assert(argumentNames.IsDefaultOrEmpty || loweredArguments.Length == argumentNames.Length); Debug.Assert(refKinds.IsDefault || loweredArguments.Length == refKinds.Length); Debug.Assert(!receiverIsStaticType || receiverRefKind == RefKind.None); var infos = new BoundExpression[(loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0)]; int j = 0; if (loweredReceiver != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredReceiver, NoName, receiverRefKind, receiverIsStaticType); } for (int i = 0; i < loweredArguments.Length; i++) { infos[j++] = GetArgumentInfo( argumentInfoFactory, loweredArguments[i], argumentNames.IsDefaultOrEmpty ? NoName : argumentNames[i], refKinds.IsDefault ? RefKind.None : refKinds[i], isStaticType: false); } if (loweredRight != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredRight, NoName, RefKind.None, isStaticType: false); } return _factory.ArrayOrEmpty(argumentInfoFactory.ContainingType, infos); } internal LoweredDynamicOperation MakeDynamicOperation( BoundExpression? binderConstruction, BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(!loweredArguments.IsDefault); // get well-known types and members we need: NamedTypeSymbol? delegateTypeOverMethodTypeParameters = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType); NamedTypeSymbol callSiteTypeGeneric = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); MethodSymbol callSiteFactoryGeneric = _factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Create); FieldSymbol callSiteTargetFieldGeneric = (FieldSymbol)_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Target); MethodSymbol? delegateInvoke; if (binderConstruction == null || delegateTypeOverMethodTypeParameters is null || delegateTypeOverMethodTypeParameters.IsErrorType() || (delegateInvoke = delegateTypeOverMethodTypeParameters.DelegateInvokeMethod) is null || callSiteTypeGeneric.IsErrorType() || callSiteFactoryGeneric is null || callSiteTargetFieldGeneric is null) { // CS1969: One or more types required to compile a dynamic expression cannot be found. // Dev11 reports it with source location for each dynamic operation, which results in many error messages. // The diagnostic that names the specific missing type or member has already been reported. _factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton); return LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType); } if (_currentDynamicCallSiteContainer is null) { _currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal, _localFunctionOrdinal); } var containerDef = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition; var methodToContainerTypeParametersMap = containerDef.TypeMap; ImmutableArray<LocalSymbol> temps = MakeTempsForDiscardArguments(ref loweredArguments); var callSiteType = callSiteTypeGeneric.Construct(new[] { delegateTypeOverMethodTypeParameters }); var callSiteFactoryMethod = callSiteFactoryGeneric.AsMember(callSiteType); var callSiteTargetField = callSiteTargetFieldGeneric.AsMember(callSiteType); var callSiteField = DefineCallSiteStorageSymbol(containerDef, delegateTypeOverMethodTypeParameters, methodToContainerTypeParametersMap); var callSiteFieldAccess = _factory.Field(null, callSiteField); var callSiteArguments = GetCallSiteArguments(callSiteFieldAccess, loweredReceiver, loweredArguments, loweredRight); var nullCallSite = _factory.Null(callSiteField.Type); var siteInitialization = _factory.Conditional( _factory.ObjectEqual(callSiteFieldAccess, nullCallSite), _factory.AssignmentExpression(callSiteFieldAccess, _factory.Call(null, callSiteFactoryMethod, binderConstruction)), nullCallSite, callSiteField.Type); var siteInvocation = _factory.Call( _factory.Field(callSiteFieldAccess, callSiteTargetField), delegateInvoke, callSiteArguments); return new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType, temps); } /// <summary> /// If there are any discards in the arguments, create locals for each, updates the arguments and /// returns the symbols that were created. /// Returns default if no discards found. /// </summary> private ImmutableArray<LocalSymbol> MakeTempsForDiscardArguments(ref ImmutableArray<BoundExpression> loweredArguments) { int discardCount = loweredArguments.Count(a => a.Kind == BoundKind.DiscardExpression); if (discardCount == 0) { return ImmutableArray<LocalSymbol>.Empty; } ArrayBuilder<LocalSymbol> temporariesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(discardCount); loweredArguments = _factory.MakeTempsForDiscardArguments(loweredArguments, temporariesBuilder); return temporariesBuilder.ToImmutableAndFree(); } private static NamedTypeSymbol CreateCallSiteContainer(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal) { Debug.Assert(factory.CompilationState.ModuleBuilderOpt is { }); Debug.Assert(factory.TopLevelMethod is { }); Debug.Assert(factory.CurrentFunction is { }); // We don't reuse call-sites during EnC. Each edit creates a new container and sites. int generation = factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var containerName = GeneratedNames.MakeDynamicCallSiteContainerName(methodOrdinal, localFunctionOrdinal, generation); var synthesizedContainer = new DynamicSiteContainer(containerName, factory.TopLevelMethod, factory.CurrentFunction); factory.AddNestedType(synthesizedContainer); if (!synthesizedContainer.TypeParameters.IsEmpty) { return synthesizedContainer.Construct(synthesizedContainer.ConstructedFromTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); } return synthesizedContainer; } internal FieldSymbol DefineCallSiteStorageSymbol(NamedTypeSymbol containerDefinition, NamedTypeSymbol delegateTypeOverMethodTypeParameters, TypeMap methodToContainerTypeParametersMap) { var fieldName = GeneratedNames.MakeDynamicCallSiteFieldName(_callSiteIdDispenser++); var delegateTypeOverContainerTypeParameters = methodToContainerTypeParametersMap.SubstituteNamedType(delegateTypeOverMethodTypeParameters); var callSiteType = _factory.Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); _factory.Diagnostics.ReportUseSite(callSiteType, _factory.Syntax); callSiteType = callSiteType.Construct(new[] { delegateTypeOverContainerTypeParameters }); var field = new SynthesizedFieldSymbol(containerDefinition, callSiteType, fieldName, isPublic: true, isStatic: true); _factory.AddField(containerDefinition, field); Debug.Assert(_currentDynamicCallSiteContainer is { }); return _currentDynamicCallSiteContainer.IsGenericType ? field.AsMember(_currentDynamicCallSiteContainer) : field; } internal NamedTypeSymbol? GetDelegateType( BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(refKinds.IsDefaultOrEmpty || refKinds.Length == loweredArguments.Length); var callSiteType = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite); if (callSiteType.IsErrorType()) { return null; } var delegateSignature = MakeCallSiteDelegateSignature(callSiteType, loweredReceiver, loweredArguments, loweredRight, resultType); bool returnsVoid = resultType.IsVoidType(); bool hasByRefs = receiverRefKind != RefKind.None || !refKinds.IsDefaultOrEmpty; if (!hasByRefs) { var wkDelegateType = returnsVoid ? WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: delegateSignature.Length) : WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: delegateSignature.Length - 1); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = _factory.Compilation.GetWellKnownType(wkDelegateType); if (!delegateType.HasUseSiteError) { _factory.Diagnostics.AddDependencies(delegateType); return delegateType.Construct(delegateSignature); } } } RefKindVector byRefs; if (hasByRefs) { byRefs = RefKindVector.Create(1 + (loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0) + (returnsVoid ? 0 : 1)); int j = 1; if (loweredReceiver != null) { byRefs[j++] = getRefKind(receiverRefKind); } if (!refKinds.IsDefault) { for (int i = 0; i < refKinds.Length; i++, j++) { byRefs[j] = getRefKind(refKinds[i]); } } if (!returnsVoid) { byRefs[j++] = RefKind.None; } } else { byRefs = default(RefKindVector); } int parameterCount = delegateSignature.Length - (returnsVoid ? 0 : 1); Debug.Assert(_factory.CompilationState.ModuleBuilderOpt is { }); int generation = _factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var synthesizedType = _factory.Compilation.AnonymousTypeManager.SynthesizeDelegate(parameterCount, byRefs, returnsVoid, generation); return synthesizedType.Construct(delegateSignature); // The distinction between by-ref kinds is ignored for dynamic call-sites. static RefKind getRefKind(RefKind refKind) => refKind == RefKind.None ? RefKind.None : RefKind.Ref; } private BoundExpression GetArgumentInfo( MethodSymbol argumentInfoFactory, BoundExpression boundArgument, string? name, RefKind refKind, bool isStaticType) { CSharpArgumentInfoFlags flags = 0; if (isStaticType) { flags |= CSharpArgumentInfoFlags.IsStaticType; } if (name != null) { flags |= CSharpArgumentInfoFlags.NamedArgument; } Debug.Assert(refKind == RefKind.None || refKind == RefKind.Ref || refKind == RefKind.Out, "unexpected refKind in dynamic"); // by-ref type doesn't trigger dynamic dispatch and it can't be a null literal => set UseCompileTimeType if (refKind == RefKind.Out) { flags |= CSharpArgumentInfoFlags.IsOut | CSharpArgumentInfoFlags.UseCompileTimeType; } else if (refKind == RefKind.Ref) { flags |= CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.UseCompileTimeType; } var argType = boundArgument.Type; // Check "literal" constant. // What the runtime binder does with this LiteralConstant flag is just to create a constant, // which is a compelling enough reason to make sure that on the production end of the binder // data, we do the inverse (i.e., use the LiteralConstant flag whenever we encounter a constant // argument. // And in fact, the bug being fixed with this change is that the compiler will consider constants // for numeric and enum conversions even if they are not literals (such as, (1-1) --> enum), but // the runtime binder didn't. So we do need to set this flag whenever we see a constant. // But the complication is that null values lose their type when they get to the runtime binder, // and so we need a way to distinguish a null constant of any given type from the null literal. // The design is simple! We use UseCompileTimeType to determine whether we care about the type of // a null constant argument, so that the null literal gets "LiteralConstant" whereas every other // constant gets "LiteralConstant | UseCompileTimeType". Because obviously UseCompileTimeType is // wrong for the null literal. // We care, because we want to prevent this from working: // // const C x = null; // class C { public void M(SomeUnrelatedReferenceType x) { } } // ... // dynamic d = new C(); d.M(x); // This will pass a null constant and the type is gone! // // as well as the alternative where x is a const null of type object. if (boundArgument.ConstantValue != null) { flags |= CSharpArgumentInfoFlags.Constant; } // Check compile time type. // See also DynamicRewriter::GenerateCallingObjectFlags. if (argType is { } && !argType.IsDynamic()) { flags |= CSharpArgumentInfoFlags.UseCompileTimeType; } return _factory.Call(null, argumentInfoFactory, _factory.Literal((int)flags), _factory.Literal(name)); } private static ImmutableArray<BoundExpression> GetCallSiteArguments(BoundExpression callSiteFieldAccess, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right) { var result = new BoundExpression[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0)]; int j = 0; result[j++] = callSiteFieldAccess; if (receiver != null) { result[j++] = receiver; } arguments.CopyTo(result, j); j += arguments.Length; if (right != null) { result[j++] = right; } return result.AsImmutableOrNull(); } private TypeSymbol[] MakeCallSiteDelegateSignature(TypeSymbol callSiteType, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right, TypeSymbol resultType) { var systemObjectType = _factory.SpecialType(SpecialType.System_Object); var result = new TypeSymbol[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0) + (resultType.IsVoidType() ? 0 : 1)]; int j = 0; // CallSite: result[j++] = callSiteType; // receiver: if (receiver != null) { result[j++] = receiver.Type ?? systemObjectType; } // argument types: for (int i = 0; i < arguments.Length; i++) { result[j++] = arguments[i].Type ?? systemObjectType; } // right hand side of an assignment: if (right != null) { result[j++] = right.Type ?? systemObjectType; } // return type: if (j < result.Length) { result[j++] = resultType ?? systemObjectType; } return result; } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.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.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a type other than an array, a pointer, a type parameter, and dynamic. /// </summary> internal abstract partial class NamedTypeSymbol : TypeSymbol, INamedTypeSymbolInternal { private bool _hasNoBaseCycles; // Only the compiler can create NamedTypeSymbols. internal NamedTypeSymbol(TupleExtraData tupleData = null) { _lazyTupleData = tupleData; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: How should anonymous types be represented? One possible options: have an // IsAnonymous on this type. The Name would then return a unique compiler-generated // type that matches the metadata name. /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> public abstract int Arity { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> public abstract ImmutableArray<TypeParameterSymbol> TypeParameters { get; } /// <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 abstract ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get; } internal ImmutableArray<TypeWithAnnotations> TypeArgumentsWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (var typeArgument in result) { typeArgument.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal TypeWithAnnotations TypeArgumentWithDefinitionUseSiteDiagnostics(int index, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[index]; result.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); return result; } /// <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 abstract NamedTypeSymbol ConstructedFrom { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> public virtual NamedTypeSymbol EnumUnderlyingType { get { return null; } } public override NamedTypeSymbol ContainingType { get { // we can do this since if a type does not live directly in a type // there is no containing type at all // NOTE: many derived types will override this with even better implementation // since most know their containing types/symbols directly return this.ContainingSymbol as NamedTypeSymbol; } } /// <summary> /// Returns true for a struct type containing a cycle. /// This property is intended for flow analysis only /// since it is only implemented for source types. /// </summary> internal virtual bool KnownCircularStruct { get { return false; } } internal bool KnownToHaveNoDeclaredBaseCycles { get { return _hasNoBaseCycles; } } internal void SetKnownToHaveNoDeclaredBaseCycles() { _hasNoBaseCycles = true; } /// <summary> /// Is this a NoPia local type explicitly declared in source, i.e. /// top level type with a TypeIdentifier attribute on it? /// </summary> internal virtual bool IsExplicitDefinitionOfNoPiaLocalType { get { return false; } } /// <summary> /// Returns true and a string from the first GuidAttribute on the type, /// the string might be null or an invalid guid representation. False, /// if there is no GuidAttribute with string argument. /// </summary> internal virtual bool GetGuidString(out string guidString) { return GetGuidStringDefaultImplementation(out guidString); } /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> public MethodSymbol DelegateInvokeMethod { get { if (TypeKind != TypeKind.Delegate) { return null; } var methods = GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { return null; } var method = methods[0] as MethodSymbol; //EDMAURER we used to also check 'method.IsVirtual' because section 13.6 //of the CLI spec dictates that it be virtual, but real world //working metadata has been found that contains an Invoke method that is //marked as virtual but not newslot (both of those must be combined to //meet the C# definition of virtual). Rather than weaken the check //I've removed it, as the Dev10 compiler makes no check, and we don't //stand to gain anything by having it. //return method != null && method.IsVirtual ? method : null; return method; } } /// <summary> /// Get the operators for this type by their metadata name /// </summary> internal ImmutableArray<MethodSymbol> GetOperators(string name) { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(name); if (candidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> operators = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (MethodSymbol candidate in candidates.OfType<MethodSymbol>()) { if (candidate.MethodKind == MethodKind.UserDefinedOperator || candidate.MethodKind == MethodKind.Conversion) { operators.Add(candidate); } } return operators.ToImmutableAndFree(); } /// <summary> /// Get the instance constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> InstanceConstructors { get { return GetConstructors(includeInstance: true, includeStatic: false); } } /// <summary> /// Get the static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> StaticConstructors { get { return GetConstructors(includeInstance: false, includeStatic: true); } } /// <summary> /// Get the instance and static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> Constructors { get { return GetConstructors(includeInstance: true, includeStatic: true); } } private ImmutableArray<MethodSymbol> GetConstructors(bool includeInstance, bool includeStatic) { Debug.Assert(includeInstance || includeStatic); ImmutableArray<Symbol> instanceCandidates = includeInstance ? GetMembers(WellKnownMemberNames.InstanceConstructorName) : ImmutableArray<Symbol>.Empty; ImmutableArray<Symbol> staticCandidates = includeStatic ? GetMembers(WellKnownMemberNames.StaticConstructorName) : ImmutableArray<Symbol>.Empty; if (instanceCandidates.IsEmpty && staticCandidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> constructors = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (Symbol candidate in instanceCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.Constructor); constructors.Add(method); } } foreach (Symbol candidate in staticCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.StaticConstructor); constructors.Add(method); } } return constructors.ToImmutableAndFree(); } /// <summary> /// Get the indexers for this type. /// </summary> /// <remarks> /// Won't include indexers that are explicit interface implementations. /// </remarks> public ImmutableArray<PropertySymbol> Indexers { get { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(WellKnownMemberNames.Indexer); if (candidates.IsEmpty) { return ImmutableArray<PropertySymbol>.Empty; } // The common case will be returning a list with the same elements as "candidates", // but we need a list of PropertySymbols, so we're stuck building a new list anyway. ArrayBuilder<PropertySymbol> indexers = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol candidate in candidates) { if (candidate.Kind == SymbolKind.Property) { Debug.Assert(((PropertySymbol)candidate).IsIndexer); indexers.Add((PropertySymbol)candidate); } } return indexers.ToImmutableAndFree(); } } /// <summary> /// Returns true if this type might contain extension methods. If this property /// returns false, there are no extension methods in this type. /// </summary> /// <remarks> /// This property allows the search for extension methods to be narrowed quickly. /// </remarks> public abstract bool MightContainExtensionMethods { get; } internal void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { if (this.MightContainExtensionMethods) { DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal void DoGetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var members = nameOpt == null ? this.GetMembersUnordered() : this.GetSimpleNonTypeMembers(nameOpt); foreach (var member in members) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; if (method.IsExtensionMethod && ((options & LookupOptions.AllMethodsOnArityZero) != 0 || arity == method.Arity)) { var thisParam = method.Parameters.First(); if ((thisParam.RefKind == RefKind.Ref && !thisParam.Type.IsValueType) || (thisParam.RefKind == RefKind.In && thisParam.Type.TypeKind != TypeKind.Struct)) { // For ref and ref-readonly extension methods, receivers need to be of the correct types to be considered in lookup continue; } Debug.Assert(method.MethodKind != MethodKind.ReducedExtension); methods.Add(method); } } } } // TODO: Probably should provide similar accessors for static constructor, destructor, // TODO: operators, conversions. /// <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 { get { var kind = TypeKind; return kind != TypeKind.Enum && kind != TypeKind.Struct && kind != TypeKind.Error; } } /// <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 override bool IsValueType { get { var kind = TypeKind; return kind == TypeKind.Struct || kind == TypeKind.Enum; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // CONSIDER: we could cache this, but it's only expensive for non-special struct types // that are pointed to. For now, only cache on SourceMemberContainerSymbol since it fits // nicely into the flags variable. return BaseTypeAnalysis.GetManagedKind(this, ref useSiteInfo); } /// <summary> /// Gets the associated attribute usage info for an attribute type. /// </summary> internal abstract AttributeUsageInfo GetAttributeUsageInfo(); /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> public virtual bool IsScriptClass { get { return false; } } internal bool IsSubmissionClass { get { return TypeKind == TypeKind.Submission; } } internal SynthesizedInstanceConstructor GetScriptConstructor() { Debug.Assert(IsScriptClass); return (SynthesizedInstanceConstructor)InstanceConstructors.Single(); } internal SynthesizedInteractiveInitializerMethod GetScriptInitializer() { Debug.Assert(IsScriptClass); return (SynthesizedInteractiveInitializerMethod)GetMembers(SynthesizedInteractiveInitializerMethod.InitializerName).Single(); } internal SynthesizedEntryPointSymbol GetScriptEntryPoint() { Debug.Assert(IsScriptClass); var name = (TypeKind == TypeKind.Submission) ? SynthesizedEntryPointSymbol.FactoryName : SynthesizedEntryPointSymbol.MainName; return (SynthesizedEntryPointSymbol)GetMembers(name).Single(); } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> public virtual bool IsImplicitClass { get { return false; } } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public abstract override string Name { get; } /// <summary> /// Return the name including the metadata arity suffix. /// </summary> public override string MetadataName { get { return MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity) : Name; } } /// <summary> /// Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name. /// Must return False for a type with Arity == 0. /// </summary> internal abstract bool MangleName { // Intentionally no default implementation to force consideration of appropriate implementation for each new subclass get; } /// <summary> /// Collection of names of members declared within this type. May return duplicates. /// </summary> public abstract IEnumerable<string> MemberNames { get; } /// <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 abstract override ImmutableArray<Symbol> GetMembers(); /// <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 abstract override ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// A lightweight check for whether this type has a possible clone method. This is less costly than GetMembers, /// particularly for PE symbols, and can be used as a cheap heuristic for whether to fully search through all /// members of this type for a valid clone method. /// </summary> internal abstract bool HasPossibleWellKnownCloneMethod(); internal virtual ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { return 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 abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(); /// <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 abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name); /// <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 abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity); /// <summary> /// Get all instance field and event members. /// </summary> /// <remarks> /// For source symbols may be called while calculating /// <see cref="NamespaceOrTypeSymbol.GetMembersUnordered"/>. /// </remarks> internal virtual IEnumerable<Symbol> GetInstanceFieldsAndEvents() { return GetMembersUnordered().Where(IsInstanceFieldOrEvent); } protected static Func<Symbol, bool> IsInstanceFieldOrEvent = symbol => { if (!symbol.IsStatic) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Event: return true; } } return false; }; /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public abstract override Accessibility DeclaredAccessibility { get; } /// <summary> /// Used to implement visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamedType(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamedType(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamedType(this); } /// <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. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(); /// <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. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name); /// <summary> /// Gets the kind of this symbol. /// </summary> public override SymbolKind Kind // Cannot seal this method because of the ErrorSymbol. { get { return SymbolKind.NamedType; } } internal abstract NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved); internal abstract ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved); public override int GetHashCode() { // return a distinguished value for 'object' so we can return the same value for 'dynamic'. // That's because the hash code ignores the distinction between dynamic and object. It also // ignores custom modifiers. if (this.SpecialType == SpecialType.System_Object) { return (int)SpecialType.System_Object; } // OriginalDefinition must be object-equivalent. return RuntimeHelpers.GetHashCode(OriginalDefinition); } /// <summary> /// Compares this type to another type. /// </summary> internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == this) return true; if ((object)t2 == null) return false; if ((comparison & TypeCompareKind.IgnoreDynamic) != 0) { if (t2.TypeKind == TypeKind.Dynamic) { // if ignoring dynamic, then treat dynamic the same as the type 'object' if (this.SpecialType == SpecialType.System_Object) { return true; } } } NamedTypeSymbol other = t2 as NamedTypeSymbol; if ((object)other == null) return false; // Compare OriginalDefinitions. var thisOriginalDefinition = this.OriginalDefinition; var otherOriginalDefinition = other.OriginalDefinition; bool thisIsOriginalDefinition = ((object)this == (object)thisOriginalDefinition); bool otherIsOriginalDefinition = ((object)other == (object)otherOriginalDefinition); if (thisIsOriginalDefinition && otherIsOriginalDefinition) { // If we continue, we either return false, or get into a cycle. return false; } if ((thisIsOriginalDefinition || otherIsOriginalDefinition) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } // CONSIDER: original definitions are not unique for missing metadata type // symbols. Therefore this code may not behave correctly if 'this' is List<int> // where List`1 is a missing metadata type symbol, and other is similarly List<int> // but for a reference-distinct List`1. if (!Equals(thisOriginalDefinition, otherOriginalDefinition, comparison)) { return false; } // The checks above are supposed to handle the vast majority of cases. // More complicated cases are handled in a special helper to make the common case scenario simple/fast (fewer locals and smaller stack frame) return EqualsComplicatedCases(other, comparison); } /// <summary> /// Helper for more complicated cases of Equals like when we have generic instantiations or types nested within them. /// </summary> private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind comparison) { if ((object)this.ContainingType != null && !this.ContainingType.Equals(other.ContainingType, comparison)) { return false; } var thisIsNotConstructed = ReferenceEquals(ConstructedFrom, this); var otherIsNotConstructed = ReferenceEquals(other.ConstructedFrom, other); if (thisIsNotConstructed && otherIsNotConstructed) { // Note that the arguments might appear different here due to alpha-renaming. For example, given // class A<T> { class B<U> {} } // The type A<int>.B<int> is "constructed from" A<int>.B<1>, which may be a distinct type object // with a different alpha-renaming of B's type parameter every time that type expression is bound, // but these should be considered the same type each time. return true; } if (this.IsUnboundGenericType != other.IsUnboundGenericType) { return false; } if ((thisIsNotConstructed || otherIsNotConstructed) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } var typeArguments = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var otherTypeArguments = other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; int count = typeArguments.Length; // since both are constructed from the same (original) type, they must have the same arity Debug.Assert(count == otherTypeArguments.Length); for (int i = 0; i < count; i++) { var typeArgument = typeArguments[i]; var otherTypeArgument = otherTypeArguments[i]; if (!typeArgument.Equals(otherTypeArgument, comparison)) { return false; } } if (this.IsTupleType && !tupleNamesEquals(other, comparison)) { return false; } return true; bool tupleNamesEquals(NamedTypeSymbol other, TypeCompareKind comparison) { // Make sure field names are the same. if ((comparison & TypeCompareKind.IgnoreTupleNames) == 0) { var elementNames = TupleElementNames; var otherElementNames = other.TupleElementNames; return elementNames.IsDefault ? otherElementNames.IsDefault : !otherElementNames.IsDefault && elementNames.SequenceEqual(otherElementNames); } return true; } } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { ContainingType?.AddNullableTransforms(transforms); foreach (TypeWithAnnotations arg in this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { arg.AddNullableTransforms(transforms); } } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { if (!IsGenericType) { result = this; return true; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument; if (!oldTypeArgument.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newTypeArgument)) { allTypeArguments.Free(); result = this; return false; } else if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { if (!IsGenericType) { return this; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument = transform(oldTypeArgument); if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } NamedTypeSymbol result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return result; } internal NamedTypeSymbol WithTypeArguments(ImmutableArray<TypeWithAnnotations> allTypeArguments) { var definition = this.OriginalDefinition; TypeMap substitution = new TypeMap(definition.GetAllTypeParameters(), allTypeArguments); return substitution.SubstituteNamedType(definition).WithTupleDataFrom(this); } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (!IsGenericType) { return other.IsDynamic() ? other : this; } var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); bool haveChanges = MergeEquivalentTypeArguments(this, (NamedTypeSymbol)other, variance, allTypeParameters, allTypeArguments); NamedTypeSymbol result; if (haveChanges) { TypeMap substitution = new TypeMap(allTypeParameters.ToImmutable(), allTypeArguments.ToImmutable()); result = substitution.SubstituteNamedType(this.OriginalDefinition); } else { result = this; } allTypeArguments.Free(); allTypeParameters.Free(); return IsTupleType ? MergeTupleNames((NamedTypeSymbol)other, result) : result; } /// <summary> /// Merges nullability of all type arguments from the `typeA` and `typeB`. /// The type parameters are added to `allTypeParameters`; the merged /// type arguments are added to `allTypeArguments`; and the method /// returns true if there were changes from the original `typeA`. /// </summary> private static bool MergeEquivalentTypeArguments( NamedTypeSymbol typeA, NamedTypeSymbol typeB, VarianceKind variance, ArrayBuilder<TypeParameterSymbol> allTypeParameters, ArrayBuilder<TypeWithAnnotations> allTypeArguments) { Debug.Assert(typeA.IsGenericType); Debug.Assert(typeA.Equals(typeB, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // Tuple types act as covariant when merging equivalent types. bool isTuple = typeA.IsTupleType; var definition = typeA.OriginalDefinition; bool haveChanges = false; while (true) { var typeParameters = definition.TypeParameters; if (typeParameters.Length > 0) { var typeArgumentsA = typeA.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeArgumentsB = typeB.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; allTypeParameters.AddRange(typeParameters); for (int i = 0; i < typeArgumentsA.Length; i++) { TypeWithAnnotations typeArgumentA = typeArgumentsA[i]; TypeWithAnnotations typeArgumentB = typeArgumentsB[i]; VarianceKind typeArgumentVariance = GetTypeArgumentVariance(variance, isTuple ? VarianceKind.Out : typeParameters[i].Variance); TypeWithAnnotations merged = typeArgumentA.MergeEquivalentTypes(typeArgumentB, typeArgumentVariance); allTypeArguments.Add(merged); if (!typeArgumentA.IsSameAs(merged)) { haveChanges = true; } } } definition = definition.ContainingType; if (definition is null) { break; } typeA = typeA.ContainingType; typeB = typeB.ContainingType; variance = VarianceKind.None; } return haveChanges; } private static VarianceKind GetTypeArgumentVariance(VarianceKind typeVariance, VarianceKind typeParameterVariance) { switch (typeVariance) { case VarianceKind.In: switch (typeParameterVariance) { case VarianceKind.In: return VarianceKind.Out; case VarianceKind.Out: return VarianceKind.In; default: return VarianceKind.None; } case VarianceKind.Out: return typeParameterVariance; default: return VarianceKind.None; } } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(params TypeSymbol[] typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass TypeWithAnnotations[] instead of TypeSymbol[]. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(ImmutableArray<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass ImmutableArray<TypeWithAnnotations> instead of ImmutableArray<TypeSymbol>. return ConstructWithoutModifiers(typeArguments, false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments"></param> public NamedTypeSymbol Construct(IEnumerable<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass IEnumerable<TypeWithAnnotations> instead of IEnumerable<TypeSymbol>. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns an unbound generic type of this named type. /// </summary> public NamedTypeSymbol ConstructUnboundGenericType() { return OriginalDefinition.AsUnboundGenericType(); } internal NamedTypeSymbol GetUnboundGenericTypeOrSelf() { if (!this.IsGenericType) { return this; } return this.ConstructUnboundGenericType(); } /// <summary> /// Gets a value indicating whether this type has an EmbeddedAttribute or not. /// </summary> internal abstract bool HasCodeAnalysisEmbeddedAttribute { get; } /// <summary> /// Gets a value indicating whether this type has System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute or not. /// </summary> internal abstract bool IsInterpolatedStringHandlerType { get; } internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsNullFunction = type => !type.HasType; internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsErrorType = type => type.HasType && type.Type.IsErrorType(); private NamedTypeSymbol ConstructWithoutModifiers(ImmutableArray<TypeSymbol> typeArguments, bool unbound) { ImmutableArray<TypeWithAnnotations> modifiedArguments; if (typeArguments.IsDefault) { modifiedArguments = default(ImmutableArray<TypeWithAnnotations>); } else { modifiedArguments = typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t)); } return Construct(modifiedArguments, unbound); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments) { return Construct(typeArguments, unbound: false); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { if (!ReferenceEquals(this, ConstructedFrom)) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromConstructed); } if (this.Arity == 0) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromNongeneric); } if (typeArguments.IsDefault) { throw new ArgumentNullException(nameof(typeArguments)); } if (typeArguments.Any(TypeWithAnnotationsIsNullFunction)) { throw new ArgumentException(CSharpResources.TypeArgumentCannotBeNull, nameof(typeArguments)); } if (typeArguments.Length != this.Arity) { throw new ArgumentException(CSharpResources.WrongNumberOfTypeArguments, nameof(typeArguments)); } Debug.Assert(!unbound || typeArguments.All(TypeWithAnnotationsIsErrorType)); if (ConstructedNamedTypeSymbol.TypeParametersMatchTypeArguments(this.TypeParameters, typeArguments)) { return this; } return this.ConstructCore(typeArguments, unbound); } protected virtual NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { return new ConstructedNamedTypeSymbol(this, typeArguments, unbound); } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> public bool IsGenericType { get { for (var current = this; !ReferenceEquals(current, null); current = current.ContainingType) { if (current.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length != 0) { return true; } } return false; } } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. These occur only /// within a <c>typeof</c> expression. A generic type is considered <em>unbound</em> /// if all of the type argument lists in its fully qualified name are empty. /// Note that the type arguments of an unbound generic type will be returned as error /// types because they do not really have type arguments. An unbound generic type /// yields null for its BaseType and an empty result for its Interfaces. /// </summary> public virtual bool IsUnboundGenericType { get { return false; } } // Given C<int>.D<string, double>, yields { int, string, double } internal void GetAllTypeArguments(ArrayBuilder<TypeSymbol> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } foreach (var argument in TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { builder.Add(argument.Type); } } internal ImmutableArray<TypeWithAnnotations> GetAllTypeArguments(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<TypeWithAnnotations> builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArguments(builder, ref useSiteInfo); return builder.ToImmutableAndFree(); } internal void GetAllTypeArguments(ArrayBuilder<TypeWithAnnotations> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } builder.AddRange(TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); } internal void GetAllTypeArgumentsNoUseSiteDiagnostics(ArrayBuilder<TypeWithAnnotations> builder) { ContainingType?.GetAllTypeArgumentsNoUseSiteDiagnostics(builder); builder.AddRange(TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } internal int AllTypeArgumentCount() { int count = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; var outer = ContainingType; if (!ReferenceEquals(outer, null)) { count += outer.AllTypeArgumentCount(); } return count; } internal ImmutableArray<TypeWithAnnotations> GetTypeParametersAsTypeArguments() { return TypeMap.TypeParametersAsTypeSymbolsWithAnnotations(this.TypeParameters); } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual NamedTypeSymbol OriginalDefinition { get { return this; } } protected sealed override TypeSymbol OriginalTypeSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Returns the map from type parameters to type arguments. /// If this is not a generic type instantiation, returns null. /// The map targets the original definition of the type. /// </summary> internal virtual TypeMap TypeSubstitution { get { return null; } } internal virtual NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedNestedTypeSymbol((SubstitutedNamedTypeSymbol)newOwner, this); } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { UseSiteInfo<AssemblySymbol> result = new UseSiteInfo<AssemblySymbol>(PrimaryDependency); if (this.IsDefinition) { return result; } // Check definition, type arguments if (!DeriveUseSiteInfoFromType(ref result, this.OriginalDefinition)) { DeriveUseSiteDiagnosticFromTypeArguments(ref result); } return result; } private bool DeriveUseSiteDiagnosticFromTypeArguments(ref UseSiteInfo<AssemblySymbol> result) { NamedTypeSymbol currentType = this; do { foreach (TypeWithAnnotations arg in currentType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (DeriveUseSiteInfoFromType(ref result, arg, AllowedRequiredModifierType.None)) { return true; } } currentType = currentType.ContainingType; } while (currentType?.IsDefinition == false); return false; } internal DiagnosticInfo CalculateUseSiteDiagnostic() { DiagnosticInfo result = null; // Check base type. if (MergeUseSiteDiagnostics(ref result, DeriveUseSiteDiagnosticFromBase())) { return result; } // If we reach a type (Me) that is in an assembly with unified references, // we check if that type definition depends on a type from a unified reference. if (this.ContainingModule.HasUnifiedReferences) { HashSet<TypeSymbol> unificationCheckedTypes = null; if (GetUnificationUseSiteDiagnosticRecursive(ref result, this, ref unificationCheckedTypes)) { return result; } } return result; } private DiagnosticInfo DeriveUseSiteDiagnosticFromBase() { NamedTypeSymbol @base = this.BaseTypeNoUseSiteDiagnostics; while ((object)@base != null) { if (@base.IsErrorType() && @base is NoPiaIllegalGenericInstantiationSymbol) { return @base.GetUseSiteInfo().DiagnosticInfo; } @base = @base.BaseTypeNoUseSiteDiagnostics; } return null; } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { if (!this.MarkCheckedIfNecessary(ref checkedTypes)) { return false; } Debug.Assert(owner.ContainingModule.HasUnifiedReferences); if (owner.ContainingModule.GetUnificationUseSiteDiagnostic(ref result, this)) { return true; } // We recurse into base types, interfaces and type *parameters* to check for // problems with constraints. We recurse into type *arguments* in the overload // in ConstructedNamedTypeSymbol. // // When we are binding a name with a nested type, Goo.Bar, then we ask for // use-site errors to be reported on both Goo and Goo.Bar. Therefore we should // not recurse into the containing type here; doing so will result in errors // being reported twice if Goo is bad. var @base = this.BaseTypeNoUseSiteDiagnostics; if ((object)@base != null && @base.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } return GetUnificationUseSiteDiagnosticRecursive(ref result, this.InterfacesNoUseSiteDiagnostics(), owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, this.TypeParameters, owner, ref checkedTypes); } #endregion /// <summary> /// True if the type itself is excluded from code coverage instrumentation. /// True for source types marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Returns a flag indicating whether this symbol is ComImport. /// </summary> /// <remarks> /// A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/> /// </remarks> internal abstract bool IsComImport { 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> internal abstract bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type should have its WinRT interfaces projected onto .NET types and /// have missing .NET interface members added to the type. /// </summary> internal abstract bool ShouldAddWinRTMembers { get; } /// <summary> /// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal bool IsConditional { get { if (this.GetAppliedConditionalSymbols().Any()) { return true; } // Conditional attributes are inherited by derived types. var baseType = this.BaseTypeNoUseSiteDiagnostics; return (object)baseType != null ? baseType.IsConditional : false; } } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> public abstract bool IsSerializable { get; } /// <summary> /// Returns true if locals are to be initialized /// </summary> public abstract bool AreLocalsZeroed { get; } /// <summary> /// Type layout information (ClassLayout metadata and layout kind flags). /// </summary> internal abstract TypeLayout Layout { get; } /// <summary> /// The default charset used for type marshalling. /// Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module. /// </summary> protected CharSet DefaultMarshallingCharSet { get { return this.GetEffectiveDefaultMarshallingCharSet() ?? CharSet.Ansi; } } /// <summary> /// Marshalling charset of string data fields within the type (string formatting flags in metadata). /// </summary> internal abstract CharSet MarshallingCharSet { get; } /// <summary> /// True if the type has declarative security information (HasSecurity flags). /// </summary> internal abstract bool HasDeclarativeSecurity { get; } /// <summary> /// Declaration security information associated with this type, or null if there is none. /// </summary> internal abstract IEnumerable<Cci.SecurityAttribute> GetSecurityInformation(); /// <summary> /// Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none. /// </summary> internal abstract ImmutableArray<string> GetAppliedConditionalSymbols(); /// <summary> /// If <see cref="CoClassAttribute"/> was applied to the type and the attribute argument is a valid named type argument, i.e. accessible class type, then it returns the type symbol for the argument. /// Otherwise, returns null. /// </summary> /// <remarks> /// <para> /// This property invokes force completion of attributes. If you are accessing this property /// from the binder, make sure that we are not binding within an Attribute context. /// This could lead to a possible cycle in attribute binding. /// We can avoid this cycle by first checking if we are within the context of an Attribute argument, /// i.e. if(!binder.InAttributeArgument) { ... namedType.ComImportCoClass ... } /// </para> /// <para> /// CONSIDER: We can remove the above restriction and possibility of cycle if we do an /// early binding of some well known attributes. /// </para> /// </remarks> internal virtual NamedTypeSymbol ComImportCoClass { get { return null; } } /// <summary> /// If class represents fixed buffer, this property returns the FixedElementField /// </summary> internal virtual FieldSymbol FixedElementField { get { return null; } } /// <summary> /// Requires less computation than <see cref="TypeSymbol.TypeKind"/> == <see cref="TypeKind.Interface"/>. /// </summary> /// <remarks> /// Metadata types need to compute their base types in order to know their TypeKinds, and that can lead /// to cycles if base types are already being computed. /// </remarks> /// <returns>True if this is an interface type.</returns> internal abstract bool IsInterface { get; } /// <summary> /// Verify if the given type can be used to back a tuple type /// and return cardinality of that tuple type in <paramref name="tupleCardinality"/>. /// </summary> /// <param name="tupleCardinality">If method returns true, contains cardinality of the compatible tuple type.</param> /// <returns></returns> internal bool IsTupleTypeOfCardinality(out int tupleCardinality) { // Should this be optimized for perf (caching for VT<0> to VT<7>, etc.)? if (!IsUnboundGenericType && ContainingSymbol?.Kind == SymbolKind.Namespace && ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true && Name == ValueTupleTypeName && ContainingNamespace.Name == MetadataHelpers.SystemString) { int arity = Arity; if (arity >= 0 && arity < ValueTupleRestPosition) { tupleCardinality = arity; return true; } else if (arity == ValueTupleRestPosition && !IsDefinition) { // Skip through "Rest" extensions TypeSymbol typeToCheck = this; int levelsOfNesting = 0; do { levelsOfNesting++; typeToCheck = ((NamedTypeSymbol)typeToCheck).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type; } while (Equals(typeToCheck.OriginalDefinition, this.OriginalDefinition, TypeCompareKind.ConsiderEverything) && !typeToCheck.IsDefinition); arity = (typeToCheck as NamedTypeSymbol)?.Arity ?? 0; if (arity > 0 && arity < ValueTupleRestPosition && ((NamedTypeSymbol)typeToCheck).IsTupleTypeOfCardinality(out tupleCardinality)) { Debug.Assert(tupleCardinality < ValueTupleRestPosition); tupleCardinality += (ValueTupleRestPosition - 1) * levelsOfNesting; return true; } } } tupleCardinality = 0; return false; } /// <summary> /// Returns an instance of a symbol that represents a native integer /// if this underlying symbol represents System.IntPtr or System.UIntPtr. /// For other symbols, throws <see cref="System.InvalidOperationException"/>. /// </summary> internal abstract NamedTypeSymbol AsNativeInteger(); /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> internal abstract NamedTypeSymbol NativeIntegerUnderlyingType { get; } /// <summary> /// Returns true if the type is defined in source and contains field initializers. /// This method is only valid on a definition. /// </summary> internal virtual bool HasFieldInitializers() { Debug.Assert(IsDefinition); return false; } protected override ISymbol CreateISymbol() { return new PublicModel.NonErrorNamedTypeSymbol(this, DefaultNullableAnnotation); } protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.NonErrorNamedTypeSymbol(this, nullableAnnotation); } INamedTypeSymbolInternal INamedTypeSymbolInternal.EnumUnderlyingType { get { return this.EnumUnderlyingType; } } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a type other than an array, a pointer, a type parameter, and dynamic. /// </summary> internal abstract partial class NamedTypeSymbol : TypeSymbol, INamedTypeSymbolInternal { private bool _hasNoBaseCycles; // Only the compiler can create NamedTypeSymbols. internal NamedTypeSymbol(TupleExtraData tupleData = null) { _lazyTupleData = tupleData; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: How should anonymous types be represented? One possible options: have an // IsAnonymous on this type. The Name would then return a unique compiler-generated // type that matches the metadata name. /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> public abstract int Arity { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> public abstract ImmutableArray<TypeParameterSymbol> TypeParameters { get; } /// <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 abstract ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get; } internal ImmutableArray<TypeWithAnnotations> TypeArgumentsWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (var typeArgument in result) { typeArgument.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal TypeWithAnnotations TypeArgumentWithDefinitionUseSiteDiagnostics(int index, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[index]; result.Type.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); return result; } /// <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 abstract NamedTypeSymbol ConstructedFrom { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> public virtual NamedTypeSymbol EnumUnderlyingType { get { return null; } } public override NamedTypeSymbol ContainingType { get { // we can do this since if a type does not live directly in a type // there is no containing type at all // NOTE: many derived types will override this with even better implementation // since most know their containing types/symbols directly return this.ContainingSymbol as NamedTypeSymbol; } } /// <summary> /// Returns true for a struct type containing a cycle. /// This property is intended for flow analysis only /// since it is only implemented for source types. /// </summary> internal virtual bool KnownCircularStruct { get { return false; } } internal bool KnownToHaveNoDeclaredBaseCycles { get { return _hasNoBaseCycles; } } internal void SetKnownToHaveNoDeclaredBaseCycles() { _hasNoBaseCycles = true; } /// <summary> /// Is this a NoPia local type explicitly declared in source, i.e. /// top level type with a TypeIdentifier attribute on it? /// </summary> internal virtual bool IsExplicitDefinitionOfNoPiaLocalType { get { return false; } } /// <summary> /// Returns true and a string from the first GuidAttribute on the type, /// the string might be null or an invalid guid representation. False, /// if there is no GuidAttribute with string argument. /// </summary> internal virtual bool GetGuidString(out string guidString) { return GetGuidStringDefaultImplementation(out guidString); } #nullable enable /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> public MethodSymbol? DelegateInvokeMethod { get { if (TypeKind != TypeKind.Delegate) { return null; } var methods = GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { return null; } var method = methods[0] as MethodSymbol; //EDMAURER we used to also check 'method.IsVirtual' because section 13.6 //of the CLI spec dictates that it be virtual, but real world //working metadata has been found that contains an Invoke method that is //marked as virtual but not newslot (both of those must be combined to //meet the C# definition of virtual). Rather than weaken the check //I've removed it, as the Dev10 compiler makes no check, and we don't //stand to gain anything by having it. //return method != null && method.IsVirtual ? method : null; return method; } } #nullable disable /// <summary> /// Get the operators for this type by their metadata name /// </summary> internal ImmutableArray<MethodSymbol> GetOperators(string name) { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(name); if (candidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> operators = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (MethodSymbol candidate in candidates.OfType<MethodSymbol>()) { if (candidate.MethodKind == MethodKind.UserDefinedOperator || candidate.MethodKind == MethodKind.Conversion) { operators.Add(candidate); } } return operators.ToImmutableAndFree(); } /// <summary> /// Get the instance constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> InstanceConstructors { get { return GetConstructors(includeInstance: true, includeStatic: false); } } /// <summary> /// Get the static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> StaticConstructors { get { return GetConstructors(includeInstance: false, includeStatic: true); } } /// <summary> /// Get the instance and static constructors for this type. /// </summary> public ImmutableArray<MethodSymbol> Constructors { get { return GetConstructors(includeInstance: true, includeStatic: true); } } private ImmutableArray<MethodSymbol> GetConstructors(bool includeInstance, bool includeStatic) { Debug.Assert(includeInstance || includeStatic); ImmutableArray<Symbol> instanceCandidates = includeInstance ? GetMembers(WellKnownMemberNames.InstanceConstructorName) : ImmutableArray<Symbol>.Empty; ImmutableArray<Symbol> staticCandidates = includeStatic ? GetMembers(WellKnownMemberNames.StaticConstructorName) : ImmutableArray<Symbol>.Empty; if (instanceCandidates.IsEmpty && staticCandidates.IsEmpty) { return ImmutableArray<MethodSymbol>.Empty; } ArrayBuilder<MethodSymbol> constructors = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (Symbol candidate in instanceCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.Constructor); constructors.Add(method); } } foreach (Symbol candidate in staticCandidates) { if (candidate is MethodSymbol method) { Debug.Assert(method.MethodKind == MethodKind.StaticConstructor); constructors.Add(method); } } return constructors.ToImmutableAndFree(); } /// <summary> /// Get the indexers for this type. /// </summary> /// <remarks> /// Won't include indexers that are explicit interface implementations. /// </remarks> public ImmutableArray<PropertySymbol> Indexers { get { ImmutableArray<Symbol> candidates = GetSimpleNonTypeMembers(WellKnownMemberNames.Indexer); if (candidates.IsEmpty) { return ImmutableArray<PropertySymbol>.Empty; } // The common case will be returning a list with the same elements as "candidates", // but we need a list of PropertySymbols, so we're stuck building a new list anyway. ArrayBuilder<PropertySymbol> indexers = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol candidate in candidates) { if (candidate.Kind == SymbolKind.Property) { Debug.Assert(((PropertySymbol)candidate).IsIndexer); indexers.Add((PropertySymbol)candidate); } } return indexers.ToImmutableAndFree(); } } /// <summary> /// Returns true if this type might contain extension methods. If this property /// returns false, there are no extension methods in this type. /// </summary> /// <remarks> /// This property allows the search for extension methods to be narrowed quickly. /// </remarks> public abstract bool MightContainExtensionMethods { get; } internal void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { if (this.MightContainExtensionMethods) { DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal void DoGetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var members = nameOpt == null ? this.GetMembersUnordered() : this.GetSimpleNonTypeMembers(nameOpt); foreach (var member in members) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; if (method.IsExtensionMethod && ((options & LookupOptions.AllMethodsOnArityZero) != 0 || arity == method.Arity)) { var thisParam = method.Parameters.First(); if ((thisParam.RefKind == RefKind.Ref && !thisParam.Type.IsValueType) || (thisParam.RefKind == RefKind.In && thisParam.Type.TypeKind != TypeKind.Struct)) { // For ref and ref-readonly extension methods, receivers need to be of the correct types to be considered in lookup continue; } Debug.Assert(method.MethodKind != MethodKind.ReducedExtension); methods.Add(method); } } } } // TODO: Probably should provide similar accessors for static constructor, destructor, // TODO: operators, conversions. /// <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 { get { var kind = TypeKind; return kind != TypeKind.Enum && kind != TypeKind.Struct && kind != TypeKind.Error; } } /// <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 override bool IsValueType { get { var kind = TypeKind; return kind == TypeKind.Struct || kind == TypeKind.Enum; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // CONSIDER: we could cache this, but it's only expensive for non-special struct types // that are pointed to. For now, only cache on SourceMemberContainerSymbol since it fits // nicely into the flags variable. return BaseTypeAnalysis.GetManagedKind(this, ref useSiteInfo); } /// <summary> /// Gets the associated attribute usage info for an attribute type. /// </summary> internal abstract AttributeUsageInfo GetAttributeUsageInfo(); /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> public virtual bool IsScriptClass { get { return false; } } internal bool IsSubmissionClass { get { return TypeKind == TypeKind.Submission; } } internal SynthesizedInstanceConstructor GetScriptConstructor() { Debug.Assert(IsScriptClass); return (SynthesizedInstanceConstructor)InstanceConstructors.Single(); } internal SynthesizedInteractiveInitializerMethod GetScriptInitializer() { Debug.Assert(IsScriptClass); return (SynthesizedInteractiveInitializerMethod)GetMembers(SynthesizedInteractiveInitializerMethod.InitializerName).Single(); } internal SynthesizedEntryPointSymbol GetScriptEntryPoint() { Debug.Assert(IsScriptClass); var name = (TypeKind == TypeKind.Submission) ? SynthesizedEntryPointSymbol.FactoryName : SynthesizedEntryPointSymbol.MainName; return (SynthesizedEntryPointSymbol)GetMembers(name).Single(); } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> public virtual bool IsImplicitClass { get { return false; } } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public abstract override string Name { get; } /// <summary> /// Return the name including the metadata arity suffix. /// </summary> public override string MetadataName { get { return MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity) : Name; } } /// <summary> /// Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name. /// Must return False for a type with Arity == 0. /// </summary> internal abstract bool MangleName { // Intentionally no default implementation to force consideration of appropriate implementation for each new subclass get; } /// <summary> /// Collection of names of members declared within this type. May return duplicates. /// </summary> public abstract IEnumerable<string> MemberNames { get; } /// <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 abstract override ImmutableArray<Symbol> GetMembers(); /// <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 abstract override ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// A lightweight check for whether this type has a possible clone method. This is less costly than GetMembers, /// particularly for PE symbols, and can be used as a cheap heuristic for whether to fully search through all /// members of this type for a valid clone method. /// </summary> internal abstract bool HasPossibleWellKnownCloneMethod(); internal virtual ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { return 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 abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(); /// <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 abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name); /// <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 abstract override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity); /// <summary> /// Get all instance field and event members. /// </summary> /// <remarks> /// For source symbols may be called while calculating /// <see cref="NamespaceOrTypeSymbol.GetMembersUnordered"/>. /// </remarks> internal virtual IEnumerable<Symbol> GetInstanceFieldsAndEvents() { return GetMembersUnordered().Where(IsInstanceFieldOrEvent); } protected static Func<Symbol, bool> IsInstanceFieldOrEvent = symbol => { if (!symbol.IsStatic) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Event: return true; } } return false; }; /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public abstract override Accessibility DeclaredAccessibility { get; } /// <summary> /// Used to implement visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamedType(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamedType(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamedType(this); } /// <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. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(); /// <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. /// </summary> /// <remarks> /// Never returns null (empty instead). /// Expected implementations: for source, return type and field members; for metadata, return all members. /// </remarks> internal abstract ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name); /// <summary> /// Gets the kind of this symbol. /// </summary> public override SymbolKind Kind // Cannot seal this method because of the ErrorSymbol. { get { return SymbolKind.NamedType; } } internal abstract NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved); internal abstract ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved); public override int GetHashCode() { // return a distinguished value for 'object' so we can return the same value for 'dynamic'. // That's because the hash code ignores the distinction between dynamic and object. It also // ignores custom modifiers. if (this.SpecialType == SpecialType.System_Object) { return (int)SpecialType.System_Object; } // OriginalDefinition must be object-equivalent. return RuntimeHelpers.GetHashCode(OriginalDefinition); } /// <summary> /// Compares this type to another type. /// </summary> internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == this) return true; if ((object)t2 == null) return false; if ((comparison & TypeCompareKind.IgnoreDynamic) != 0) { if (t2.TypeKind == TypeKind.Dynamic) { // if ignoring dynamic, then treat dynamic the same as the type 'object' if (this.SpecialType == SpecialType.System_Object) { return true; } } } NamedTypeSymbol other = t2 as NamedTypeSymbol; if ((object)other == null) return false; // Compare OriginalDefinitions. var thisOriginalDefinition = this.OriginalDefinition; var otherOriginalDefinition = other.OriginalDefinition; bool thisIsOriginalDefinition = ((object)this == (object)thisOriginalDefinition); bool otherIsOriginalDefinition = ((object)other == (object)otherOriginalDefinition); if (thisIsOriginalDefinition && otherIsOriginalDefinition) { // If we continue, we either return false, or get into a cycle. return false; } if ((thisIsOriginalDefinition || otherIsOriginalDefinition) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } // CONSIDER: original definitions are not unique for missing metadata type // symbols. Therefore this code may not behave correctly if 'this' is List<int> // where List`1 is a missing metadata type symbol, and other is similarly List<int> // but for a reference-distinct List`1. if (!Equals(thisOriginalDefinition, otherOriginalDefinition, comparison)) { return false; } // The checks above are supposed to handle the vast majority of cases. // More complicated cases are handled in a special helper to make the common case scenario simple/fast (fewer locals and smaller stack frame) return EqualsComplicatedCases(other, comparison); } /// <summary> /// Helper for more complicated cases of Equals like when we have generic instantiations or types nested within them. /// </summary> private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind comparison) { if ((object)this.ContainingType != null && !this.ContainingType.Equals(other.ContainingType, comparison)) { return false; } var thisIsNotConstructed = ReferenceEquals(ConstructedFrom, this); var otherIsNotConstructed = ReferenceEquals(other.ConstructedFrom, other); if (thisIsNotConstructed && otherIsNotConstructed) { // Note that the arguments might appear different here due to alpha-renaming. For example, given // class A<T> { class B<U> {} } // The type A<int>.B<int> is "constructed from" A<int>.B<1>, which may be a distinct type object // with a different alpha-renaming of B's type parameter every time that type expression is bound, // but these should be considered the same type each time. return true; } if (this.IsUnboundGenericType != other.IsUnboundGenericType) { return false; } if ((thisIsNotConstructed || otherIsNotConstructed) && (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions | TypeCompareKind.IgnoreTupleNames)) == 0) { return false; } var typeArguments = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var otherTypeArguments = other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; int count = typeArguments.Length; // since both are constructed from the same (original) type, they must have the same arity Debug.Assert(count == otherTypeArguments.Length); for (int i = 0; i < count; i++) { var typeArgument = typeArguments[i]; var otherTypeArgument = otherTypeArguments[i]; if (!typeArgument.Equals(otherTypeArgument, comparison)) { return false; } } if (this.IsTupleType && !tupleNamesEquals(other, comparison)) { return false; } return true; bool tupleNamesEquals(NamedTypeSymbol other, TypeCompareKind comparison) { // Make sure field names are the same. if ((comparison & TypeCompareKind.IgnoreTupleNames) == 0) { var elementNames = TupleElementNames; var otherElementNames = other.TupleElementNames; return elementNames.IsDefault ? otherElementNames.IsDefault : !otherElementNames.IsDefault && elementNames.SequenceEqual(otherElementNames); } return true; } } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { ContainingType?.AddNullableTransforms(transforms); foreach (TypeWithAnnotations arg in this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { arg.AddNullableTransforms(transforms); } } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { if (!IsGenericType) { result = this; return true; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument; if (!oldTypeArgument.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position, out newTypeArgument)) { allTypeArguments.Free(); result = this; return false; } else if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { if (!IsGenericType) { return this; } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument = transform(oldTypeArgument); if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } NamedTypeSymbol result = haveChanges ? this.WithTypeArguments(allTypeArguments.ToImmutable()) : this; allTypeArguments.Free(); return result; } internal NamedTypeSymbol WithTypeArguments(ImmutableArray<TypeWithAnnotations> allTypeArguments) { var definition = this.OriginalDefinition; TypeMap substitution = new TypeMap(definition.GetAllTypeParameters(), allTypeArguments); return substitution.SubstituteNamedType(definition).WithTupleDataFrom(this); } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (!IsGenericType) { return other.IsDynamic() ? other : this; } var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); bool haveChanges = MergeEquivalentTypeArguments(this, (NamedTypeSymbol)other, variance, allTypeParameters, allTypeArguments); NamedTypeSymbol result; if (haveChanges) { TypeMap substitution = new TypeMap(allTypeParameters.ToImmutable(), allTypeArguments.ToImmutable()); result = substitution.SubstituteNamedType(this.OriginalDefinition); } else { result = this; } allTypeArguments.Free(); allTypeParameters.Free(); return IsTupleType ? MergeTupleNames((NamedTypeSymbol)other, result) : result; } /// <summary> /// Merges nullability of all type arguments from the `typeA` and `typeB`. /// The type parameters are added to `allTypeParameters`; the merged /// type arguments are added to `allTypeArguments`; and the method /// returns true if there were changes from the original `typeA`. /// </summary> private static bool MergeEquivalentTypeArguments( NamedTypeSymbol typeA, NamedTypeSymbol typeB, VarianceKind variance, ArrayBuilder<TypeParameterSymbol> allTypeParameters, ArrayBuilder<TypeWithAnnotations> allTypeArguments) { Debug.Assert(typeA.IsGenericType); Debug.Assert(typeA.Equals(typeB, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // Tuple types act as covariant when merging equivalent types. bool isTuple = typeA.IsTupleType; var definition = typeA.OriginalDefinition; bool haveChanges = false; while (true) { var typeParameters = definition.TypeParameters; if (typeParameters.Length > 0) { var typeArgumentsA = typeA.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeArgumentsB = typeB.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; allTypeParameters.AddRange(typeParameters); for (int i = 0; i < typeArgumentsA.Length; i++) { TypeWithAnnotations typeArgumentA = typeArgumentsA[i]; TypeWithAnnotations typeArgumentB = typeArgumentsB[i]; VarianceKind typeArgumentVariance = GetTypeArgumentVariance(variance, isTuple ? VarianceKind.Out : typeParameters[i].Variance); TypeWithAnnotations merged = typeArgumentA.MergeEquivalentTypes(typeArgumentB, typeArgumentVariance); allTypeArguments.Add(merged); if (!typeArgumentA.IsSameAs(merged)) { haveChanges = true; } } } definition = definition.ContainingType; if (definition is null) { break; } typeA = typeA.ContainingType; typeB = typeB.ContainingType; variance = VarianceKind.None; } return haveChanges; } private static VarianceKind GetTypeArgumentVariance(VarianceKind typeVariance, VarianceKind typeParameterVariance) { switch (typeVariance) { case VarianceKind.In: switch (typeParameterVariance) { case VarianceKind.In: return VarianceKind.Out; case VarianceKind.Out: return VarianceKind.In; default: return VarianceKind.None; } case VarianceKind.Out: return typeParameterVariance; default: return VarianceKind.None; } } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(params TypeSymbol[] typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass TypeWithAnnotations[] instead of TypeSymbol[]. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> public NamedTypeSymbol Construct(ImmutableArray<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass ImmutableArray<TypeWithAnnotations> instead of ImmutableArray<TypeSymbol>. return ConstructWithoutModifiers(typeArguments, false); } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments"></param> public NamedTypeSymbol Construct(IEnumerable<TypeSymbol> typeArguments) { // https://github.com/dotnet/roslyn/issues/30064: We should fix the callers to pass IEnumerable<TypeWithAnnotations> instead of IEnumerable<TypeSymbol>. return ConstructWithoutModifiers(typeArguments.AsImmutableOrNull(), false); } /// <summary> /// Returns an unbound generic type of this named type. /// </summary> public NamedTypeSymbol ConstructUnboundGenericType() { return OriginalDefinition.AsUnboundGenericType(); } internal NamedTypeSymbol GetUnboundGenericTypeOrSelf() { if (!this.IsGenericType) { return this; } return this.ConstructUnboundGenericType(); } /// <summary> /// Gets a value indicating whether this type has an EmbeddedAttribute or not. /// </summary> internal abstract bool HasCodeAnalysisEmbeddedAttribute { get; } /// <summary> /// Gets a value indicating whether this type has System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute or not. /// </summary> internal abstract bool IsInterpolatedStringHandlerType { get; } internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsNullFunction = type => !type.HasType; internal static readonly Func<TypeWithAnnotations, bool> TypeWithAnnotationsIsErrorType = type => type.HasType && type.Type.IsErrorType(); private NamedTypeSymbol ConstructWithoutModifiers(ImmutableArray<TypeSymbol> typeArguments, bool unbound) { ImmutableArray<TypeWithAnnotations> modifiedArguments; if (typeArguments.IsDefault) { modifiedArguments = default(ImmutableArray<TypeWithAnnotations>); } else { modifiedArguments = typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t)); } return Construct(modifiedArguments, unbound); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments) { return Construct(typeArguments, unbound: false); } internal NamedTypeSymbol Construct(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { if (!ReferenceEquals(this, ConstructedFrom)) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromConstructed); } if (this.Arity == 0) { throw new InvalidOperationException(CSharpResources.CannotCreateConstructedFromNongeneric); } if (typeArguments.IsDefault) { throw new ArgumentNullException(nameof(typeArguments)); } if (typeArguments.Any(TypeWithAnnotationsIsNullFunction)) { throw new ArgumentException(CSharpResources.TypeArgumentCannotBeNull, nameof(typeArguments)); } if (typeArguments.Length != this.Arity) { throw new ArgumentException(CSharpResources.WrongNumberOfTypeArguments, nameof(typeArguments)); } Debug.Assert(!unbound || typeArguments.All(TypeWithAnnotationsIsErrorType)); if (ConstructedNamedTypeSymbol.TypeParametersMatchTypeArguments(this.TypeParameters, typeArguments)) { return this; } return this.ConstructCore(typeArguments, unbound); } protected virtual NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound) { return new ConstructedNamedTypeSymbol(this, typeArguments, unbound); } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> public bool IsGenericType { get { for (var current = this; !ReferenceEquals(current, null); current = current.ContainingType) { if (current.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length != 0) { return true; } } return false; } } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. These occur only /// within a <c>typeof</c> expression. A generic type is considered <em>unbound</em> /// if all of the type argument lists in its fully qualified name are empty. /// Note that the type arguments of an unbound generic type will be returned as error /// types because they do not really have type arguments. An unbound generic type /// yields null for its BaseType and an empty result for its Interfaces. /// </summary> public virtual bool IsUnboundGenericType { get { return false; } } // Given C<int>.D<string, double>, yields { int, string, double } internal void GetAllTypeArguments(ArrayBuilder<TypeSymbol> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } foreach (var argument in TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { builder.Add(argument.Type); } } internal ImmutableArray<TypeWithAnnotations> GetAllTypeArguments(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<TypeWithAnnotations> builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllTypeArguments(builder, ref useSiteInfo); return builder.ToImmutableAndFree(); } internal void GetAllTypeArguments(ArrayBuilder<TypeWithAnnotations> builder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var outer = ContainingType; if (!ReferenceEquals(outer, null)) { outer.GetAllTypeArguments(builder, ref useSiteInfo); } builder.AddRange(TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); } internal void GetAllTypeArgumentsNoUseSiteDiagnostics(ArrayBuilder<TypeWithAnnotations> builder) { ContainingType?.GetAllTypeArgumentsNoUseSiteDiagnostics(builder); builder.AddRange(TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } internal int AllTypeArgumentCount() { int count = TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Length; var outer = ContainingType; if (!ReferenceEquals(outer, null)) { count += outer.AllTypeArgumentCount(); } return count; } internal ImmutableArray<TypeWithAnnotations> GetTypeParametersAsTypeArguments() { return TypeMap.TypeParametersAsTypeSymbolsWithAnnotations(this.TypeParameters); } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual NamedTypeSymbol OriginalDefinition { get { return this; } } protected sealed override TypeSymbol OriginalTypeSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Returns the map from type parameters to type arguments. /// If this is not a generic type instantiation, returns null. /// The map targets the original definition of the type. /// </summary> internal virtual TypeMap TypeSubstitution { get { return null; } } internal virtual NamedTypeSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedNestedTypeSymbol((SubstitutedNamedTypeSymbol)newOwner, this); } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { UseSiteInfo<AssemblySymbol> result = new UseSiteInfo<AssemblySymbol>(PrimaryDependency); if (this.IsDefinition) { return result; } // Check definition, type arguments if (!DeriveUseSiteInfoFromType(ref result, this.OriginalDefinition)) { DeriveUseSiteDiagnosticFromTypeArguments(ref result); } return result; } private bool DeriveUseSiteDiagnosticFromTypeArguments(ref UseSiteInfo<AssemblySymbol> result) { NamedTypeSymbol currentType = this; do { foreach (TypeWithAnnotations arg in currentType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (DeriveUseSiteInfoFromType(ref result, arg, AllowedRequiredModifierType.None)) { return true; } } currentType = currentType.ContainingType; } while (currentType?.IsDefinition == false); return false; } internal DiagnosticInfo CalculateUseSiteDiagnostic() { DiagnosticInfo result = null; // Check base type. if (MergeUseSiteDiagnostics(ref result, DeriveUseSiteDiagnosticFromBase())) { return result; } // If we reach a type (Me) that is in an assembly with unified references, // we check if that type definition depends on a type from a unified reference. if (this.ContainingModule.HasUnifiedReferences) { HashSet<TypeSymbol> unificationCheckedTypes = null; if (GetUnificationUseSiteDiagnosticRecursive(ref result, this, ref unificationCheckedTypes)) { return result; } } return result; } private DiagnosticInfo DeriveUseSiteDiagnosticFromBase() { NamedTypeSymbol @base = this.BaseTypeNoUseSiteDiagnostics; while ((object)@base != null) { if (@base.IsErrorType() && @base is NoPiaIllegalGenericInstantiationSymbol) { return @base.GetUseSiteInfo().DiagnosticInfo; } @base = @base.BaseTypeNoUseSiteDiagnostics; } return null; } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { if (!this.MarkCheckedIfNecessary(ref checkedTypes)) { return false; } Debug.Assert(owner.ContainingModule.HasUnifiedReferences); if (owner.ContainingModule.GetUnificationUseSiteDiagnostic(ref result, this)) { return true; } // We recurse into base types, interfaces and type *parameters* to check for // problems with constraints. We recurse into type *arguments* in the overload // in ConstructedNamedTypeSymbol. // // When we are binding a name with a nested type, Goo.Bar, then we ask for // use-site errors to be reported on both Goo and Goo.Bar. Therefore we should // not recurse into the containing type here; doing so will result in errors // being reported twice if Goo is bad. var @base = this.BaseTypeNoUseSiteDiagnostics; if ((object)@base != null && @base.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } return GetUnificationUseSiteDiagnosticRecursive(ref result, this.InterfacesNoUseSiteDiagnostics(), owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, this.TypeParameters, owner, ref checkedTypes); } #endregion /// <summary> /// True if the type itself is excluded from code coverage instrumentation. /// True for source types marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Returns a flag indicating whether this symbol is ComImport. /// </summary> /// <remarks> /// A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/> /// </remarks> internal abstract bool IsComImport { 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> internal abstract bool IsWindowsRuntimeImport { get; } /// <summary> /// True if the type should have its WinRT interfaces projected onto .NET types and /// have missing .NET interface members added to the type. /// </summary> internal abstract bool ShouldAddWinRTMembers { get; } /// <summary> /// Returns a flag indicating whether this symbol has at least one applied/inherited conditional attribute. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal bool IsConditional { get { if (this.GetAppliedConditionalSymbols().Any()) { return true; } // Conditional attributes are inherited by derived types. var baseType = this.BaseTypeNoUseSiteDiagnostics; return (object)baseType != null ? baseType.IsConditional : false; } } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> public abstract bool IsSerializable { get; } /// <summary> /// Returns true if locals are to be initialized /// </summary> public abstract bool AreLocalsZeroed { get; } /// <summary> /// Type layout information (ClassLayout metadata and layout kind flags). /// </summary> internal abstract TypeLayout Layout { get; } /// <summary> /// The default charset used for type marshalling. /// Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module. /// </summary> protected CharSet DefaultMarshallingCharSet { get { return this.GetEffectiveDefaultMarshallingCharSet() ?? CharSet.Ansi; } } /// <summary> /// Marshalling charset of string data fields within the type (string formatting flags in metadata). /// </summary> internal abstract CharSet MarshallingCharSet { get; } /// <summary> /// True if the type has declarative security information (HasSecurity flags). /// </summary> internal abstract bool HasDeclarativeSecurity { get; } /// <summary> /// Declaration security information associated with this type, or null if there is none. /// </summary> internal abstract IEnumerable<Cci.SecurityAttribute> GetSecurityInformation(); /// <summary> /// Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none. /// </summary> internal abstract ImmutableArray<string> GetAppliedConditionalSymbols(); /// <summary> /// If <see cref="CoClassAttribute"/> was applied to the type and the attribute argument is a valid named type argument, i.e. accessible class type, then it returns the type symbol for the argument. /// Otherwise, returns null. /// </summary> /// <remarks> /// <para> /// This property invokes force completion of attributes. If you are accessing this property /// from the binder, make sure that we are not binding within an Attribute context. /// This could lead to a possible cycle in attribute binding. /// We can avoid this cycle by first checking if we are within the context of an Attribute argument, /// i.e. if(!binder.InAttributeArgument) { ... namedType.ComImportCoClass ... } /// </para> /// <para> /// CONSIDER: We can remove the above restriction and possibility of cycle if we do an /// early binding of some well known attributes. /// </para> /// </remarks> internal virtual NamedTypeSymbol ComImportCoClass { get { return null; } } /// <summary> /// If class represents fixed buffer, this property returns the FixedElementField /// </summary> internal virtual FieldSymbol FixedElementField { get { return null; } } /// <summary> /// Requires less computation than <see cref="TypeSymbol.TypeKind"/> == <see cref="TypeKind.Interface"/>. /// </summary> /// <remarks> /// Metadata types need to compute their base types in order to know their TypeKinds, and that can lead /// to cycles if base types are already being computed. /// </remarks> /// <returns>True if this is an interface type.</returns> internal abstract bool IsInterface { get; } /// <summary> /// Verify if the given type can be used to back a tuple type /// and return cardinality of that tuple type in <paramref name="tupleCardinality"/>. /// </summary> /// <param name="tupleCardinality">If method returns true, contains cardinality of the compatible tuple type.</param> /// <returns></returns> internal bool IsTupleTypeOfCardinality(out int tupleCardinality) { // Should this be optimized for perf (caching for VT<0> to VT<7>, etc.)? if (!IsUnboundGenericType && ContainingSymbol?.Kind == SymbolKind.Namespace && ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true && Name == ValueTupleTypeName && ContainingNamespace.Name == MetadataHelpers.SystemString) { int arity = Arity; if (arity >= 0 && arity < ValueTupleRestPosition) { tupleCardinality = arity; return true; } else if (arity == ValueTupleRestPosition && !IsDefinition) { // Skip through "Rest" extensions TypeSymbol typeToCheck = this; int levelsOfNesting = 0; do { levelsOfNesting++; typeToCheck = ((NamedTypeSymbol)typeToCheck).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ValueTupleRestPosition - 1].Type; } while (Equals(typeToCheck.OriginalDefinition, this.OriginalDefinition, TypeCompareKind.ConsiderEverything) && !typeToCheck.IsDefinition); arity = (typeToCheck as NamedTypeSymbol)?.Arity ?? 0; if (arity > 0 && arity < ValueTupleRestPosition && ((NamedTypeSymbol)typeToCheck).IsTupleTypeOfCardinality(out tupleCardinality)) { Debug.Assert(tupleCardinality < ValueTupleRestPosition); tupleCardinality += (ValueTupleRestPosition - 1) * levelsOfNesting; return true; } } } tupleCardinality = 0; return false; } /// <summary> /// Returns an instance of a symbol that represents a native integer /// if this underlying symbol represents System.IntPtr or System.UIntPtr. /// For other symbols, throws <see cref="System.InvalidOperationException"/>. /// </summary> internal abstract NamedTypeSymbol AsNativeInteger(); /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> internal abstract NamedTypeSymbol NativeIntegerUnderlyingType { get; } /// <summary> /// Returns true if the type is defined in source and contains field initializers. /// This method is only valid on a definition. /// </summary> internal virtual bool HasFieldInitializers() { Debug.Assert(IsDefinition); return false; } protected override ISymbol CreateISymbol() { return new PublicModel.NonErrorNamedTypeSymbol(this, DefaultNullableAnnotation); } protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.NonErrorNamedTypeSymbol(this, nullableAnnotation); } INamedTypeSymbolInternal INamedTypeSymbolInternal.EnumUnderlyingType { get { return this.EnumUnderlyingType; } } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.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.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class TypeSymbolExtensions { public static bool ImplementsInterface(this TypeSymbol subType, TypeSymbol superInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { foreach (NamedTypeSymbol @interface in subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (@interface.IsInterface && TypeSymbol.Equals(@interface, superInterface, TypeCompareKind.ConsiderEverything2)) { return true; } } return false; } public static bool CanBeAssignedNull(this TypeSymbol type) { return type.IsReferenceType || type.IsPointerOrFunctionPointer() || type.IsNullableType(); } public static bool CanContainNull(this TypeSymbol type) { // unbound type parameters might contain null, even though they cannot be *assigned* null. return !type.IsValueType || type.IsNullableTypeOrTypeParameter(); } public static bool CanBeConst(this TypeSymbol typeSymbol) { RoslynDebug.Assert((object)typeSymbol != null); return typeSymbol.IsReferenceType || typeSymbol.IsEnumType() || typeSymbol.SpecialType.CanBeConst() || typeSymbol.IsNativeIntegerType; } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => true /// T where T : IComparable? => true /// T where T : notnull => true /// </summary> /// <remarks> /// In C#9, annotations are allowed regardless of constraints. /// </remarks> public static bool IsTypeParameterDisallowingAnnotationInCSharp8(this TypeSymbol type) { if (type.TypeKind != TypeKind.TypeParameter) { return false; } var typeParameter = (TypeParameterSymbol)type; // https://github.com/dotnet/roslyn/issues/30056: Test `where T : unmanaged`. See // UninitializedNonNullableFieldTests.TypeParameterConstraints for instance. return !typeParameter.IsValueType && !(typeParameter.IsReferenceType && typeParameter.IsNotNullable == true); } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => false /// T where T : IComparable? => true /// </summary> public static bool IsPossiblyNullableReferenceTypeTypeParameter(this TypeSymbol type) { return type is TypeParameterSymbol { IsValueType: false, IsNotNullable: false }; } public static bool IsNonNullableValueType(this TypeSymbol typeArgument) { if (!typeArgument.IsValueType) { return false; } return !IsNullableTypeOrTypeParameter(typeArgument); } public static bool IsVoidType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Void; } public static bool IsNullableTypeOrTypeParameter(this TypeSymbol? type) { if (type is null) { return false; } if (type.TypeKind == TypeKind.TypeParameter) { var constraintTypes = ((TypeParameterSymbol)type).ConstraintTypesNoUseSiteDiagnostics; foreach (var constraintType in constraintTypes) { if (constraintType.Type.IsNullableTypeOrTypeParameter()) { return true; } } return false; } return type.IsNullableType(); } /// <summary> /// Is this System.Nullable`1 type, or its substitution. /// /// To check whether a type is System.Nullable`1 or is a type parameter constrained to System.Nullable`1 /// use <see cref="TypeSymbolExtensions.IsNullableTypeOrTypeParameter" /> instead. /// </summary> public static bool IsNullableType(this TypeSymbol type) { return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; } public static TypeSymbol GetNullableUnderlyingType(this TypeSymbol type) { return type.GetNullableUnderlyingTypeWithAnnotations().Type; } public static TypeWithAnnotations GetNullableUnderlyingTypeWithAnnotations(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(IsNullableType(type)); RoslynDebug.Assert(type is NamedTypeSymbol); //not testing Kind because it may be an ErrorType return ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } public static TypeSymbol StrippedType(this TypeSymbol type) { return type.IsNullableType() ? type.GetNullableUnderlyingType() : type; } public static TypeSymbol EnumUnderlyingTypeOrSelf(this TypeSymbol type) { return type.GetEnumUnderlyingType() ?? type; } public static bool IsNativeIntegerOrNullableNativeIntegerType(this TypeSymbol? type) { return type?.StrippedType().IsNativeIntegerType == true; } public static bool IsObjectType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Object; } public static bool IsStringType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_String; } public static bool IsCharType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Char; } public static bool IsIntegralType(this TypeSymbol type) { return type.SpecialType.IsIntegralType(); } public static NamedTypeSymbol? GetEnumUnderlyingType(this TypeSymbol? type) { return (type is NamedTypeSymbol namedType) ? namedType.EnumUnderlyingType : null; } public static bool IsEnumType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Enum; } public static bool IsValidEnumType(this TypeSymbol type) { var underlyingType = type.GetEnumUnderlyingType(); // SpecialType will be None if the underlying type is invalid. return (underlyingType is object) && (underlyingType.SpecialType != SpecialType.None); } /// <summary> /// Determines if the given type is a valid attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns></returns> public static bool IsValidAttributeParameterType(this TypeSymbol type, CSharpCompilation compilation) { return GetAttributeParameterTypedConstantKind(type, compilation) != TypedConstantKind.Error; } /// <summary> /// Gets the typed constant kind for the given attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns>TypedConstantKind for the attribute parameter type.</returns> public static TypedConstantKind GetAttributeParameterTypedConstantKind(this TypeSymbol type, CSharpCompilation compilation) { // Spec (17.1.3) // The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: // 1) One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. // 2) The type object. // 3) The type System.Type. // 4) An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility. // 5) Single-dimensional arrays of the above types. // A constructor argument or public field which does not have one of these types, cannot be used as a positional // or named parameter in an attribute specification. TypedConstantKind kind = TypedConstantKind.Error; if ((object)type == null) { return TypedConstantKind.Error; } if (type.Kind == SymbolKind.ArrayType) { var arrayType = (ArrayTypeSymbol)type; if (!arrayType.IsSZArray) { return TypedConstantKind.Error; } kind = TypedConstantKind.Array; type = arrayType.ElementType; } // enum or enum[] if (type.IsEnumType()) { // SPEC VIOLATION: Dev11 doesn't enforce either the Enum type or its enclosing types (if any) to have public accessibility. // We will be consistent with Dev11 behavior. if (kind == TypedConstantKind.Error) { // set only if kind is not already set (i.e. its not an array of enum) kind = TypedConstantKind.Enum; } type = type.GetEnumUnderlyingType()!; } var typedConstantKind = TypedConstant.GetTypedConstantKind(type, compilation); switch (typedConstantKind) { case TypedConstantKind.Array: case TypedConstantKind.Enum: case TypedConstantKind.Error: return TypedConstantKind.Error; default: if (kind == TypedConstantKind.Array || kind == TypedConstantKind.Enum) { // Array/Enum type with valid element/underlying type return kind; } return typedConstantKind; } } public static bool IsValidExtensionParameterType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.Dynamic: case TypeKind.FunctionPointer: return false; default: return true; } } public static bool IsInterfaceType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)type).IsInterface; } public static bool IsClassType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Class; } public static bool IsStructType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Struct; } public static bool IsErrorType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.ErrorType; } public static bool IsMethodTypeParameter(this TypeParameterSymbol p) { return p.ContainingSymbol.Kind == SymbolKind.Method; } public static bool IsDynamic(this TypeSymbol type) { return type.TypeKind == TypeKind.Dynamic; } public static bool IsTypeParameter(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.TypeParameter; } public static bool IsArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array; } public static bool IsSZArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array && ((ArrayTypeSymbol)type).IsSZArray; } public static bool IsFunctionPointer(this TypeSymbol type) { return type.TypeKind == TypeKind.FunctionPointer; } public static bool IsPointerOrFunctionPointer(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; default: return false; } } // If the type is a delegate type, it returns it. If the type is an // expression tree type associated with a delegate type, it returns // the delegate type. Otherwise, null. public static NamedTypeSymbol? GetDelegateType(this TypeSymbol? type) { if (type is null) return null; if (type.IsExpressionTree()) { type = ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; } return type.IsDelegateType() ? (NamedTypeSymbol)type : null; } public static TypeSymbol? GetDelegateOrFunctionPointerType(this TypeSymbol? type) { return (TypeSymbol?)GetDelegateType(type) ?? type as FunctionPointerTypeSymbol; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter. /// </summary> public static bool IsExpressionTree(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && isGenericType; } /// <summary> /// Returns true if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsNonGenericExpressionType(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && !isGenericType; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter, or if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsGenericOrNonGenericExpressionType(this TypeSymbol _type, out bool isGenericType) { if (_type.OriginalDefinition is NamedTypeSymbol type) { switch (type.Name) { case "Expression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName)) { if (type.Arity == 0) { isGenericType = false; return true; } if (type.Arity == 1 && type.MangleName) { isGenericType = true; return true; } } break; case "LambdaExpression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName) && type.Arity == 0) { isGenericType = false; return true; } break; } } isGenericType = false; return false; } /// <summary> /// return true if the type is constructed from a generic interface that /// might be implemented by an array. /// </summary> public static bool IsPossibleArrayGenericInterface(this TypeSymbol type) { if (!(type is NamedTypeSymbol t)) { return false; } t = t.OriginalDefinition; SpecialType st = t.SpecialType; if (st == SpecialType.System_Collections_Generic_IList_T || st == SpecialType.System_Collections_Generic_ICollection_T || st == SpecialType.System_Collections_Generic_IEnumerable_T || st == SpecialType.System_Collections_Generic_IReadOnlyList_T || st == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { return true; } return false; } private static readonly string[] s_expressionsNamespaceName = { "Expressions", "Linq", MetadataHelpers.SystemString, "" }; private static bool IsNamespaceName(Symbol symbol, string[] names) { if (symbol.Kind != SymbolKind.Namespace) { return false; } for (int i = 0; i < names.Length; i++) { if ((object)symbol == null || symbol.Name != names[i]) return false; symbol = symbol.ContainingSymbol; } return true; } public static bool IsDelegateType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Delegate; } public static ImmutableArray<ParameterSymbol> DelegateParameters(this TypeSymbol type) { var invokeMethod = type.DelegateInvokeMethod(); if ((object)invokeMethod == null) { return default(ImmutableArray<ParameterSymbol>); } return invokeMethod.Parameters; } public static ImmutableArray<ParameterSymbol> DelegateOrFunctionPointerParameters(this TypeSymbol type) { Debug.Assert(type is FunctionPointerTypeSymbol || type.IsDelegateType()); if (type is FunctionPointerTypeSymbol { Signature: { Parameters: var functionPointerParameters } }) { return functionPointerParameters; } else { return type.DelegateParameters(); } } public static bool TryGetElementTypesWithAnnotationsIfTupleType(this TypeSymbol type, out ImmutableArray<TypeWithAnnotations> elementTypes) { if (type.IsTupleType) { elementTypes = ((NamedTypeSymbol)type).TupleElementTypesWithAnnotations; return true; } // source not a tuple elementTypes = default(ImmutableArray<TypeWithAnnotations>); return false; } public static MethodSymbol DelegateInvokeMethod(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(type.IsDelegateType() || type.IsExpressionTree()); return type.GetDelegateType()!.DelegateInvokeMethod; } /// <summary> /// Return the default value constant for the given type, /// or null if the default value is not a constant. /// </summary> public static ConstantValue? GetDefaultValue(this TypeSymbol type) { // SPEC: A default-value-expression is a constant expression (§7.19) if the type // SPEC: is a reference type or a type parameter that is known to be a reference type (§10.1.5). // SPEC: In addition, a default-value-expression is a constant expression if the type is // SPEC: one of the following value types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type. RoslynDebug.Assert((object)type != null); if (type.IsErrorType()) { return null; } if (type.IsReferenceType) { return ConstantValue.Null; } if (type.IsValueType) { type = type.EnumUnderlyingTypeOrSelf(); switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Char: case SpecialType.System_Boolean: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: return ConstantValue.Default(type.SpecialType); } } return null; } public static SpecialType GetSpecialTypeSafe(this TypeSymbol? type) { return type is object ? type.SpecialType : SpecialType.None; } public static bool IsAtLeastAsVisibleAs(this TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { CompoundUseSiteInfo<AssemblySymbol> localUseSiteInfo = useSiteInfo; var result = type.VisitType((type1, symbol, unused) => IsTypeLessVisibleThan(type1, symbol, ref localUseSiteInfo), sym, canDigThroughNullable: true); // System.Nullable is public useSiteInfo = localUseSiteInfo; return result is null; } private static bool IsTypeLessVisibleThan(TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: case TypeKind.Submission: return !IsAsRestrictive((NamedTypeSymbol)type, sym, ref useSiteInfo); default: return false; } } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type" /// (such as A in A[], or { A&lt;T&gt;, T, U } in A&lt;T&gt;.B&lt;U&gt;) invoking 'predicate' /// with the type and 'arg' at each sub type. If the predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> public static TypeSymbol? VisitType<T>( this TypeSymbol type, Func<TypeSymbol, T, bool, bool> predicate, T arg, bool canDigThroughNullable = false) { return VisitType( typeWithAnnotationsOpt: default, type: type, typeWithAnnotationsPredicate: null, typePredicate: predicate, arg, canDigThroughNullable); } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type". /// One of the predicates will be invoked at each type. If the type is a /// TypeWithAnnotations, <paramref name="typeWithAnnotationsPredicate"/> /// will be invoked; otherwise <paramref name="typePredicate"/> will be invoked. /// If the corresponding predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> /// <param name="useDefaultType">If true, use <see cref="TypeWithAnnotations.DefaultType"/> /// instead of <see cref="TypeWithAnnotations.Type"/> to avoid early resolution of nullable types</param> public static TypeSymbol? VisitType<T>( this TypeWithAnnotations typeWithAnnotationsOpt, TypeSymbol? type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool canDigThroughNullable = false, bool useDefaultType = false) { RoslynDebug.Assert(typeWithAnnotationsOpt.HasType == (type is null)); RoslynDebug.Assert(canDigThroughNullable == false || useDefaultType == false, "digging through nullable will cause early resolution of nullable types"); // In order to handle extremely "deep" types like "int[][][][][][][][][]...[]" // or int*****************...* we implement manual tail recursion rather than // doing the natural recursion. while (true) { TypeSymbol current = type ?? (useDefaultType ? typeWithAnnotationsOpt.DefaultType : typeWithAnnotationsOpt.Type); bool isNestedNamedType = false; // Visit containing types from outer-most to inner-most. switch (current.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: { var containingType = current.ContainingType; if ((object)containingType != null) { isNestedNamedType = true; var result = VisitType(default, containingType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { return result; } } } break; case TypeKind.Submission: RoslynDebug.Assert((object)current.ContainingType == null); break; } if (typeWithAnnotationsOpt.HasType && typeWithAnnotationsPredicate != null) { if (typeWithAnnotationsPredicate(typeWithAnnotationsOpt, arg, isNestedNamedType)) { return current; } } else if (typePredicate != null) { if (typePredicate(current, arg, isNestedNamedType)) { return current; } } TypeWithAnnotations next; switch (current.TypeKind) { case TypeKind.Dynamic: case TypeKind.TypeParameter: case TypeKind.Submission: case TypeKind.Enum: return null; case TypeKind.Error: case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Delegate: var typeArguments = ((NamedTypeSymbol)current).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; if (typeArguments.IsEmpty) { return null; } int i; for (i = 0; i < typeArguments.Length - 1; i++) { // Let's try to avoid early resolution of nullable types (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(typeArguments[i], canDigThroughNullable); var result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { return result; } } next = typeArguments[i]; break; case TypeKind.Array: next = ((ArrayTypeSymbol)current).ElementTypeWithAnnotations; break; case TypeKind.Pointer: next = ((PointerTypeSymbol)current).PointedAtTypeWithAnnotations; break; case TypeKind.FunctionPointer: { var result = visitFunctionPointerType((FunctionPointerTypeSymbol)current, typeWithAnnotationsPredicate, typePredicate, arg, useDefaultType, canDigThroughNullable, out next); if (result is object) { return result; } break; } default: throw ExceptionUtilities.UnexpectedValue(current.TypeKind); } // Let's try to avoid early resolution of nullable types typeWithAnnotationsOpt = canDigThroughNullable ? default : next; type = canDigThroughNullable ? next.NullableUnderlyingTypeOrSelf : null; } static (TypeWithAnnotations, TypeSymbol?) getNextIterationElements(TypeWithAnnotations type, bool canDigThroughNullable) => canDigThroughNullable ? (default(TypeWithAnnotations), type.NullableUnderlyingTypeOrSelf) : (type, null); static TypeSymbol? visitFunctionPointerType(FunctionPointerTypeSymbol type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool useDefaultType, bool canDigThroughNullable, out TypeWithAnnotations next) { MethodSymbol currentPointer = type.Signature; if (currentPointer.ParameterCount == 0) { next = currentPointer.ReturnTypeWithAnnotations; return null; } var result = VisitType( typeWithAnnotationsOpt: canDigThroughNullable ? default : currentPointer.ReturnTypeWithAnnotations, type: canDigThroughNullable ? currentPointer.ReturnTypeWithAnnotations.NullableUnderlyingTypeOrSelf : null, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { next = default; return result; } int i; for (i = 0; i < currentPointer.ParameterCount - 1; i++) { (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(currentPointer.Parameters[i].TypeWithAnnotations, canDigThroughNullable); result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { next = default; return result; } } next = currentPointer.Parameters[i].TypeWithAnnotations; return null; } } private static bool IsAsRestrictive(NamedTypeSymbol s1, Symbol sym2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Accessibility acc1 = s1.DeclaredAccessibility; if (acc1 == Accessibility.Public) { return true; } for (Symbol s2 = sym2; s2.Kind != SymbolKind.Namespace; s2 = s2.ContainingSymbol) { Accessibility acc2 = s2.DeclaredAccessibility; switch (acc1) { case Accessibility.Internal: { // If s2 is private or internal, and within the same assembly as s1, // then this is at least as restrictive as s1's internal. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; } case Accessibility.ProtectedAndInternal: // Since s1 is private protected, s2 must pass the test for being both more restrictive than internal and more restrictive than protected. // We first do the "internal" test (copied from above), then if it passes we continue with the "protected" test. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { // passed the internal test; now do the test for the protected case goto case Accessibility.Protected; } break; case Accessibility.Protected: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { // not helpful } else if (acc2 == Accessibility.Private) { // if s2 is private and within s1's parent or within a subclass of s1's parent, // then this is at least as restrictive as s1's protected. for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } } else if (acc2 == Accessibility.Protected || acc2 == Accessibility.ProtectedAndInternal) { // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's protected var parent2 = s2.ContainingType; if ((object)parent2 != null && parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; } case Accessibility.ProtectedOrInternal: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } switch (acc2) { case Accessibility.Private: // if s2 is private and within a subclass of s1's parent, // or within the same assembly as s1 // then this is at least as restrictive as s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; case Accessibility.Internal: // If s2 is in the same assembly as s1, then this is more restrictive // than s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; case Accessibility.Protected: // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's internal protected if (parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedAndInternal: // if s2 is private protected, and it's parent is a subclass (or the same as) s1's parent // or its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) || parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedOrInternal: // if s2 is internal protected, and it's parent is a subclass (or the same as) s1's parent // and its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) && parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; } break; } case Accessibility.Private: if (acc2 == Accessibility.Private) { // if s2 is private, and it is within s1's parent, then this is at // least as restrictive as s1's private. NamedTypeSymbol parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } var parent1OriginalDefinition = parent1.OriginalDefinition; for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (ReferenceEquals(parent2.OriginalDefinition, parent1OriginalDefinition) || parent1OriginalDefinition.TypeKind == TypeKind.Submission && parent2.TypeKind == TypeKind.Submission) { return true; } } } break; default: throw ExceptionUtilities.UnexpectedValue(acc1); } } return false; } public static bool IsUnboundGenericType(this TypeSymbol type) { return type is NamedTypeSymbol { IsUnboundGenericType: true }; } public static bool IsTopLevelType(this NamedTypeSymbol type) { return (object)type.ContainingType == null; } /// <summary> /// (null TypeParameterSymbol "parameter"): Checks if the given type is a type parameter /// or its referent type is a type parameter (array/pointer) or contains a type parameter (aggregate type) /// (non-null TypeParameterSymbol "parameter"): above + also checks if the type parameter /// is the same as "parameter" /// </summary> public static bool ContainsTypeParameter(this TypeSymbol type, TypeParameterSymbol? parameter = null) { var result = type.VisitType(s_containsTypeParameterPredicate, parameter); return result is object; } private static readonly Func<TypeSymbol, TypeParameterSymbol?, bool, bool> s_containsTypeParameterPredicate = (type, parameter, unused) => type.TypeKind == TypeKind.TypeParameter && (parameter is null || TypeSymbol.Equals(type, parameter, TypeCompareKind.ConsiderEverything2)); public static bool ContainsTypeParameter(this TypeSymbol type, MethodSymbol parameterContainer) { RoslynDebug.Assert((object)parameterContainer != null); var result = type.VisitType(s_isTypeParameterWithSpecificContainerPredicate, parameterContainer); return result is object; } private static readonly Func<TypeSymbol, Symbol, bool, bool> s_isTypeParameterWithSpecificContainerPredicate = (type, parameterContainer, unused) => type.TypeKind == TypeKind.TypeParameter && (object)type.ContainingSymbol == (object)parameterContainer; public static bool ContainsTypeParameters(this TypeSymbol type, HashSet<TypeParameterSymbol> parameters) { var result = type.VisitType(s_containsTypeParametersPredicate, parameters); return result is object; } private static readonly Func<TypeSymbol, HashSet<TypeParameterSymbol>, bool, bool> s_containsTypeParametersPredicate = (type, parameters, unused) => type.TypeKind == TypeKind.TypeParameter && parameters.Contains((TypeParameterSymbol)type); public static bool ContainsMethodTypeParameter(this TypeSymbol type) { var result = type.VisitType(s_containsMethodTypeParameterPredicate, null); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsMethodTypeParameterPredicate = (type, _, _) => type.TypeKind == TypeKind.TypeParameter && type.ContainingSymbol is MethodSymbol; /// <summary> /// Return true if the type contains any dynamic type reference. /// </summary> public static bool ContainsDynamic(this TypeSymbol type) { var result = type.VisitType(s_containsDynamicPredicate, null, canDigThroughNullable: true); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsDynamicPredicate = (type, unused1, unused2) => type.TypeKind == TypeKind.Dynamic; internal static bool ContainsNativeInteger(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsNativeIntegerType, (object?)null, canDigThroughNullable: true); return result is object; } internal static bool ContainsNativeInteger(this TypeWithAnnotations type) { return type.Type?.ContainsNativeInteger() == true; } internal static bool ContainsErrorType(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsErrorType(), (object?)null, canDigThroughNullable: true); return result is object; } /// <summary> /// Return true if the type contains any tuples. /// </summary> internal static bool ContainsTuple(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => t.IsTupleType, null) is object; /// <summary> /// Return true if the type contains any tuples with element names. /// </summary> internal static bool ContainsTupleNames(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => !t.TupleElementNames.IsDefault, null) is object; /// <summary> /// Return true if the type contains any function pointer types. /// </summary> internal static bool ContainsFunctionPointer(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) is object; /// <summary> /// Guess the non-error type that the given type was intended to represent. /// If the type itself is not an error type, then it will be returned. /// Otherwise, the underlying type (if any) of the error type will be /// returned. /// </summary> /// <remarks> /// Any non-null type symbol returned is guaranteed not to be an error type. /// /// It is possible to pass in a constructed type and received back an /// unconstructed type. This can occur when the type passed in was /// constructed from an error type - the underlying definition will be /// available, but there won't be a good way to "re-substitute" back up /// to the level of the specified type. /// </remarks> internal static TypeSymbol? GetNonErrorGuess(this TypeSymbol type) { var result = ExtendedErrorTypeSymbol.ExtractNonErrorType(type); RoslynDebug.Assert((object?)result == null || !result.IsErrorType()); return result; } /// <summary> /// Guess the non-error type kind that the given type was intended to represent, /// if possible. If not, return TypeKind.Error. /// </summary> internal static TypeKind GetNonErrorTypeKindGuess(this TypeSymbol type) { return ExtendedErrorTypeSymbol.ExtractNonErrorTypeKind(type); } /// <summary> /// Returns true if the type was a valid switch expression type in C# 6. We use this test to determine /// whether or not we should attempt a user-defined conversion from the type to a C# 6 switch governing /// type, which we support for compatibility with C# 6 and earlier. /// </summary> internal static bool IsValidV6SwitchGoverningType(this TypeSymbol type, bool isTargetTypeOfUserDefinedOp = false) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types RoslynDebug.Assert((object)type != null); if (type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } // User-defined implicit conversion with target type as Enum type is not valid. if (!isTargetTypeOfUserDefinedOp) { type = type.EnumUnderlyingTypeOrSelf(); } switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Char: case SpecialType.System_String: return true; case SpecialType.System_Boolean: // User-defined implicit conversion with target type as bool type is not valid. return !isTargetTypeOfUserDefinedOp; } return false; } #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <summary> /// Returns true if the type is one of the restricted types, namely: <see cref="T:System.TypedReference"/>, /// <see cref="T:System.ArgIterator"/>, or <see cref="T:System.RuntimeArgumentHandle"/>. /// or a ref-like type. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix internal static bool IsRestrictedType(this TypeSymbol type, bool ignoreSpanLikeTypes = false) { // See Dev10 C# compiler, "type.cpp", bool Type::isSpecialByRefType() const RoslynDebug.Assert((object)type != null); switch (type.SpecialType) { case SpecialType.System_TypedReference: case SpecialType.System_ArgIterator: case SpecialType.System_RuntimeArgumentHandle: return true; } return ignoreSpanLikeTypes ? false : type.IsRefLikeType; } public static bool IsIntrinsicType(this TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Single: case SpecialType.System_Double: // NOTE: VB treats System.DateTime as an intrinsic, while C# does not. //case SpecialType.System_DateTime: case SpecialType.System_Decimal: return true; default: return false; } } public static bool IsPartial(this TypeSymbol type) { return type is SourceNamedTypeSymbol { IsPartial: true }; } public static bool IsPointerType(this TypeSymbol type) { return type is PointerTypeSymbol; } internal static int FixedBufferElementSizeInBytes(this TypeSymbol type) { return type.SpecialType.FixedBufferElementSizeInBytes(); } // check that its type is allowed for Volatile internal static bool IsValidVolatileFieldType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Struct: return type.SpecialType.IsValidVolatileFieldType(); case TypeKind.Array: case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Dynamic: case TypeKind.Error: case TypeKind.Interface: case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Enum: return ((NamedTypeSymbol)type).EnumUnderlyingType.SpecialType.IsValidVolatileFieldType(); case TypeKind.TypeParameter: return type.IsReferenceType; case TypeKind.Submission: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } return false; } /// <summary> /// Add this instance to the set of checked types. Returns true /// if this was added, false if the type was already in the set. /// </summary> public static bool MarkCheckedIfNecessary(this TypeSymbol type, ref HashSet<TypeSymbol> checkedTypes) { if (checkedTypes == null) { checkedTypes = new HashSet<TypeSymbol>(); } return checkedTypes.Add(type); } internal static bool IsUnsafe(this TypeSymbol type) { while (true) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Array: type = ((ArrayTypeSymbol)type).ElementType; break; default: // NOTE: we could consider a generic type with unsafe type arguments to be unsafe, // but that's already an error, so there's no reason to report it. Also, this // matches Type::isUnsafe in Dev10. return false; } } } internal static bool IsVoidPointer(this TypeSymbol type) { return type is PointerTypeSymbol p && p.PointedAtType.IsVoidType(); } /// <summary> /// These special types are structs that contain fields of the same type /// (e.g. <see cref="System.Int32"/> contains an instance field of type <see cref="System.Int32"/>). /// </summary> internal static bool IsPrimitiveRecursiveStruct(this TypeSymbol t) { return t.SpecialType.IsPrimitiveRecursiveStruct(); } /// <summary> /// Compute a hash code for the constructed type. The return value will be /// non-zero so callers can used zero to represent an uninitialized value. /// </summary> internal static int ComputeHashCode(this NamedTypeSymbol type) { RoslynDebug.Assert(!type.Equals(type.OriginalDefinition, TypeCompareKind.AllIgnoreOptions) || wasConstructedForAnnotations(type)); if (wasConstructedForAnnotations(type)) { // A type that uses its own type parameters as type arguments was constructed only for the purpose of adding annotations. // In that case we'll use the hash from the definition. return type.OriginalDefinition.GetHashCode(); } int code = type.OriginalDefinition.GetHashCode(); code = Hash.Combine(type.ContainingType, code); // Unconstructed type may contain alpha-renamed type parameters while // may still be considered equal, we do not want to give different hashcode to such types. // // Example: // Having original type A<U>.B<V> we create two _unconstructed_ types // A<int>.B<V'> // A<int>.B<V"> // Note that V' and V" are type parameters substituted via alpha-renaming of original V // These are different objects, but represent the same "type parameter at index 1" // // In short - we are not interested in the type parameters of unconstructed types. if ((object)type.ConstructedFrom != (object)type) { foreach (var arg in type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { code = Hash.Combine(arg.Type, code); } } // 0 may be used by the caller to indicate the hashcode is not // initialized. If we computed 0 for the hashcode, tweak it. if (code == 0) { code++; } return code; static bool wasConstructedForAnnotations(NamedTypeSymbol type) { do { var typeArguments = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeParameters = type.OriginalDefinition.TypeParameters; for (int i = 0; i < typeArguments.Length; i++) { if (!typeParameters[i].Equals( typeArguments[i].Type.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } } type = type.ContainingType; } while (type is object && !type.IsDefinition); return true; } } /// <summary> /// If we are in a COM PIA with embedInteropTypes enabled we should turn properties and methods /// that have the type and return type of object, respectively, into type dynamic. If the requisite conditions /// are fulfilled, this method returns a dynamic type. If not, it returns the original type. /// </summary> /// <param name="type">A property type or method return type to be checked for dynamification.</param> /// <param name="containingType">Containing type.</param> /// <returns></returns> public static TypeSymbol AsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType) { return type.TryAsDynamicIfNoPia(containingType, out TypeSymbol? result) ? result : type; } public static bool TryAsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType, [NotNullWhen(true)] out TypeSymbol? result) { if (type.SpecialType == SpecialType.System_Object) { AssemblySymbol assembly = containingType.ContainingAssembly; if ((object)assembly != null && assembly.IsLinked && containingType.IsComImport) { result = DynamicTypeSymbol.Instance; return true; } } result = null; return false; } /// <summary> /// Type variables are never considered reference types by the verifier. /// </summary> internal static bool IsVerifierReference(this TypeSymbol type) { return type.IsReferenceType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Type variables are never considered value types by the verifier. /// </summary> internal static bool IsVerifierValue(this TypeSymbol type) { return type.IsValueType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this NamedTypeSymbol type) { // Avoid allocating a builder in the common case. if ((object)type.ContainingType == null) { return type.TypeParameters; } var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(builder); return builder.ToImmutableAndFree(); } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static void GetAllTypeParameters(this NamedTypeSymbol type, ArrayBuilder<TypeParameterSymbol> result) { var containingType = type.ContainingType; if ((object)containingType != null) { containingType.GetAllTypeParameters(result); } result.AddRange(type.TypeParameters); } /// <summary> /// Return the nearest type parameter with the given name in /// this type or any enclosing type. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this NamedTypeSymbol type, string name) { var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(allTypeParameters); TypeParameterSymbol? result = null; foreach (TypeParameterSymbol tpEnclosing in allTypeParameters) { if (name == tpEnclosing.Name) { result = tpEnclosing; break; } } allTypeParameters.Free(); return result; } /// <summary> /// Return the nearest type parameter with the given name in /// this symbol or any enclosing symbol. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this Symbol methodOrType, string name) { while (methodOrType != null) { switch (methodOrType.Kind) { case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: break; default: return null; } foreach (var typeParameter in methodOrType.GetMemberTypeParameters()) { if (typeParameter.Name == name) { return typeParameter; } } methodOrType = methodOrType.ContainingSymbol; } return null; } /// <summary> /// Return true if the fully qualified name of the type's containing symbol /// matches the given name. This method avoids string concatenations /// in the common case where the type is a top-level type. /// </summary> internal static bool HasNameQualifier(this NamedTypeSymbol type, string qualifiedName) { const StringComparison comparison = StringComparison.Ordinal; var container = type.ContainingSymbol; if (container.Kind != SymbolKind.Namespace) { // Nested type. For simplicity, compare qualified name to SymbolDisplay result. return string.Equals(container.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), qualifiedName, comparison); } var @namespace = (NamespaceSymbol)container; if (@namespace.IsGlobalNamespace) { return qualifiedName.Length == 0; } return HasNamespaceName(@namespace, qualifiedName, comparison, length: qualifiedName.Length); } private static bool HasNamespaceName(NamespaceSymbol @namespace, string namespaceName, StringComparison comparison, int length) { if (length == 0) { return false; } var container = @namespace.ContainingNamespace; int separator = namespaceName.LastIndexOf('.', length - 1, length); int offset = 0; if (separator >= 0) { if (container.IsGlobalNamespace) { return false; } if (!HasNamespaceName(container, namespaceName, comparison, length: separator)) { return false; } int n = separator + 1; offset = n; length -= n; } else if (!container.IsGlobalNamespace) { return false; } var name = @namespace.Name; return (name.Length == length) && (string.Compare(name, 0, namespaceName, offset, length, comparison) == 0); } internal static bool IsNonGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { var namedType = type as NamedTypeSymbol; if (namedType is null || namedType.Arity != 0) { return false; } if ((object)namedType == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)) { return true; } if (namedType.IsVoidType()) { return false; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } if ((object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) { return true; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsIAsyncEnumerableType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T); } internal static bool IsIAsyncEnumeratorType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T); } /// <summary> /// Returns true if the type is generic or non-generic custom task-like type due to the /// [AsyncMethodBuilder(typeof(B))] attribute. It returns the "B". /// </summary> /// <remarks> /// For the Task types themselves, this method might return true or false depending on mscorlib. /// The definition of "custom task-like type" is one that has an [AsyncMethodBuilder(typeof(B))] attribute, /// no more, no less. Validation of builder type B is left for elsewhere. This method returns B /// without validation of any kind. /// </remarks> internal static bool IsCustomTaskType(this NamedTypeSymbol type, [NotNullWhen(true)] out object? builderArgument) { RoslynDebug.Assert((object)type != null); var arity = type.Arity; if (arity < 2) { return type.HasAsyncMethodBuilderAttribute(out builderArgument); } builderArgument = null; return false; } /// <summary> /// Replace Task-like types with Task types. /// </summary> internal static TypeSymbol NormalizeTaskTypes(this TypeSymbol type, CSharpCompilation compilation) { NormalizeTaskTypesInType(compilation, ref type); return type; } /// <summary> /// Replace Task-like types with Task types. Returns true if there were changes. /// </summary> private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeSymbol type) { switch (type.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: { var namedType = (NamedTypeSymbol)type; var changed = NormalizeTaskTypesInNamedType(compilation, ref namedType); type = namedType; return changed; } case SymbolKind.ArrayType: { var arrayType = (ArrayTypeSymbol)type; var changed = NormalizeTaskTypesInArray(compilation, ref arrayType); type = arrayType; return changed; } case SymbolKind.PointerType: { var pointerType = (PointerTypeSymbol)type; var changed = NormalizeTaskTypesInPointer(compilation, ref pointerType); type = pointerType; return changed; } case SymbolKind.FunctionPointerType: { var functionPointerType = (FunctionPointerTypeSymbol)type; var changed = NormalizeTaskTypesInFunctionPointer(compilation, ref functionPointerType); type = functionPointerType; return changed; } } return false; } private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; if (NormalizeTaskTypesInType(compilation, ref type)) { typeWithAnnotations = TypeWithAnnotations.Create(type, customModifiers: typeWithAnnotations.CustomModifiers); return true; } return false; } private static bool NormalizeTaskTypesInNamedType(CSharpCompilation compilation, ref NamedTypeSymbol type) { bool hasChanged = false; if (!type.IsDefinition) { RoslynDebug.Assert(type.IsGenericType); var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; type.GetAllTypeArguments(typeArgumentsBuilder, ref discardedUseSiteInfo); for (int i = 0; i < typeArgumentsBuilder.Count; i++) { var typeWithModifier = typeArgumentsBuilder[i]; var typeArgNormalized = typeWithModifier.Type; if (NormalizeTaskTypesInType(compilation, ref typeArgNormalized)) { hasChanged = true; // Preserve custom modifiers but without normalizing those types. typeArgumentsBuilder[i] = TypeWithAnnotations.Create(typeArgNormalized, customModifiers: typeWithModifier.CustomModifiers); } } if (hasChanged) { var originalType = type; var originalDefinition = originalType.OriginalDefinition; var typeParameters = originalDefinition.GetAllTypeParameters(); var typeMap = new TypeMap(typeParameters, typeArgumentsBuilder.ToImmutable(), allowAlpha: true); type = typeMap.SubstituteNamedType(originalDefinition).WithTupleDataFrom(originalType); } typeArgumentsBuilder.Free(); } if (type.OriginalDefinition.IsCustomTaskType(builderArgument: out _)) { int arity = type.Arity; RoslynDebug.Assert(arity < 2); var taskType = compilation.GetWellKnownType( arity == 0 ? WellKnownType.System_Threading_Tasks_Task : WellKnownType.System_Threading_Tasks_Task_T); if (taskType.TypeKind == TypeKind.Error) { // Skip if Task types are not available. return false; } type = arity == 0 ? taskType : taskType.Construct( ImmutableArray.Create(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]), unbound: false); hasChanged = true; } return hasChanged; } private static bool NormalizeTaskTypesInArray(CSharpCompilation compilation, ref ArrayTypeSymbol arrayType) { var elementType = arrayType.ElementTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref elementType)) { return false; } arrayType = arrayType.WithElementType(elementType); return true; } private static bool NormalizeTaskTypesInPointer(CSharpCompilation compilation, ref PointerTypeSymbol pointerType) { var pointedAtType = pointerType.PointedAtTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref pointedAtType)) { return false; } // Preserve custom modifiers but without normalizing those types. pointerType = new PointerTypeSymbol(pointedAtType); return true; } private static bool NormalizeTaskTypesInFunctionPointer(CSharpCompilation compilation, ref FunctionPointerTypeSymbol funcPtrType) { var returnType = funcPtrType.Signature.ReturnTypeWithAnnotations; var madeChanges = NormalizeTaskTypesInType(compilation, ref returnType); var paramTypes = ImmutableArray<TypeWithAnnotations>.Empty; if (funcPtrType.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(funcPtrType.Signature.ParameterCount); bool madeParamChanges = false; foreach (var param in funcPtrType.Signature.Parameters) { var paramType = param.TypeWithAnnotations; madeParamChanges |= NormalizeTaskTypesInType(compilation, ref paramType); paramsBuilder.Add(paramType); } if (madeParamChanges) { madeChanges = true; paramTypes = paramsBuilder.ToImmutableAndFree(); } else { paramTypes = funcPtrType.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } if (madeChanges) { funcPtrType = funcPtrType.SubstituteTypeSymbol(returnType, paramTypes, refCustomModifiers: default, paramRefCustomModifiers: default); return true; } else { return false; } } internal static Cci.TypeReferenceWithAttributes GetTypeRefWithAttributes( this TypeWithAnnotations type, Emit.PEModuleBuilder moduleBuilder, Symbol declaringSymbol, Cci.ITypeReference typeRef) { var builder = ArrayBuilder<Cci.ICustomAttribute>.GetInstance(); var compilation = declaringSymbol.DeclaringCompilation; if (compilation != null) { if (type.Type.ContainsTupleNames()) { addIfNotNull(builder, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (type.Type.ContainsNativeInteger()) { addIfNotNull(builder, moduleBuilder.SynthesizeNativeIntegerAttribute(declaringSymbol, type.Type)); } if (compilation.ShouldEmitNullableAttributes(declaringSymbol)) { addIfNotNull(builder, moduleBuilder.SynthesizeNullableAttributeIfNecessary(declaringSymbol, declaringSymbol.GetNullableContextValue(), type)); } static void addIfNotNull(ArrayBuilder<Cci.ICustomAttribute> builder, SynthesizedAttributeData? attr) { if (attr != null) { builder.Add(attr); } } } return new Cci.TypeReferenceWithAttributes(typeRef, builder.ToImmutableAndFree()); } internal static bool IsWellKnownTypeInAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("InAttribute"); internal static bool IsWellKnownTypeUnmanagedType(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("UnmanagedType"); internal static bool IsWellKnownTypeIsExternalInit(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownCompilerServicesTopLevelType("IsExternalInit"); internal static bool IsWellKnownTypeOutAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("OutAttribute"); private static bool IsWellKnownInteropServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name || typeSymbol.ContainingType is object) { return false; } return IsContainedInNamespace(typeSymbol, "System", "Runtime", "InteropServices"); } private static bool IsWellKnownCompilerServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name) { return false; } return IsCompilerServicesTopLevelType(typeSymbol); } internal static bool IsCompilerServicesTopLevelType(this TypeSymbol typeSymbol) => typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Runtime", "CompilerServices"); private static bool IsContainedInNamespace(this TypeSymbol typeSymbol, string outerNS, string midNS, string innerNS) { var innerNamespace = typeSymbol.ContainingNamespace; if (innerNamespace?.Name != innerNS) { return false; } var midNamespace = innerNamespace.ContainingNamespace; if (midNamespace?.Name != midNS) { return false; } var outerNamespace = midNamespace.ContainingNamespace; if (outerNamespace?.Name != outerNS) { return false; } var globalNamespace = outerNamespace.ContainingNamespace; return globalNamespace != null && globalNamespace.IsGlobalNamespace; } internal static int TypeToIndex(this TypeSymbol type) { switch (type.GetSpecialTypeSafe()) { case SpecialType.System_Object: return 0; case SpecialType.System_String: return 1; case SpecialType.System_Boolean: return 2; case SpecialType.System_Char: return 3; case SpecialType.System_SByte: return 4; case SpecialType.System_Int16: return 5; case SpecialType.System_Int32: return 6; case SpecialType.System_Int64: return 7; case SpecialType.System_Byte: return 8; case SpecialType.System_UInt16: return 9; case SpecialType.System_UInt32: return 10; case SpecialType.System_UInt64: return 11; case SpecialType.System_IntPtr when type.IsNativeIntegerType: return 12; case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return 13; case SpecialType.System_Single: return 14; case SpecialType.System_Double: return 15; case SpecialType.System_Decimal: return 16; case SpecialType.None: if ((object)type != null && type.IsNullableType()) { TypeSymbol underlyingType = type.GetNullableUnderlyingType(); switch (underlyingType.GetSpecialTypeSafe()) { case SpecialType.System_Boolean: return 17; case SpecialType.System_Char: return 18; case SpecialType.System_SByte: return 19; case SpecialType.System_Int16: return 20; case SpecialType.System_Int32: return 21; case SpecialType.System_Int64: return 22; case SpecialType.System_Byte: return 23; case SpecialType.System_UInt16: return 24; case SpecialType.System_UInt32: return 25; case SpecialType.System_UInt64: return 26; case SpecialType.System_IntPtr when underlyingType.IsNativeIntegerType: return 27; case SpecialType.System_UIntPtr when underlyingType.IsNativeIntegerType: return 28; case SpecialType.System_Single: return 29; case SpecialType.System_Double: return 30; case SpecialType.System_Decimal: return 31; } } // fall through goto default; default: return -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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class TypeSymbolExtensions { public static bool ImplementsInterface(this TypeSymbol subType, TypeSymbol superInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { foreach (NamedTypeSymbol @interface in subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (@interface.IsInterface && TypeSymbol.Equals(@interface, superInterface, TypeCompareKind.ConsiderEverything2)) { return true; } } return false; } public static bool CanBeAssignedNull(this TypeSymbol type) { return type.IsReferenceType || type.IsPointerOrFunctionPointer() || type.IsNullableType(); } public static bool CanContainNull(this TypeSymbol type) { // unbound type parameters might contain null, even though they cannot be *assigned* null. return !type.IsValueType || type.IsNullableTypeOrTypeParameter(); } public static bool CanBeConst(this TypeSymbol typeSymbol) { RoslynDebug.Assert((object)typeSymbol != null); return typeSymbol.IsReferenceType || typeSymbol.IsEnumType() || typeSymbol.SpecialType.CanBeConst() || typeSymbol.IsNativeIntegerType; } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => true /// T where T : IComparable? => true /// T where T : notnull => true /// </summary> /// <remarks> /// In C#9, annotations are allowed regardless of constraints. /// </remarks> public static bool IsTypeParameterDisallowingAnnotationInCSharp8(this TypeSymbol type) { if (type.TypeKind != TypeKind.TypeParameter) { return false; } var typeParameter = (TypeParameterSymbol)type; // https://github.com/dotnet/roslyn/issues/30056: Test `where T : unmanaged`. See // UninitializedNonNullableFieldTests.TypeParameterConstraints for instance. return !typeParameter.IsValueType && !(typeParameter.IsReferenceType && typeParameter.IsNotNullable == true); } /// <summary> /// Assuming that nullable annotations are enabled: /// T => true /// T where T : struct => false /// T where T : class => false /// T where T : class? => true /// T where T : IComparable => false /// T where T : IComparable? => true /// </summary> public static bool IsPossiblyNullableReferenceTypeTypeParameter(this TypeSymbol type) { return type is TypeParameterSymbol { IsValueType: false, IsNotNullable: false }; } public static bool IsNonNullableValueType(this TypeSymbol typeArgument) { if (!typeArgument.IsValueType) { return false; } return !IsNullableTypeOrTypeParameter(typeArgument); } public static bool IsVoidType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Void; } public static bool IsNullableTypeOrTypeParameter(this TypeSymbol? type) { if (type is null) { return false; } if (type.TypeKind == TypeKind.TypeParameter) { var constraintTypes = ((TypeParameterSymbol)type).ConstraintTypesNoUseSiteDiagnostics; foreach (var constraintType in constraintTypes) { if (constraintType.Type.IsNullableTypeOrTypeParameter()) { return true; } } return false; } return type.IsNullableType(); } /// <summary> /// Is this System.Nullable`1 type, or its substitution. /// /// To check whether a type is System.Nullable`1 or is a type parameter constrained to System.Nullable`1 /// use <see cref="TypeSymbolExtensions.IsNullableTypeOrTypeParameter" /> instead. /// </summary> public static bool IsNullableType(this TypeSymbol type) { return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; } public static TypeSymbol GetNullableUnderlyingType(this TypeSymbol type) { return type.GetNullableUnderlyingTypeWithAnnotations().Type; } public static TypeWithAnnotations GetNullableUnderlyingTypeWithAnnotations(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(IsNullableType(type)); RoslynDebug.Assert(type is NamedTypeSymbol); //not testing Kind because it may be an ErrorType return ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } public static TypeSymbol StrippedType(this TypeSymbol type) { return type.IsNullableType() ? type.GetNullableUnderlyingType() : type; } public static TypeSymbol EnumUnderlyingTypeOrSelf(this TypeSymbol type) { return type.GetEnumUnderlyingType() ?? type; } public static bool IsNativeIntegerOrNullableNativeIntegerType(this TypeSymbol? type) { return type?.StrippedType().IsNativeIntegerType == true; } public static bool IsObjectType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Object; } public static bool IsStringType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_String; } public static bool IsCharType(this TypeSymbol type) { return type.SpecialType == SpecialType.System_Char; } public static bool IsIntegralType(this TypeSymbol type) { return type.SpecialType.IsIntegralType(); } public static NamedTypeSymbol? GetEnumUnderlyingType(this TypeSymbol? type) { return (type is NamedTypeSymbol namedType) ? namedType.EnumUnderlyingType : null; } public static bool IsEnumType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Enum; } public static bool IsValidEnumType(this TypeSymbol type) { var underlyingType = type.GetEnumUnderlyingType(); // SpecialType will be None if the underlying type is invalid. return (underlyingType is object) && (underlyingType.SpecialType != SpecialType.None); } /// <summary> /// Determines if the given type is a valid attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns></returns> public static bool IsValidAttributeParameterType(this TypeSymbol type, CSharpCompilation compilation) { return GetAttributeParameterTypedConstantKind(type, compilation) != TypedConstantKind.Error; } /// <summary> /// Gets the typed constant kind for the given attribute parameter type. /// </summary> /// <param name="type">Type to validated</param> /// <param name="compilation">compilation</param> /// <returns>TypedConstantKind for the attribute parameter type.</returns> public static TypedConstantKind GetAttributeParameterTypedConstantKind(this TypeSymbol type, CSharpCompilation compilation) { // Spec (17.1.3) // The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: // 1) One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. // 2) The type object. // 3) The type System.Type. // 4) An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility. // 5) Single-dimensional arrays of the above types. // A constructor argument or public field which does not have one of these types, cannot be used as a positional // or named parameter in an attribute specification. TypedConstantKind kind = TypedConstantKind.Error; if ((object)type == null) { return TypedConstantKind.Error; } if (type.Kind == SymbolKind.ArrayType) { var arrayType = (ArrayTypeSymbol)type; if (!arrayType.IsSZArray) { return TypedConstantKind.Error; } kind = TypedConstantKind.Array; type = arrayType.ElementType; } // enum or enum[] if (type.IsEnumType()) { // SPEC VIOLATION: Dev11 doesn't enforce either the Enum type or its enclosing types (if any) to have public accessibility. // We will be consistent with Dev11 behavior. if (kind == TypedConstantKind.Error) { // set only if kind is not already set (i.e. its not an array of enum) kind = TypedConstantKind.Enum; } type = type.GetEnumUnderlyingType()!; } var typedConstantKind = TypedConstant.GetTypedConstantKind(type, compilation); switch (typedConstantKind) { case TypedConstantKind.Array: case TypedConstantKind.Enum: case TypedConstantKind.Error: return TypedConstantKind.Error; default: if (kind == TypedConstantKind.Array || kind == TypedConstantKind.Enum) { // Array/Enum type with valid element/underlying type return kind; } return typedConstantKind; } } public static bool IsValidExtensionParameterType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.Dynamic: case TypeKind.FunctionPointer: return false; default: return true; } } public static bool IsInterfaceType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)type).IsInterface; } public static bool IsClassType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Class; } public static bool IsStructType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Struct; } public static bool IsErrorType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.Kind == SymbolKind.ErrorType; } public static bool IsMethodTypeParameter(this TypeParameterSymbol p) { return p.ContainingSymbol.Kind == SymbolKind.Method; } public static bool IsDynamic(this TypeSymbol type) { return type.TypeKind == TypeKind.Dynamic; } public static bool IsTypeParameter(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.TypeParameter; } public static bool IsArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array; } public static bool IsSZArray(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Array && ((ArrayTypeSymbol)type).IsSZArray; } public static bool IsFunctionPointer(this TypeSymbol type) { return type.TypeKind == TypeKind.FunctionPointer; } public static bool IsPointerOrFunctionPointer(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; default: return false; } } // If the type is a delegate type, it returns it. If the type is an // expression tree type associated with a delegate type, it returns // the delegate type. Otherwise, null. public static NamedTypeSymbol? GetDelegateType(this TypeSymbol? type) { if (type is null) return null; if (type.IsExpressionTree()) { type = ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; } return type.IsDelegateType() ? (NamedTypeSymbol)type : null; } public static TypeSymbol? GetDelegateOrFunctionPointerType(this TypeSymbol? type) { return (TypeSymbol?)GetDelegateType(type) ?? type as FunctionPointerTypeSymbol; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter. /// </summary> public static bool IsExpressionTree(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && isGenericType; } /// <summary> /// Returns true if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsNonGenericExpressionType(this TypeSymbol type) { return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && !isGenericType; } /// <summary> /// Returns true if the type is constructed from a generic type named "System.Linq.Expressions.Expression" /// with one type parameter, or if the type is a non-generic type named "System.Linq.Expressions.Expression" /// or "System.Linq.Expressions.LambdaExpression". /// </summary> public static bool IsGenericOrNonGenericExpressionType(this TypeSymbol _type, out bool isGenericType) { if (_type.OriginalDefinition is NamedTypeSymbol type) { switch (type.Name) { case "Expression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName)) { if (type.Arity == 0) { isGenericType = false; return true; } if (type.Arity == 1 && type.MangleName) { isGenericType = true; return true; } } break; case "LambdaExpression": if (IsNamespaceName(type.ContainingSymbol, s_expressionsNamespaceName) && type.Arity == 0) { isGenericType = false; return true; } break; } } isGenericType = false; return false; } /// <summary> /// return true if the type is constructed from a generic interface that /// might be implemented by an array. /// </summary> public static bool IsPossibleArrayGenericInterface(this TypeSymbol type) { if (!(type is NamedTypeSymbol t)) { return false; } t = t.OriginalDefinition; SpecialType st = t.SpecialType; if (st == SpecialType.System_Collections_Generic_IList_T || st == SpecialType.System_Collections_Generic_ICollection_T || st == SpecialType.System_Collections_Generic_IEnumerable_T || st == SpecialType.System_Collections_Generic_IReadOnlyList_T || st == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { return true; } return false; } private static readonly string[] s_expressionsNamespaceName = { "Expressions", "Linq", MetadataHelpers.SystemString, "" }; private static bool IsNamespaceName(Symbol symbol, string[] names) { if (symbol.Kind != SymbolKind.Namespace) { return false; } for (int i = 0; i < names.Length; i++) { if ((object)symbol == null || symbol.Name != names[i]) return false; symbol = symbol.ContainingSymbol; } return true; } public static bool IsDelegateType(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); return type.TypeKind == TypeKind.Delegate; } public static ImmutableArray<ParameterSymbol> DelegateParameters(this TypeSymbol type) { var invokeMethod = type.DelegateInvokeMethod(); if (invokeMethod is null) { return default(ImmutableArray<ParameterSymbol>); } return invokeMethod.Parameters; } public static ImmutableArray<ParameterSymbol> DelegateOrFunctionPointerParameters(this TypeSymbol type) { Debug.Assert(type is FunctionPointerTypeSymbol || type.IsDelegateType()); if (type is FunctionPointerTypeSymbol { Signature: { Parameters: var functionPointerParameters } }) { return functionPointerParameters; } else { return type.DelegateParameters(); } } public static bool TryGetElementTypesWithAnnotationsIfTupleType(this TypeSymbol type, out ImmutableArray<TypeWithAnnotations> elementTypes) { if (type.IsTupleType) { elementTypes = ((NamedTypeSymbol)type).TupleElementTypesWithAnnotations; return true; } // source not a tuple elementTypes = default(ImmutableArray<TypeWithAnnotations>); return false; } public static MethodSymbol? DelegateInvokeMethod(this TypeSymbol type) { RoslynDebug.Assert((object)type != null); RoslynDebug.Assert(type.IsDelegateType() || type.IsExpressionTree()); return type.GetDelegateType()!.DelegateInvokeMethod; } /// <summary> /// Return the default value constant for the given type, /// or null if the default value is not a constant. /// </summary> public static ConstantValue? GetDefaultValue(this TypeSymbol type) { // SPEC: A default-value-expression is a constant expression (§7.19) if the type // SPEC: is a reference type or a type parameter that is known to be a reference type (§10.1.5). // SPEC: In addition, a default-value-expression is a constant expression if the type is // SPEC: one of the following value types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type. RoslynDebug.Assert((object)type != null); if (type.IsErrorType()) { return null; } if (type.IsReferenceType) { return ConstantValue.Null; } if (type.IsValueType) { type = type.EnumUnderlyingTypeOrSelf(); switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Char: case SpecialType.System_Boolean: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: return ConstantValue.Default(type.SpecialType); } } return null; } public static SpecialType GetSpecialTypeSafe(this TypeSymbol? type) { return type is object ? type.SpecialType : SpecialType.None; } public static bool IsAtLeastAsVisibleAs(this TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { CompoundUseSiteInfo<AssemblySymbol> localUseSiteInfo = useSiteInfo; var result = type.VisitType((type1, symbol, unused) => IsTypeLessVisibleThan(type1, symbol, ref localUseSiteInfo), sym, canDigThroughNullable: true); // System.Nullable is public useSiteInfo = localUseSiteInfo; return result is null; } private static bool IsTypeLessVisibleThan(TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: case TypeKind.Submission: return !IsAsRestrictive((NamedTypeSymbol)type, sym, ref useSiteInfo); default: return false; } } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type" /// (such as A in A[], or { A&lt;T&gt;, T, U } in A&lt;T&gt;.B&lt;U&gt;) invoking 'predicate' /// with the type and 'arg' at each sub type. If the predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> public static TypeSymbol? VisitType<T>( this TypeSymbol type, Func<TypeSymbol, T, bool, bool> predicate, T arg, bool canDigThroughNullable = false) { return VisitType( typeWithAnnotationsOpt: default, type: type, typeWithAnnotationsPredicate: null, typePredicate: predicate, arg, canDigThroughNullable); } /// <summary> /// Visit the given type and, in the case of compound types, visit all "sub type". /// One of the predicates will be invoked at each type. If the type is a /// TypeWithAnnotations, <paramref name="typeWithAnnotationsPredicate"/> /// will be invoked; otherwise <paramref name="typePredicate"/> will be invoked. /// If the corresponding predicate returns true for any type, /// traversal stops and that type is returned from this method. Otherwise if traversal /// completes without the predicate returning true for any type, this method returns null. /// </summary> /// <param name="useDefaultType">If true, use <see cref="TypeWithAnnotations.DefaultType"/> /// instead of <see cref="TypeWithAnnotations.Type"/> to avoid early resolution of nullable types</param> public static TypeSymbol? VisitType<T>( this TypeWithAnnotations typeWithAnnotationsOpt, TypeSymbol? type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool canDigThroughNullable = false, bool useDefaultType = false) { RoslynDebug.Assert(typeWithAnnotationsOpt.HasType == (type is null)); RoslynDebug.Assert(canDigThroughNullable == false || useDefaultType == false, "digging through nullable will cause early resolution of nullable types"); // In order to handle extremely "deep" types like "int[][][][][][][][][]...[]" // or int*****************...* we implement manual tail recursion rather than // doing the natural recursion. while (true) { TypeSymbol current = type ?? (useDefaultType ? typeWithAnnotationsOpt.DefaultType : typeWithAnnotationsOpt.Type); bool isNestedNamedType = false; // Visit containing types from outer-most to inner-most. switch (current.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: { var containingType = current.ContainingType; if ((object)containingType != null) { isNestedNamedType = true; var result = VisitType(default, containingType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { return result; } } } break; case TypeKind.Submission: RoslynDebug.Assert((object)current.ContainingType == null); break; } if (typeWithAnnotationsOpt.HasType && typeWithAnnotationsPredicate != null) { if (typeWithAnnotationsPredicate(typeWithAnnotationsOpt, arg, isNestedNamedType)) { return current; } } else if (typePredicate != null) { if (typePredicate(current, arg, isNestedNamedType)) { return current; } } TypeWithAnnotations next; switch (current.TypeKind) { case TypeKind.Dynamic: case TypeKind.TypeParameter: case TypeKind.Submission: case TypeKind.Enum: return null; case TypeKind.Error: case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Delegate: var typeArguments = ((NamedTypeSymbol)current).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; if (typeArguments.IsEmpty) { return null; } int i; for (i = 0; i < typeArguments.Length - 1; i++) { // Let's try to avoid early resolution of nullable types (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(typeArguments[i], canDigThroughNullable); var result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { return result; } } next = typeArguments[i]; break; case TypeKind.Array: next = ((ArrayTypeSymbol)current).ElementTypeWithAnnotations; break; case TypeKind.Pointer: next = ((PointerTypeSymbol)current).PointedAtTypeWithAnnotations; break; case TypeKind.FunctionPointer: { var result = visitFunctionPointerType((FunctionPointerTypeSymbol)current, typeWithAnnotationsPredicate, typePredicate, arg, useDefaultType, canDigThroughNullable, out next); if (result is object) { return result; } break; } default: throw ExceptionUtilities.UnexpectedValue(current.TypeKind); } // Let's try to avoid early resolution of nullable types typeWithAnnotationsOpt = canDigThroughNullable ? default : next; type = canDigThroughNullable ? next.NullableUnderlyingTypeOrSelf : null; } static (TypeWithAnnotations, TypeSymbol?) getNextIterationElements(TypeWithAnnotations type, bool canDigThroughNullable) => canDigThroughNullable ? (default(TypeWithAnnotations), type.NullableUnderlyingTypeOrSelf) : (type, null); static TypeSymbol? visitFunctionPointerType(FunctionPointerTypeSymbol type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool useDefaultType, bool canDigThroughNullable, out TypeWithAnnotations next) { MethodSymbol currentPointer = type.Signature; if (currentPointer.ParameterCount == 0) { next = currentPointer.ReturnTypeWithAnnotations; return null; } var result = VisitType( typeWithAnnotationsOpt: canDigThroughNullable ? default : currentPointer.ReturnTypeWithAnnotations, type: canDigThroughNullable ? currentPointer.ReturnTypeWithAnnotations.NullableUnderlyingTypeOrSelf : null, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { next = default; return result; } int i; for (i = 0; i < currentPointer.ParameterCount - 1; i++) { (TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(currentPointer.Parameters[i].TypeWithAnnotations, canDigThroughNullable); result = VisitType( typeWithAnnotationsOpt: nextTypeWithAnnotations, type: nextType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType); if (result is object) { next = default; return result; } } next = currentPointer.Parameters[i].TypeWithAnnotations; return null; } } private static bool IsAsRestrictive(NamedTypeSymbol s1, Symbol sym2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Accessibility acc1 = s1.DeclaredAccessibility; if (acc1 == Accessibility.Public) { return true; } for (Symbol s2 = sym2; s2.Kind != SymbolKind.Namespace; s2 = s2.ContainingSymbol) { Accessibility acc2 = s2.DeclaredAccessibility; switch (acc1) { case Accessibility.Internal: { // If s2 is private or internal, and within the same assembly as s1, // then this is at least as restrictive as s1's internal. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; } case Accessibility.ProtectedAndInternal: // Since s1 is private protected, s2 must pass the test for being both more restrictive than internal and more restrictive than protected. // We first do the "internal" test (copied from above), then if it passes we continue with the "protected" test. if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { // passed the internal test; now do the test for the protected case goto case Accessibility.Protected; } break; case Accessibility.Protected: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { // not helpful } else if (acc2 == Accessibility.Private) { // if s2 is private and within s1's parent or within a subclass of s1's parent, // then this is at least as restrictive as s1's protected. for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } } else if (acc2 == Accessibility.Protected || acc2 == Accessibility.ProtectedAndInternal) { // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's protected var parent2 = s2.ContainingType; if ((object)parent2 != null && parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; } case Accessibility.ProtectedOrInternal: { var parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } switch (acc2) { case Accessibility.Private: // if s2 is private and within a subclass of s1's parent, // or within the same assembly as s1 // then this is at least as restrictive as s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo)) { return true; } } break; case Accessibility.Internal: // If s2 is in the same assembly as s1, then this is more restrictive // than s1's internal protected. if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly)) { return true; } break; case Accessibility.Protected: // if s2 is protected, and it's parent is a subclass (or the same as) s1's parent // then this is at least as restrictive as s1's internal protected if (parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedAndInternal: // if s2 is private protected, and it's parent is a subclass (or the same as) s1's parent // or its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) || parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; case Accessibility.ProtectedOrInternal: // if s2 is internal protected, and it's parent is a subclass (or the same as) s1's parent // and its in the same assembly as s1, then this is at least as restrictive as s1's protected if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) && parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo)) { return true; } break; } break; } case Accessibility.Private: if (acc2 == Accessibility.Private) { // if s2 is private, and it is within s1's parent, then this is at // least as restrictive as s1's private. NamedTypeSymbol parent1 = s1.ContainingType; if ((object)parent1 == null) { break; } var parent1OriginalDefinition = parent1.OriginalDefinition; for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType) { if (ReferenceEquals(parent2.OriginalDefinition, parent1OriginalDefinition) || parent1OriginalDefinition.TypeKind == TypeKind.Submission && parent2.TypeKind == TypeKind.Submission) { return true; } } } break; default: throw ExceptionUtilities.UnexpectedValue(acc1); } } return false; } public static bool IsUnboundGenericType(this TypeSymbol type) { return type is NamedTypeSymbol { IsUnboundGenericType: true }; } public static bool IsTopLevelType(this NamedTypeSymbol type) { return (object)type.ContainingType == null; } /// <summary> /// (null TypeParameterSymbol "parameter"): Checks if the given type is a type parameter /// or its referent type is a type parameter (array/pointer) or contains a type parameter (aggregate type) /// (non-null TypeParameterSymbol "parameter"): above + also checks if the type parameter /// is the same as "parameter" /// </summary> public static bool ContainsTypeParameter(this TypeSymbol type, TypeParameterSymbol? parameter = null) { var result = type.VisitType(s_containsTypeParameterPredicate, parameter); return result is object; } private static readonly Func<TypeSymbol, TypeParameterSymbol?, bool, bool> s_containsTypeParameterPredicate = (type, parameter, unused) => type.TypeKind == TypeKind.TypeParameter && (parameter is null || TypeSymbol.Equals(type, parameter, TypeCompareKind.ConsiderEverything2)); public static bool ContainsTypeParameter(this TypeSymbol type, MethodSymbol parameterContainer) { RoslynDebug.Assert((object)parameterContainer != null); var result = type.VisitType(s_isTypeParameterWithSpecificContainerPredicate, parameterContainer); return result is object; } private static readonly Func<TypeSymbol, Symbol, bool, bool> s_isTypeParameterWithSpecificContainerPredicate = (type, parameterContainer, unused) => type.TypeKind == TypeKind.TypeParameter && (object)type.ContainingSymbol == (object)parameterContainer; public static bool ContainsTypeParameters(this TypeSymbol type, HashSet<TypeParameterSymbol> parameters) { var result = type.VisitType(s_containsTypeParametersPredicate, parameters); return result is object; } private static readonly Func<TypeSymbol, HashSet<TypeParameterSymbol>, bool, bool> s_containsTypeParametersPredicate = (type, parameters, unused) => type.TypeKind == TypeKind.TypeParameter && parameters.Contains((TypeParameterSymbol)type); public static bool ContainsMethodTypeParameter(this TypeSymbol type) { var result = type.VisitType(s_containsMethodTypeParameterPredicate, null); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsMethodTypeParameterPredicate = (type, _, _) => type.TypeKind == TypeKind.TypeParameter && type.ContainingSymbol is MethodSymbol; /// <summary> /// Return true if the type contains any dynamic type reference. /// </summary> public static bool ContainsDynamic(this TypeSymbol type) { var result = type.VisitType(s_containsDynamicPredicate, null, canDigThroughNullable: true); return result is object; } private static readonly Func<TypeSymbol, object?, bool, bool> s_containsDynamicPredicate = (type, unused1, unused2) => type.TypeKind == TypeKind.Dynamic; internal static bool ContainsNativeInteger(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsNativeIntegerType, (object?)null, canDigThroughNullable: true); return result is object; } internal static bool ContainsNativeInteger(this TypeWithAnnotations type) { return type.Type?.ContainsNativeInteger() == true; } internal static bool ContainsErrorType(this TypeSymbol type) { var result = type.VisitType((type, unused1, unused2) => type.IsErrorType(), (object?)null, canDigThroughNullable: true); return result is object; } /// <summary> /// Return true if the type contains any tuples. /// </summary> internal static bool ContainsTuple(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => t.IsTupleType, null) is object; /// <summary> /// Return true if the type contains any tuples with element names. /// </summary> internal static bool ContainsTupleNames(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _1, bool _2) => !t.TupleElementNames.IsDefault, null) is object; /// <summary> /// Return true if the type contains any function pointer types. /// </summary> internal static bool ContainsFunctionPointer(this TypeSymbol type) => type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) is object; /// <summary> /// Guess the non-error type that the given type was intended to represent. /// If the type itself is not an error type, then it will be returned. /// Otherwise, the underlying type (if any) of the error type will be /// returned. /// </summary> /// <remarks> /// Any non-null type symbol returned is guaranteed not to be an error type. /// /// It is possible to pass in a constructed type and received back an /// unconstructed type. This can occur when the type passed in was /// constructed from an error type - the underlying definition will be /// available, but there won't be a good way to "re-substitute" back up /// to the level of the specified type. /// </remarks> internal static TypeSymbol? GetNonErrorGuess(this TypeSymbol type) { var result = ExtendedErrorTypeSymbol.ExtractNonErrorType(type); RoslynDebug.Assert((object?)result == null || !result.IsErrorType()); return result; } /// <summary> /// Guess the non-error type kind that the given type was intended to represent, /// if possible. If not, return TypeKind.Error. /// </summary> internal static TypeKind GetNonErrorTypeKindGuess(this TypeSymbol type) { return ExtendedErrorTypeSymbol.ExtractNonErrorTypeKind(type); } /// <summary> /// Returns true if the type was a valid switch expression type in C# 6. We use this test to determine /// whether or not we should attempt a user-defined conversion from the type to a C# 6 switch governing /// type, which we support for compatibility with C# 6 and earlier. /// </summary> internal static bool IsValidV6SwitchGoverningType(this TypeSymbol type, bool isTargetTypeOfUserDefinedOp = false) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types RoslynDebug.Assert((object)type != null); if (type.IsNullableType()) { type = type.GetNullableUnderlyingType(); } // User-defined implicit conversion with target type as Enum type is not valid. if (!isTargetTypeOfUserDefinedOp) { type = type.EnumUnderlyingTypeOrSelf(); } switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Char: case SpecialType.System_String: return true; case SpecialType.System_Boolean: // User-defined implicit conversion with target type as bool type is not valid. return !isTargetTypeOfUserDefinedOp; } return false; } #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <summary> /// Returns true if the type is one of the restricted types, namely: <see cref="T:System.TypedReference"/>, /// <see cref="T:System.ArgIterator"/>, or <see cref="T:System.RuntimeArgumentHandle"/>. /// or a ref-like type. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix internal static bool IsRestrictedType(this TypeSymbol type, bool ignoreSpanLikeTypes = false) { // See Dev10 C# compiler, "type.cpp", bool Type::isSpecialByRefType() const RoslynDebug.Assert((object)type != null); switch (type.SpecialType) { case SpecialType.System_TypedReference: case SpecialType.System_ArgIterator: case SpecialType.System_RuntimeArgumentHandle: return true; } return ignoreSpanLikeTypes ? false : type.IsRefLikeType; } public static bool IsIntrinsicType(this TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: case SpecialType.System_Single: case SpecialType.System_Double: // NOTE: VB treats System.DateTime as an intrinsic, while C# does not. //case SpecialType.System_DateTime: case SpecialType.System_Decimal: return true; default: return false; } } public static bool IsPartial(this TypeSymbol type) { return type is SourceNamedTypeSymbol { IsPartial: true }; } public static bool IsPointerType(this TypeSymbol type) { return type is PointerTypeSymbol; } internal static int FixedBufferElementSizeInBytes(this TypeSymbol type) { return type.SpecialType.FixedBufferElementSizeInBytes(); } // check that its type is allowed for Volatile internal static bool IsValidVolatileFieldType(this TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Struct: return type.SpecialType.IsValidVolatileFieldType(); case TypeKind.Array: case TypeKind.Class: case TypeKind.Delegate: case TypeKind.Dynamic: case TypeKind.Error: case TypeKind.Interface: case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Enum: return ((NamedTypeSymbol)type).EnumUnderlyingType.SpecialType.IsValidVolatileFieldType(); case TypeKind.TypeParameter: return type.IsReferenceType; case TypeKind.Submission: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } return false; } /// <summary> /// Add this instance to the set of checked types. Returns true /// if this was added, false if the type was already in the set. /// </summary> public static bool MarkCheckedIfNecessary(this TypeSymbol type, ref HashSet<TypeSymbol> checkedTypes) { if (checkedTypes == null) { checkedTypes = new HashSet<TypeSymbol>(); } return checkedTypes.Add(type); } internal static bool IsUnsafe(this TypeSymbol type) { while (true) { switch (type.TypeKind) { case TypeKind.Pointer: case TypeKind.FunctionPointer: return true; case TypeKind.Array: type = ((ArrayTypeSymbol)type).ElementType; break; default: // NOTE: we could consider a generic type with unsafe type arguments to be unsafe, // but that's already an error, so there's no reason to report it. Also, this // matches Type::isUnsafe in Dev10. return false; } } } internal static bool IsVoidPointer(this TypeSymbol type) { return type is PointerTypeSymbol p && p.PointedAtType.IsVoidType(); } /// <summary> /// These special types are structs that contain fields of the same type /// (e.g. <see cref="System.Int32"/> contains an instance field of type <see cref="System.Int32"/>). /// </summary> internal static bool IsPrimitiveRecursiveStruct(this TypeSymbol t) { return t.SpecialType.IsPrimitiveRecursiveStruct(); } /// <summary> /// Compute a hash code for the constructed type. The return value will be /// non-zero so callers can used zero to represent an uninitialized value. /// </summary> internal static int ComputeHashCode(this NamedTypeSymbol type) { RoslynDebug.Assert(!type.Equals(type.OriginalDefinition, TypeCompareKind.AllIgnoreOptions) || wasConstructedForAnnotations(type)); if (wasConstructedForAnnotations(type)) { // A type that uses its own type parameters as type arguments was constructed only for the purpose of adding annotations. // In that case we'll use the hash from the definition. return type.OriginalDefinition.GetHashCode(); } int code = type.OriginalDefinition.GetHashCode(); code = Hash.Combine(type.ContainingType, code); // Unconstructed type may contain alpha-renamed type parameters while // may still be considered equal, we do not want to give different hashcode to such types. // // Example: // Having original type A<U>.B<V> we create two _unconstructed_ types // A<int>.B<V'> // A<int>.B<V"> // Note that V' and V" are type parameters substituted via alpha-renaming of original V // These are different objects, but represent the same "type parameter at index 1" // // In short - we are not interested in the type parameters of unconstructed types. if ((object)type.ConstructedFrom != (object)type) { foreach (var arg in type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { code = Hash.Combine(arg.Type, code); } } // 0 may be used by the caller to indicate the hashcode is not // initialized. If we computed 0 for the hashcode, tweak it. if (code == 0) { code++; } return code; static bool wasConstructedForAnnotations(NamedTypeSymbol type) { do { var typeArguments = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var typeParameters = type.OriginalDefinition.TypeParameters; for (int i = 0; i < typeArguments.Length; i++) { if (!typeParameters[i].Equals( typeArguments[i].Type.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } } type = type.ContainingType; } while (type is object && !type.IsDefinition); return true; } } /// <summary> /// If we are in a COM PIA with embedInteropTypes enabled we should turn properties and methods /// that have the type and return type of object, respectively, into type dynamic. If the requisite conditions /// are fulfilled, this method returns a dynamic type. If not, it returns the original type. /// </summary> /// <param name="type">A property type or method return type to be checked for dynamification.</param> /// <param name="containingType">Containing type.</param> /// <returns></returns> public static TypeSymbol AsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType) { return type.TryAsDynamicIfNoPia(containingType, out TypeSymbol? result) ? result : type; } public static bool TryAsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType, [NotNullWhen(true)] out TypeSymbol? result) { if (type.SpecialType == SpecialType.System_Object) { AssemblySymbol assembly = containingType.ContainingAssembly; if ((object)assembly != null && assembly.IsLinked && containingType.IsComImport) { result = DynamicTypeSymbol.Instance; return true; } } result = null; return false; } /// <summary> /// Type variables are never considered reference types by the verifier. /// </summary> internal static bool IsVerifierReference(this TypeSymbol type) { return type.IsReferenceType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Type variables are never considered value types by the verifier. /// </summary> internal static bool IsVerifierValue(this TypeSymbol type) { return type.IsValueType && type.TypeKind != TypeKind.TypeParameter; } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this NamedTypeSymbol type) { // Avoid allocating a builder in the common case. if ((object)type.ContainingType == null) { return type.TypeParameters; } var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(builder); return builder.ToImmutableAndFree(); } /// <summary> /// Return all of the type parameters in this type and enclosing types, /// from outer-most to inner-most type. /// </summary> internal static void GetAllTypeParameters(this NamedTypeSymbol type, ArrayBuilder<TypeParameterSymbol> result) { var containingType = type.ContainingType; if ((object)containingType != null) { containingType.GetAllTypeParameters(result); } result.AddRange(type.TypeParameters); } /// <summary> /// Return the nearest type parameter with the given name in /// this type or any enclosing type. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this NamedTypeSymbol type, string name) { var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); type.GetAllTypeParameters(allTypeParameters); TypeParameterSymbol? result = null; foreach (TypeParameterSymbol tpEnclosing in allTypeParameters) { if (name == tpEnclosing.Name) { result = tpEnclosing; break; } } allTypeParameters.Free(); return result; } /// <summary> /// Return the nearest type parameter with the given name in /// this symbol or any enclosing symbol. /// </summary> internal static TypeParameterSymbol? FindEnclosingTypeParameter(this Symbol methodOrType, string name) { while (methodOrType != null) { switch (methodOrType.Kind) { case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: break; default: return null; } foreach (var typeParameter in methodOrType.GetMemberTypeParameters()) { if (typeParameter.Name == name) { return typeParameter; } } methodOrType = methodOrType.ContainingSymbol; } return null; } /// <summary> /// Return true if the fully qualified name of the type's containing symbol /// matches the given name. This method avoids string concatenations /// in the common case where the type is a top-level type. /// </summary> internal static bool HasNameQualifier(this NamedTypeSymbol type, string qualifiedName) { const StringComparison comparison = StringComparison.Ordinal; var container = type.ContainingSymbol; if (container.Kind != SymbolKind.Namespace) { // Nested type. For simplicity, compare qualified name to SymbolDisplay result. return string.Equals(container.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), qualifiedName, comparison); } var @namespace = (NamespaceSymbol)container; if (@namespace.IsGlobalNamespace) { return qualifiedName.Length == 0; } return HasNamespaceName(@namespace, qualifiedName, comparison, length: qualifiedName.Length); } private static bool HasNamespaceName(NamespaceSymbol @namespace, string namespaceName, StringComparison comparison, int length) { if (length == 0) { return false; } var container = @namespace.ContainingNamespace; int separator = namespaceName.LastIndexOf('.', length - 1, length); int offset = 0; if (separator >= 0) { if (container.IsGlobalNamespace) { return false; } if (!HasNamespaceName(container, namespaceName, comparison, length: separator)) { return false; } int n = separator + 1; offset = n; length -= n; } else if (!container.IsGlobalNamespace) { return false; } var name = @namespace.Name; return (name.Length == length) && (string.Compare(name, 0, namespaceName, offset, length, comparison) == 0); } internal static bool IsNonGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { var namedType = type as NamedTypeSymbol; if (namedType is null || namedType.Arity != 0) { return false; } if ((object)namedType == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)) { return true; } if (namedType.IsVoidType()) { return false; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsGenericTaskType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } if ((object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) { return true; } return namedType.IsCustomTaskType(builderArgument: out _); } internal static bool IsIAsyncEnumerableType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T); } internal static bool IsIAsyncEnumeratorType(this TypeSymbol type, CSharpCompilation compilation) { if (!(type is NamedTypeSymbol { Arity: 1 } namedType)) { return false; } return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T); } /// <summary> /// Returns true if the type is generic or non-generic custom task-like type due to the /// [AsyncMethodBuilder(typeof(B))] attribute. It returns the "B". /// </summary> /// <remarks> /// For the Task types themselves, this method might return true or false depending on mscorlib. /// The definition of "custom task-like type" is one that has an [AsyncMethodBuilder(typeof(B))] attribute, /// no more, no less. Validation of builder type B is left for elsewhere. This method returns B /// without validation of any kind. /// </remarks> internal static bool IsCustomTaskType(this NamedTypeSymbol type, [NotNullWhen(true)] out object? builderArgument) { RoslynDebug.Assert((object)type != null); var arity = type.Arity; if (arity < 2) { return type.HasAsyncMethodBuilderAttribute(out builderArgument); } builderArgument = null; return false; } /// <summary> /// Replace Task-like types with Task types. /// </summary> internal static TypeSymbol NormalizeTaskTypes(this TypeSymbol type, CSharpCompilation compilation) { NormalizeTaskTypesInType(compilation, ref type); return type; } /// <summary> /// Replace Task-like types with Task types. Returns true if there were changes. /// </summary> private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeSymbol type) { switch (type.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: { var namedType = (NamedTypeSymbol)type; var changed = NormalizeTaskTypesInNamedType(compilation, ref namedType); type = namedType; return changed; } case SymbolKind.ArrayType: { var arrayType = (ArrayTypeSymbol)type; var changed = NormalizeTaskTypesInArray(compilation, ref arrayType); type = arrayType; return changed; } case SymbolKind.PointerType: { var pointerType = (PointerTypeSymbol)type; var changed = NormalizeTaskTypesInPointer(compilation, ref pointerType); type = pointerType; return changed; } case SymbolKind.FunctionPointerType: { var functionPointerType = (FunctionPointerTypeSymbol)type; var changed = NormalizeTaskTypesInFunctionPointer(compilation, ref functionPointerType); type = functionPointerType; return changed; } } return false; } private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; if (NormalizeTaskTypesInType(compilation, ref type)) { typeWithAnnotations = TypeWithAnnotations.Create(type, customModifiers: typeWithAnnotations.CustomModifiers); return true; } return false; } private static bool NormalizeTaskTypesInNamedType(CSharpCompilation compilation, ref NamedTypeSymbol type) { bool hasChanged = false; if (!type.IsDefinition) { RoslynDebug.Assert(type.IsGenericType); var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; type.GetAllTypeArguments(typeArgumentsBuilder, ref discardedUseSiteInfo); for (int i = 0; i < typeArgumentsBuilder.Count; i++) { var typeWithModifier = typeArgumentsBuilder[i]; var typeArgNormalized = typeWithModifier.Type; if (NormalizeTaskTypesInType(compilation, ref typeArgNormalized)) { hasChanged = true; // Preserve custom modifiers but without normalizing those types. typeArgumentsBuilder[i] = TypeWithAnnotations.Create(typeArgNormalized, customModifiers: typeWithModifier.CustomModifiers); } } if (hasChanged) { var originalType = type; var originalDefinition = originalType.OriginalDefinition; var typeParameters = originalDefinition.GetAllTypeParameters(); var typeMap = new TypeMap(typeParameters, typeArgumentsBuilder.ToImmutable(), allowAlpha: true); type = typeMap.SubstituteNamedType(originalDefinition).WithTupleDataFrom(originalType); } typeArgumentsBuilder.Free(); } if (type.OriginalDefinition.IsCustomTaskType(builderArgument: out _)) { int arity = type.Arity; RoslynDebug.Assert(arity < 2); var taskType = compilation.GetWellKnownType( arity == 0 ? WellKnownType.System_Threading_Tasks_Task : WellKnownType.System_Threading_Tasks_Task_T); if (taskType.TypeKind == TypeKind.Error) { // Skip if Task types are not available. return false; } type = arity == 0 ? taskType : taskType.Construct( ImmutableArray.Create(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]), unbound: false); hasChanged = true; } return hasChanged; } private static bool NormalizeTaskTypesInArray(CSharpCompilation compilation, ref ArrayTypeSymbol arrayType) { var elementType = arrayType.ElementTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref elementType)) { return false; } arrayType = arrayType.WithElementType(elementType); return true; } private static bool NormalizeTaskTypesInPointer(CSharpCompilation compilation, ref PointerTypeSymbol pointerType) { var pointedAtType = pointerType.PointedAtTypeWithAnnotations; if (!NormalizeTaskTypesInType(compilation, ref pointedAtType)) { return false; } // Preserve custom modifiers but without normalizing those types. pointerType = new PointerTypeSymbol(pointedAtType); return true; } private static bool NormalizeTaskTypesInFunctionPointer(CSharpCompilation compilation, ref FunctionPointerTypeSymbol funcPtrType) { var returnType = funcPtrType.Signature.ReturnTypeWithAnnotations; var madeChanges = NormalizeTaskTypesInType(compilation, ref returnType); var paramTypes = ImmutableArray<TypeWithAnnotations>.Empty; if (funcPtrType.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(funcPtrType.Signature.ParameterCount); bool madeParamChanges = false; foreach (var param in funcPtrType.Signature.Parameters) { var paramType = param.TypeWithAnnotations; madeParamChanges |= NormalizeTaskTypesInType(compilation, ref paramType); paramsBuilder.Add(paramType); } if (madeParamChanges) { madeChanges = true; paramTypes = paramsBuilder.ToImmutableAndFree(); } else { paramTypes = funcPtrType.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } if (madeChanges) { funcPtrType = funcPtrType.SubstituteTypeSymbol(returnType, paramTypes, refCustomModifiers: default, paramRefCustomModifiers: default); return true; } else { return false; } } internal static Cci.TypeReferenceWithAttributes GetTypeRefWithAttributes( this TypeWithAnnotations type, Emit.PEModuleBuilder moduleBuilder, Symbol declaringSymbol, Cci.ITypeReference typeRef) { var builder = ArrayBuilder<Cci.ICustomAttribute>.GetInstance(); var compilation = declaringSymbol.DeclaringCompilation; if (compilation != null) { if (type.Type.ContainsTupleNames()) { addIfNotNull(builder, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (type.Type.ContainsNativeInteger()) { addIfNotNull(builder, moduleBuilder.SynthesizeNativeIntegerAttribute(declaringSymbol, type.Type)); } if (compilation.ShouldEmitNullableAttributes(declaringSymbol)) { addIfNotNull(builder, moduleBuilder.SynthesizeNullableAttributeIfNecessary(declaringSymbol, declaringSymbol.GetNullableContextValue(), type)); } static void addIfNotNull(ArrayBuilder<Cci.ICustomAttribute> builder, SynthesizedAttributeData? attr) { if (attr != null) { builder.Add(attr); } } } return new Cci.TypeReferenceWithAttributes(typeRef, builder.ToImmutableAndFree()); } internal static bool IsWellKnownTypeInAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("InAttribute"); internal static bool IsWellKnownTypeUnmanagedType(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("UnmanagedType"); internal static bool IsWellKnownTypeIsExternalInit(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownCompilerServicesTopLevelType("IsExternalInit"); internal static bool IsWellKnownTypeOutAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("OutAttribute"); private static bool IsWellKnownInteropServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name || typeSymbol.ContainingType is object) { return false; } return IsContainedInNamespace(typeSymbol, "System", "Runtime", "InteropServices"); } private static bool IsWellKnownCompilerServicesTopLevelType(this TypeSymbol typeSymbol, string name) { if (typeSymbol.Name != name) { return false; } return IsCompilerServicesTopLevelType(typeSymbol); } internal static bool IsCompilerServicesTopLevelType(this TypeSymbol typeSymbol) => typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Runtime", "CompilerServices"); private static bool IsContainedInNamespace(this TypeSymbol typeSymbol, string outerNS, string midNS, string innerNS) { var innerNamespace = typeSymbol.ContainingNamespace; if (innerNamespace?.Name != innerNS) { return false; } var midNamespace = innerNamespace.ContainingNamespace; if (midNamespace?.Name != midNS) { return false; } var outerNamespace = midNamespace.ContainingNamespace; if (outerNamespace?.Name != outerNS) { return false; } var globalNamespace = outerNamespace.ContainingNamespace; return globalNamespace != null && globalNamespace.IsGlobalNamespace; } internal static int TypeToIndex(this TypeSymbol type) { switch (type.GetSpecialTypeSafe()) { case SpecialType.System_Object: return 0; case SpecialType.System_String: return 1; case SpecialType.System_Boolean: return 2; case SpecialType.System_Char: return 3; case SpecialType.System_SByte: return 4; case SpecialType.System_Int16: return 5; case SpecialType.System_Int32: return 6; case SpecialType.System_Int64: return 7; case SpecialType.System_Byte: return 8; case SpecialType.System_UInt16: return 9; case SpecialType.System_UInt32: return 10; case SpecialType.System_UInt64: return 11; case SpecialType.System_IntPtr when type.IsNativeIntegerType: return 12; case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return 13; case SpecialType.System_Single: return 14; case SpecialType.System_Double: return 15; case SpecialType.System_Decimal: return 16; case SpecialType.None: if ((object)type != null && type.IsNullableType()) { TypeSymbol underlyingType = type.GetNullableUnderlyingType(); switch (underlyingType.GetSpecialTypeSafe()) { case SpecialType.System_Boolean: return 17; case SpecialType.System_Char: return 18; case SpecialType.System_SByte: return 19; case SpecialType.System_Int16: return 20; case SpecialType.System_Int32: return 21; case SpecialType.System_Int64: return 22; case SpecialType.System_Byte: return 23; case SpecialType.System_UInt16: return 24; case SpecialType.System_UInt32: return 25; case SpecialType.System_UInt64: return 26; case SpecialType.System_IntPtr when underlyingType.IsNativeIntegerType: return 27; case SpecialType.System_UIntPtr when underlyingType.IsNativeIntegerType: return 28; case SpecialType.System_Single: return 29; case SpecialType.System_Double: return 30; case SpecialType.System_Decimal: return 31; } } // fall through goto default; default: return -1; } } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Semantic/Semantics/DelegateTypeTests.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegateTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,20): warning CS8974: Converting method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20)); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; System.Linq.Expressions.LambdaExpression l = F; l = (System.Linq.Expressions.LambdaExpression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0030: Cannot convert type 'method' to 'LambdaExpression' // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression e = () => 1; Report(e); e = (LambdaExpression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 30), // (9,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // e = (LambdaExpression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 32)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); LambdaExpression l = x => x; l = (LambdaExpression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26), // (11,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(11, 30), // (12,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(12, 32)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26), // (11,30): error CS8917: The delegate type could not be inferred. // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 30), // (12,32): error CS8917: The delegate type could not be inferred. // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(12, 32)); } [Fact] public void LambdaConversions_06() { var sourceA = @"namespace System.Linq.Expressions { public class LambdaExpression<T> { } }"; var sourceB = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression<Func<int>> l = () => 1; l = (LambdaExpression<Func<int>>)(() => 2); } }"; var expectedDiagnostics = new[] { // (7,41): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // LambdaExpression<Func<int>> l = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(7, 41), // (8,43): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // l = (LambdaExpression<Func<int>>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(8, 43) }; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaConversions_07() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void AnonymousMethod_02() { var source = @"using System.Linq.Expressions; class Program { static void Main() { System.Linq.Expressions.Expression e = delegate () { return 1; }; e = (Expression)delegate () { return 2; }; LambdaExpression l = delegate () { return 3; }; l = (LambdaExpression)delegate () { return 4; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,48): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 1; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(6, 48), // (7,25): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 2; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,30): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 3; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 30), // (9,31): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 4; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 31)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,48): error CS1946: An anonymous method expression cannot be converted to an expression tree // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 1; }").WithLocation(6, 48), // (7,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(Expression)delegate () { return 2; }").WithLocation(7, 13), // (8,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 3; }").WithLocation(8, 30), // (9,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(LambdaExpression)delegate () { return 4; }").WithLocation(9, 13)); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); // Distinct names for distinct signatures with > 16 parameters: https://github.com/dotnet/roslyn/issues/55570 yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, ref int _17) => { }", "<>A{100000000}<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, System.Int32>"); yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, in int _17) => { }", "<>A{300000000}<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, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_01() { var source = @"class Program { static object GetValue() => 0; static void Main() { object x = GetValue; x = GetValue; x = (object)GetValue; #pragma warning disable 8974 object y = GetValue; y = GetValue; y = (object)GetValue; #pragma warning restore 8974 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13), // (8,13): error CS0030: Cannot convert type 'method' to 'object' // x = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(8, 13), // (10,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(10, 20), // (11,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(11, 13), // (12,13): error CS0030: Cannot convert type 'method' to 'object' // y = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (6,20): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_02() { var source = @"class Program { static int F() => 0; static object F1() => F; static object F2() => (object)F; static object F3() { return F; } static object F4() { return (object)F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (5,27): error CS0030: Cannot convert type 'method' to 'object' // static object F2() => (object)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(5, 27), // (6,33): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33), // (7,33): error CS0030: Cannot convert type 'method' to 'object' // static object F4() { return (object)F; } Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(7, 33)); var expectedDiagnostics = new[] { // (4,27): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (6,33): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_03() { var source = @"class Program { static int F() => 0; static void Main() { object[] a = new[] { F, (object)F, F }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,33): error CS0030: Cannot convert type 'method' to 'object' // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(6, 33), // (6,44): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44)); var expectedDiagnostics = new[] { // (6,30): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,44): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } /// <summary> /// System.Linq.Expressions as a type rather than a namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsType() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace System.Linq { public class Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } } }"; var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e1 = () => 1; System.Linq.Expressions.LambdaExpression e2 = () => 2; System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,49): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression' because it is not a delegate type // System.Linq.Expressions.Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 49), // (6,55): error CS1660: Cannot convert lambda expression to type 'Expressions.LambdaExpression' because it is not a delegate type // System.Linq.Expressions.LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(6, 55), // (7,67): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression<Func<int>>' because it is not a delegate type // System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(7, 67)); } /// <summary> /// System.Linq.Expressions as a nested namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsNestedNamespace() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace Root.System.Linq.Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } }"; var sourceB = @"using System; using Root.System.Linq.Expressions; class Program { static void Main() { Expression e1 = () => 1; LambdaExpression e2 = () => 2; Expression<Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (7,25): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,31): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "Root.System.Linq.Expressions.LambdaExpression").WithLocation(8, 31), // (9,36): error CS1660: Cannot convert lambda expression to type 'Expression<Func<int>>' because it is not a delegate type // Expression<Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(9, 36)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = "M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): 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 // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) { Console.WriteLine(""AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback)""); return app; } } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) { Console.WriteLine(""RouteBuilderExtensions.Map(this IRouteBuilder routes, string path, Delegate callback)""); return routes; } } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; var expectedOutput = @"AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { Console.WriteLine(""F(object obj, Action a)""); } static void F(int i, Delegate d) { Console.WriteLine(""F(int i, Delegate d)""); } }"; var expectedOutput = @"F(object obj, Action a) F(object obj, Action a) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { Console.WriteLine(""F(Expression<Func<object>> f, object obj)""); } static void F(Expression e, int i) { Console.WriteLine(""F(Expression e, int i)""); } }"; var expectedOutput = @"F(Expression<Func<object>> f, object obj)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"using System; delegate void StringAction(string arg); class Program { static void F<T>(T t) { Console.WriteLine(typeof(T).Name); } static void F(StringAction a) { Console.WriteLine(""StringAction""); } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var expectedOutput = @"StringAction StringAction "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var expectedDiagnostics = new[] { // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_25() { var source = @"using static System.Console; delegate void D(); class Program { static void F(D d) => WriteLine(""D""); static void F<T>(T t) => WriteLine(typeof(T).Name); static void Main() { F(() => { }); } }"; string expectedOutput = "D"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_26() { var source = @"using System; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F<T>(T t) => Console.WriteLine(typeof(T).Name); static void Main() { int i = 0; F(() => i++); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_27() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F(Expression expression) => Console.WriteLine(""Expression""); static int GetValue() => 0; static void Main() { F(() => GetValue()); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56319, "https://github.com/dotnet/roslyn/issues/56319")] [Fact] public void OverloadResolution_28() { var source = @"using System; var source = new C<int>(); source.Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i); class C<T> { } static class Extensions { public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, Func<TAccumulate> seedFactory, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } }"; string expectedOutput = "(System.Int32, System.Int32, System.Int32)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_29() { var source = @"using System; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Func<object> x, Func<object> y) { Console.WriteLine(""M(Func<object> x, Func<object> y)""); } static void Main() { Func<object> fo = () => new A(); Func<A> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Func<object> x, Func<object> y) M(Func<object> x, Func<object> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_30() { var source = @"using System; class Program { static void M<T>(T t, Func<object> f) { Console.WriteLine(""M<T>(T t, Func<object> f)""); } static void M<T>(Func<object> f, T t) { Console.WriteLine(""M<T>(Func<object> f, T t)""); } static object F() => null; static void Main() { M(F, F); M(() => 1, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(F, F); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(10, 9)); var expectedDiagnostics = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(F, F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_31() { var source = @"using System; using System.Linq.Expressions; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Expression<Func<object>> e) { Console.WriteLine(""M(Expression<Func<object>> e)""); } static void Main() { M(() => string.Empty); } }"; var expectedOutput = "M(Expression<Func<object>> e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_32() { var source = @"using System; using System.Linq.Expressions; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Expression<Func<object>> x, Expression<Func<object>> y) { Console.WriteLine(""M(Expression<Func<object>> x, Expression<Func<object>> y)""); } static void Main() { Expression<Func<object>> fo = () => new A(); Expression<Func<A>> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Expression<Func<object>> x, Expression<Func<object>> y) M(Expression<Func<object>> x, Expression<Func<object>> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_33() { var source = @"using System; class Program { static void M<T>(object x, T y) { Console.WriteLine(""M<T>(object x, T y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(9, 9), // (10,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(10, 11), // (11,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M<T, U>(T x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_34() { var source = @"using System; class Program { static void M<T, U>(Func<T> x, U y) { Console.WriteLine(""M<T, U>(Func<T> x, U y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(9, 9), // (11,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_35() { var source = @"using System; class Program { static void M(Delegate x, Func<int> y) { Console.WriteLine(""M(Delegate x, Func<int> y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(10, 11)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M(Delegate x, Func<int> y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_36() { var source = @"using System; class Program { static void F<T>(T t) { Console.WriteLine(""F<{0}>({0} t)"", typeof(T).Name); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "System.Delegate").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11)); var expectedOutput = @"F<Action>(Action t) F<Func`1>(Func`1 t)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_37() { var source = @"using System; class Program { static void F(object o) { Console.WriteLine(""F(object o)""); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "object").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(9, 11)); var expectedOutput = @"F(Delegate d) F(Delegate d)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_38() { var source = @"using System; class MyString { public static implicit operator MyString(string s) => new MyString(); } class Program { static void F(Delegate d1, Delegate d2, string s) { Console.WriteLine(""F(Delegate d1, Delegate d2, string s)""); } static void F(Func<int> f, Delegate d, MyString s) { Console.WriteLine(""F(Func<int> f, Delegate d, MyString s)""); } static void Main() { F(() => 1, () => 2, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 11), // (12,20): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 20)); var expectedDiagnostics = new[] { // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Delegate, Delegate, string)' and 'Program.F(Func<int>, Delegate, MyString)' // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Delegate, System.Delegate, string)", "Program.F(System.Func<int>, System.Delegate, MyString)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_39() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static int F() => 0; static void Main() { M(F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11)); var expectedDiagnostics = new[] { // (10,11): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(10, 11) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_40() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static void Main() { M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 11)); var expectedOutput = @"M(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_41() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(Delegate d) { Console.WriteLine(""M(Delegate d)""); } static int F() => 0; static void Main() { M(F); M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11), // (11,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 11)); var expectedDiagnostics = new[] { // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(() => 1); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(11, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_42() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""96A2DE64-6D44-4DA5-BBA4-25F5F07E0E6B"")] interface I { void F(Delegate d, short s); void F(Action a, ref int i); } class C : I { void I.F(Delegate d, short s) => Console.WriteLine(""I.F(Delegate d, short s)""); void I.F(Action a, ref int i) => Console.WriteLine(""I.F(Action a, ref int i)""); } class Program { static void M(I i) { i.F(() => { }, 1); } static void Main() { M(new C()); } }"; var expectedOutput = @"I.F(Action a, ref int i)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_43() { var source = @"using System; using System.Linq.Expressions; class Program { static int F() => 0; static void Main() { var c = new C(); c.M(F); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); var expectedDiagnostics = new[] { // (9,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // c.M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(9, 13) }; // Breaking change from C#9 which binds to E.M. var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_44() { var source = @"using System; using System.Linq.Expressions; class A { public static void F1(Func<int> f) { Console.WriteLine(""A.F1(Func<int> f)""); } public void F2(Func<int> f) { Console.WriteLine(""A.F2(Func<int> f)""); } } class B : A { public static void F1(Delegate d) { Console.WriteLine(""B.F1(Delegate d)""); } public void F2(Expression e) { Console.WriteLine(""B.F2(Expression e)""); } } class Program { static void Main() { B.F1(() => 1); var b = new B(); b.F2(() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.F1(Func<int> f) A.F2(Func<int> f)"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B.F1(Delegate d) B.F2(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_45() { var source = @"using System; using System.Linq.Expressions; class A { public object this[Func<int> f] => Report(""A.this[Func<int> f]""); public static object Report(string message) { Console.WriteLine(message); return null; } } class B1 : A { public object this[Delegate d] => Report(""B1.this[Delegate d]""); } class B2 : A { public object this[Expression e] => Report(""B2.this[Expression e]""); } class Program { static void Main() { var b1 = new B1(); _ = b1[() => 1]; var b2 = new B2(); _ = b2[() => 2]; } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.this[Func<int> f] A.this[Func<int> f]"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B1.this[Delegate d] B2.this[Expression e]"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_01() { var source = @"using System; class Program { static void Main() { Report(() => { return; }); Report((bool b) => { if (b) return; }); Report((bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action`1[System.Boolean] System.Action`1[System.Boolean] "); } [Fact] public void InferredReturnType_02() { var source = @"using System; class Program { static void Main() { Report(async () => { return; }); Report(async (bool b) => { if (b) return; }); Report(async (bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] "); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_03() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return null; }); Report((bool b) => { if (b) return; else return null; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return null; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return null; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_04() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return default; }); Report((bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return default; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return default; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [Fact] public void ExplicitReturnType_01() { var source = @"using System; class Program { static void Main() { Report(object () => { return; }); Report(object (bool b) => { if (b) return null; }); Report(object (bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,31): error CS0126: An object of a type convertible to 'object' is required // Report(object () => { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(6, 31), // (7,32): error CS1643: Not all code paths return a value in lambda expression of type 'Func<bool, object>' // Report(object (bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<bool, object>").WithLocation(7, 32), // (8,44): error CS0126: An object of a type convertible to 'object' is required // Report(object (bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(8, 44)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegateTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): 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 // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void Variance() { var source = @"using System; delegate void StringAction(string s); class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(9, 29), // (9,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(9, 37)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator_01() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); var expectedOutput = @"(False, False, False)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_02() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Expression e) { Console.WriteLine(""operator=(C c, Expression e)""); return c; } static void Main() { var c = new C(); _ = c + Main; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (10,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_03() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_04() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13), // (12,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_05() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_06() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static void Main() { var c = new C(); _ = c + (() => new object()); _ = c + (() => 1); } }"; var expectedOutput = @"operator+(C c, Func<object> f) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_07() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_08() { var source = @"using System; class A { public static A operator+(A a, Func<int> f) { Console.WriteLine(""operator+(A a, Func<int> f)""); return a; } } class B : A { public static B operator+(B b, Delegate d) { Console.WriteLine(""operator+(B b, Delegate d)""); return b; } static int F() => 1; static void Main() { var b = new B(); _ = b + F; _ = b + (() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"operator+(A a, Func<int> f) operator+(A a, Func<int> f) "); // Breaking change from C#9. string expectedOutput = @"operator+(B b, Delegate d) operator+(B b, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_18() { var source = @"using System; class Program { static void Main() { Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { return 1; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, out int _17) => { _17 = 0; return 2; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, ref int _17) => { return 3; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, in int _17) => { return 4; }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>F`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{200000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{100000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{300000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_19() { var source = @"using System; class Program { static void F1(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18) { } static void F2(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, out object _18) { _18 = null; } static void F3(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, ref object _18) { } static void F4(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, in object _18) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{800000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{400000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{c00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_20() { var source = @"using System; class Program { static void F1( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, int _33) { } static void F2( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, out int _33) { _33 = 0; } static void F3( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, ref int _33) { } static void F4( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, in int _33) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{4000000000000000\,00000000}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000002}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000001}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000003}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_21() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { var d1 = F1; D2 d2 = F2; var d3 = (ref object x, out object y) => { y = null; }; D4 d4 = (out object x, ref object y) => { x = null; }; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; private static readonly string s_expressionOfTDelegate0ArgTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression0`1"; private static readonly string s_expressionOfTDelegate1ArgTypeName = ExecutionConditionUtil.IsDesktop ? "System.Linq.Expressions.Expression`1" : "System.Linq.Expressions.Expression1`1"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions_01() { var source = @"using System; class Program { static void Main() { object o = Main; ICloneable c = Main; Delegate d = Main; MulticastDelegate m = Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20), // (7,24): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // Delegate d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(8, 22), // (9,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(9, 31)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,20): warning CS8974: Converting method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 20)); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)Main; var c = (ICloneable)Main; var d = (Delegate)Main; var m = (MulticastDelegate)Main; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'method' to 'object' // var o = (object)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)Main").WithArguments("method", "object").WithLocation(6, 17), // (7,17): error CS0030: Cannot convert type 'method' to 'ICloneable' // var c = (ICloneable)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(ICloneable)Main").WithArguments("method", "System.ICloneable").WithLocation(7, 17), // (8,17): error CS0030: Cannot convert type 'method' to 'Delegate' // var d = (Delegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Delegate)Main").WithArguments("method", "System.Delegate").WithLocation(8, 17), // (9,17): error CS0030: Cannot convert type 'method' to 'MulticastDelegate' // var m = (MulticastDelegate)Main; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(MulticastDelegate)Main").WithArguments("method", "System.MulticastDelegate").WithLocation(9, 17)); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void MethodGroupConversions_03() { var source = @"class Program { static void Main() { System.Linq.Expressions.Expression e = F; e = (System.Linq.Expressions.Expression)F; System.Linq.Expressions.LambdaExpression l = F; l = (System.Linq.Expressions.LambdaExpression)F; } static int F() => 1; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0030: Cannot convert type 'method' to 'Expression' // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.Expression)F").WithArguments("method", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0030: Cannot convert type 'method' to 'LambdaExpression' // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,48): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // System.Linq.Expressions.Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (6,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // e = (System.Linq.Expressions.Expression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.Expression)F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(6, 13), // (7,54): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // System.Linq.Expressions.LambdaExpression l = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 54), // (8,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'LambdaExpression'. Did you intend to invoke the method? // l = (System.Linq.Expressions.LambdaExpression)F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "(System.Linq.Expressions.LambdaExpression)F").WithArguments("F", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 13)); } [Fact] public void MethodGroupConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F() { } static void F(object o) { } static void Main() { object o = F; ICloneable c = F; Delegate d = F; MulticastDelegate m = F; Expression e = F; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,20): error CS8917: The delegate type could not be inferred. // object o = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(9, 20), // (10,24): error CS8917: The delegate type could not be inferred. // ICloneable c = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(10, 24), // (11,22): error CS8917: The delegate type could not be inferred. // Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(11, 22), // (12,31): error CS8917: The delegate type could not be inferred. // MulticastDelegate m = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(12, 31), // (13,24): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // Expression e = F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(13, 24)); } [Fact] public void LambdaConversions_01() { var source = @"using System; class Program { static void Main() { object o = () => { }; ICloneable c = () => { }; Delegate d = () => { }; MulticastDelegate m = () => { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_02() { var source = @"using System; class Program { static void Main() { var o = (object)(() => { }); var c = (ICloneable)(() => { }); var d = (Delegate)(() => { }); var m = (MulticastDelegate)(() => { }); Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,26): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // var o = (object)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(6, 26), // (7,30): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // var c = (ICloneable)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(7, 30), // (8,28): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var d = (Delegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(8, 28), // (9,37): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // var m = (MulticastDelegate)(() => { }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(9, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void LambdaConversions_03() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression e = () => 1; Report(e); e = (Expression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(7, 24), // (9,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 26)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression e = () => 1; Report(e); e = (LambdaExpression)(() => 2); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(7, 30), // (9,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // e = (LambdaExpression)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 32)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"{s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void LambdaConversions_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { Delegate d = x => x; object o = (object)(x => x); Expression e = x => x; e = (Expression)(x => x); LambdaExpression l = x => x; l = (LambdaExpression)(x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,22): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // Delegate d = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 22), // (8,29): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "object").WithLocation(8, 29), // (9,24): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 24), // (10,26): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(10, 26), // (11,30): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(11, 30), // (12,32): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(12, 32)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,22): error CS8917: The delegate type could not be inferred. // Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(7, 22), // (8,29): error CS8917: The delegate type could not be inferred. // object o = (object)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 29), // (9,24): error CS8917: The delegate type could not be inferred. // Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 24), // (10,26): error CS8917: The delegate type could not be inferred. // e = (Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(10, 26), // (11,30): error CS8917: The delegate type could not be inferred. // LambdaExpression l = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 30), // (12,32): error CS8917: The delegate type could not be inferred. // l = (LambdaExpression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(12, 32)); } [Fact] public void LambdaConversions_06() { var sourceA = @"namespace System.Linq.Expressions { public class LambdaExpression<T> { } }"; var sourceB = @"using System; using System.Linq.Expressions; class Program { static void Main() { LambdaExpression<Func<int>> l = () => 1; l = (LambdaExpression<Func<int>>)(() => 2); } }"; var expectedDiagnostics = new[] { // (7,41): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // LambdaExpression<Func<int>> l = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(7, 41), // (8,43): error CS1660: Cannot convert lambda expression to type 'LambdaExpression<Func<int>>' because it is not a delegate type // l = (LambdaExpression<Func<int>>)(() => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression<System.Func<int>>").WithLocation(8, 43) }; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaConversions_07() { var source = @"using System; class Program { static void Main() { System.Delegate d = () => Main; System.Linq.Expressions.Expression e = () => Main; Report(d); Report(e); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Action] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Action]] "); } [Fact] public void AnonymousMethod_01() { var source = @"using System; class Program { static void Main() { object o = delegate () { }; ICloneable c = delegate () { }; Delegate d = delegate () { }; MulticastDelegate m = delegate () { }; Report(o); Report(c); Report(d); Report(m); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS1660: Cannot convert anonymous method to type 'object' because it is not a delegate type // object o = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "object").WithLocation(6, 20), // (7,24): error CS1660: Cannot convert anonymous method to type 'ICloneable' because it is not a delegate type // ICloneable c = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.ICloneable").WithLocation(7, 24), // (8,22): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // Delegate d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 22), // (9,31): error CS1660: Cannot convert anonymous method to type 'MulticastDelegate' because it is not a delegate type // MulticastDelegate m = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.MulticastDelegate").WithLocation(9, 31)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action System.Action System.Action "); } [Fact] public void AnonymousMethod_02() { var source = @"using System.Linq.Expressions; class Program { static void Main() { System.Linq.Expressions.Expression e = delegate () { return 1; }; e = (Expression)delegate () { return 2; }; LambdaExpression l = delegate () { return 3; }; l = (LambdaExpression)delegate () { return 4; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,48): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 1; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(6, 48), // (7,25): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 2; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,30): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 3; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(8, 30), // (9,31): error CS1660: Cannot convert anonymous method to type 'LambdaExpression' because it is not a delegate type // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 4; }").WithArguments("anonymous method", "System.Linq.Expressions.LambdaExpression").WithLocation(9, 31)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,48): error CS1946: An anonymous method expression cannot be converted to an expression tree // System.Linq.Expressions.Expression e = delegate () { return 1; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 1; }").WithLocation(6, 48), // (7,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // e = (Expression)delegate () { return 2; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(Expression)delegate () { return 2; }").WithLocation(7, 13), // (8,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // LambdaExpression l = delegate () { return 3; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 3; }").WithLocation(8, 30), // (9,13): error CS1946: An anonymous method expression cannot be converted to an expression tree // l = (LambdaExpression)delegate () { return 4; }; Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "(LambdaExpression)delegate () { return 4; }").WithLocation(9, 13)); } [Fact] public void DynamicConversion() { var source = @"using System; class Program { static void Main() { dynamic d; d = Main; d = () => 1; } static void Report(dynamic d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'dynamic'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "dynamic").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert lambda expression to type 'dynamic' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "dynamic").WithLocation(8, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", "System.Func<System.Action<System.String[]>>"); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); // Distinct names for distinct signatures with > 16 parameters: https://github.com/dotnet/roslyn/issues/55570 yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, ref int _17) => { }", "<>A{100000000}<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, System.Int32>"); yield return getData("(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, in int _17) => { }", "<>A{300000000}<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, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); if (typeInfo.Type is { }) { Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } } private static bool HaveMatchingSignatures(IMethodSymbol methodA, IMethodSymbol methodB) { return MemberSignatureComparer.MethodGroupSignatureComparer.Equals(methodA.GetSymbol<MethodSymbol>(), methodB.GetSymbol<MethodSymbol>()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (5,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(5, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>", new[] { // (6,34): error CS0123: No overload for 'F' matches delegate 'Action' // System.Delegate d = this.F<int>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F<int>").WithArguments("F", "System.Action").WithLocation(6, 34) }); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_01() { var source = @"class Program { static object GetValue() => 0; static void Main() { object x = GetValue; x = GetValue; x = (object)GetValue; #pragma warning disable 8974 object y = GetValue; y = GetValue; y = (object)GetValue; #pragma warning restore 8974 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13), // (8,13): error CS0030: Cannot convert type 'method' to 'object' // x = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(8, 13), // (10,20): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(10, 20), // (11,13): error CS0428: Cannot convert method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // y = GetValue; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(11, 13), // (12,13): error CS0030: Cannot convert type 'method' to 'object' // y = (object)GetValue; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)GetValue").WithArguments("method", "object").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (6,20): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // object x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(6, 20), // (7,13): warning CS8974: Converting method group 'GetValue' to non-delegate type 'object'. Did you intend to invoke the method? // x = GetValue; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "GetValue").WithArguments("GetValue", "object").WithLocation(7, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_02() { var source = @"class Program { static int F() => 0; static object F1() => F; static object F2() => (object)F; static object F3() { return F; } static object F4() { return (object)F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (5,27): error CS0030: Cannot convert type 'method' to 'object' // static object F2() => (object)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(5, 27), // (6,33): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33), // (7,33): error CS0030: Cannot convert type 'method' to 'object' // static object F4() { return (object)F; } Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(7, 33)); var expectedDiagnostics = new[] { // (4,27): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F1() => F; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(4, 27), // (6,33): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // static object F3() { return F; } Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 33) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(55923, "https://github.com/dotnet/roslyn/issues/55923")] [Fact] public void ConvertMethodGroupToObject_03() { var source = @"class Program { static int F() => 0; static void Main() { object[] a = new[] { F, (object)F, F }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,33): error CS0030: Cannot convert type 'method' to 'object' // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)F").WithArguments("method", "object").WithLocation(6, 33), // (6,44): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44)); var expectedDiagnostics = new[] { // (6,30): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 30), // (6,44): warning CS8974: Converting method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // object[] a = new[] { F, (object)F, F }; Diagnostic(ErrorCode.WRN_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(6, 44) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } [Fact] public void Member_01() { var source = @"using System; class Program { static void Main() { Console.WriteLine((() => { }).GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // Console.WriteLine((() => { }).GetType()); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(() => { }).GetType").WithArguments(".", "lambda expression").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void Member_02() { var source = @"using System; class Program { static void Main() { Console.WriteLine(Main.GetType()); } }"; var expectedDiagnostics = new[] { // (6,27): error CS0119: 'Program.Main()' is a method, which is not valid in the given context // Console.WriteLine(Main.GetType()); Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(6, 27) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(expectedDiagnostics); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS0570: 'A.F1(object)' is not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F1").WithArguments("A.F1(object)").WithLocation(10, 16), // (10,16): error CS0648: '' is a type not supported by the language // Report(A.F1); Diagnostic(ErrorCode.ERR_BogusType, "A.F1").WithArguments("").WithLocation(10, 16), // (11,16): error CS0570: 'A.F2()' is not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BindToBogus, "A.F2").WithArguments("A.F2()").WithLocation(11, 16), // (11,16): error CS0648: '' is a type not supported by the language // Report(A.F2); Diagnostic(ErrorCode.ERR_BogusType, "A.F2").WithArguments("").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48), // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } // Expression<T> not derived from Expression. private static MetadataReference GetCorlibWithExpressionOfTNotDerivedType() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_01() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (5,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_NotDerivedType_02() { var refA = GetCorlibWithExpressionOfTNotDerivedType(); var sourceB = @"class Program { static T F<T>(T t) where T : System.Linq.Expressions.Expression => t; static void Main() { var e = F(() => 1); } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }); comp.VerifyDiagnostics( // (6,17): error CS0311: The type 'System.Linq.Expressions.Expression<System.Func<int>>' cannot be used as type parameter 'T' in the generic type or method 'Program.F<T>(T)'. There is no implicit reference conversion from 'System.Linq.Expressions.Expression<System.Func<int>>' to 'System.Linq.Expressions.Expression'. // var e = F(() => 1); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("Program.F<T>(T)", "System.Linq.Expressions.Expression", "T", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(6, 17)); } /// <summary> /// System.Linq.Expressions as a type rather than a namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsType() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace System.Linq { public class Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } } }"; var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e1 = () => 1; System.Linq.Expressions.LambdaExpression e2 = () => 2; System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,49): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression' because it is not a delegate type // System.Linq.Expressions.Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(5, 49), // (6,55): error CS1660: Cannot convert lambda expression to type 'Expressions.LambdaExpression' because it is not a delegate type // System.Linq.Expressions.LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.LambdaExpression").WithLocation(6, 55), // (7,67): error CS1660: Cannot convert lambda expression to type 'Expressions.Expression<Func<int>>' because it is not a delegate type // System.Linq.Expressions.Expression<System.Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(7, 67)); } /// <summary> /// System.Linq.Expressions as a nested namespace. /// </summary> [Fact] public void SystemLinqExpressions_IsNestedNamespace() { var sourceA = @"namespace System { public class Object { } public abstract class ValueType { } public class String { } public class Type { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct IntPtr { } public abstract class Delegate { } public abstract class MulticastDelegate : Delegate { } public delegate T Func<T>(); } namespace Root.System.Linq.Expressions { public abstract class Expression { } public abstract class LambdaExpression : Expression { } public sealed class Expression<T> : LambdaExpression { } }"; var sourceB = @"using System; using Root.System.Linq.Expressions; class Program { static void Main() { Expression e1 = () => 1; LambdaExpression e2 = () => 2; Expression<Func<int>> e3 = () => 3; } }"; var comp = CreateEmptyCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (7,25): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // Expression e1 = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression").WithLocation(7, 25), // (8,31): error CS1660: Cannot convert lambda expression to type 'LambdaExpression' because it is not a delegate type // LambdaExpression e2 = () => 2; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "Root.System.Linq.Expressions.LambdaExpression").WithLocation(8, 31), // (9,36): error CS1660: Cannot convert lambda expression to type 'Expression<Func<int>>' because it is not a delegate type // Expression<Func<int>> e3 = () => 3; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 3").WithArguments("lambda expression", "Root.System.Linq.Expressions.Expression<System.Func<int>>").WithLocation(9, 36)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = "M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M(object x, Action y) E.M(object x, Action y) "); // Breaking change from C#9 which binds to E.M(object x, Action y). CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"C.M(object y) C.M(object y) "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): 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 // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_12() { var source = @"using System; #nullable enable var app = new WebApp(); app.Map(""/sub1"", builder => { builder.UseAuth(); }); app.Map(""/sub2"", (IAppBuilder builder) => { builder.UseAuth(); }); class WebApp : IAppBuilder, IRouteBuilder { public void UseAuth() { } } interface IAppBuilder { void UseAuth(); } interface IRouteBuilder { } static class AppBuilderExtensions { public static IAppBuilder Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) { Console.WriteLine(""AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback)""); return app; } } static class RouteBuilderExtensions { public static IRouteBuilder Map(this IRouteBuilder routes, string path, Delegate callback) { Console.WriteLine(""RouteBuilderExtensions.Map(this IRouteBuilder routes, string path, Delegate callback)""); return routes; } } struct PathSring { public PathSring(string? path) { Path = path; } public string? Path { get; } public static implicit operator PathSring(string? s) => new PathSring(s); public static implicit operator string?(PathSring path) => path.Path; }"; var expectedOutput = @"AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) AppBuilderExtensions.Map(this IAppBuilder app, PathSring path, Action<IAppBuilder> callback) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_13() { var source = @"using System; class Program { static void Main() { F(1, () => { }); F(2, Main); } static void F(object obj, Action a) { Console.WriteLine(""F(object obj, Action a)""); } static void F(int i, Delegate d) { Console.WriteLine(""F(int i, Delegate d)""); } }"; var expectedOutput = @"F(object obj, Action a) F(object obj, Action a) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(55691, "https://github.com/dotnet/roslyn/issues/55691")] [Fact] public void OverloadResolution_14() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { F(() => 1, 2); } static void F(Expression<Func<object>> f, object obj) { Console.WriteLine(""F(Expression<Func<object>> f, object obj)""); } static void F(Expression e, int i) { Console.WriteLine(""F(Expression e, int i)""); } }"; var expectedOutput = @"F(Expression<Func<object>> f, object obj)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_15() { var source = @"using System; delegate void StringAction(string arg); class Program { static void F<T>(T t) { Console.WriteLine(typeof(T).Name); } static void F(StringAction a) { Console.WriteLine(""StringAction""); } static void M(string arg) { } static void Main() { F((string s) => { }); // C#9: F(StringAction) F(M); // C#9: F(StringAction) } }"; var expectedOutput = @"StringAction StringAction "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_16() { var source = @"using System; class Program { static void F(Func<Func<object>> f, int i) => Report(f); static void F(Func<Func<int>> f, object o) => Report(f); static void Main() { F(() => () => 1, 2); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"System.Func`1[System.Func`1[System.Object]]"); // Breaking change from C#9 which binds calls to F(Func<Func<object>>, int). var expectedDiagnostics = new[] { // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Func<Func<object>>, int)' and 'Program.F(Func<Func<int>>, object)' // F(() => () => 1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Func<System.Func<object>>, int)", "Program.F(System.Func<System.Func<int>>, object)").WithLocation(8, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_17() { var source = @"delegate void StringAction(string arg); class Program { static void F<T>(System.Action<T> a) { } static void F(StringAction a) { } static void Main() { F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F(StringAction)").WithLocation(8, 9)); } [Fact] public void OverloadResolution_18() { var source = @"delegate void StringAction(string arg); class Program { static void F0<T>(System.Action<T> a) { } static void F1<T>(System.Action<T> a) { } static void F1(StringAction a) { } static void M(string arg) { } static void Main() { F0(M); F1(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F0<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F0(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F0").WithArguments("Program.F0<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_19() { var source = @"delegate void MyAction<T>(T arg); class Program { static void F<T>(System.Action<T> a) { } static void F<T>(MyAction<T> a) { } static void M(string arg) { } static void Main() { F((string s) => { }); F(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F<T>(Action<T>)' and 'Program.F<T>(MyAction<T>)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F<T>(System.Action<T>)", "Program.F<T>(MyAction<T>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(M); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Action<T>)").WithLocation(10, 9)); } [Fact] public void OverloadResolution_20() { var source = @"using System; delegate void StringAction(string s); class Program { static void F(Action<string> a) { } static void F(StringAction a) { } static void M(string s) { } static void Main() { F(M); F((string s) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F(M); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Action<string>)' and 'Program.F(StringAction)' // F((string s) => { }); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Action<string>)", "Program.F(StringAction)").WithLocation(11, 9)); } [Fact] public void OverloadResolution_21() { var source = @"using System; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Delegate>(); c.F(() => (Action)null); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Delegate]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_22() { var source = @"using System; using System.Linq.Expressions; class C<T> { public void F(Delegate d) => Report(""F(Delegate d)"", d); public void F(T t) => Report(""F(T t)"", t); public void F(Func<T> f) => Report(""F(Func<T> f)"", f); static void Report(string method, object arg) => Console.WriteLine(""{0}, {1}"", method, arg.GetType()); } class Program { static void Main() { var c = new C<Expression>(); c.F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<T> f), System.Func`1[System.Linq.Expressions.Expression]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_23() { var source = @"using System; class Program { static void F(Delegate d) => Console.WriteLine(""F(Delegate d)""); static void F(Func<object> f) => Console.WriteLine(""F(Func<int> f)""); static void Main() { F(() => 1); } }"; string expectedOutput = "F(Func<int> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(1361172, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1361172")] [Fact] public void OverloadResolution_24() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) => Console.WriteLine(""F(Expression e)""); static void F(Func<Expression> f) => Console.WriteLine(""F(Func<Expression> f)""); static void Main() { F(() => Expression.Constant(1)); } }"; string expectedOutput = "F(Func<Expression> f)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_25() { var source = @"using static System.Console; delegate void D(); class Program { static void F(D d) => WriteLine(""D""); static void F<T>(T t) => WriteLine(typeof(T).Name); static void Main() { F(() => { }); } }"; string expectedOutput = "D"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_26() { var source = @"using System; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F<T>(T t) => Console.WriteLine(typeof(T).Name); static void Main() { int i = 0; F(() => i++); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56167, "https://github.com/dotnet/roslyn/issues/56167")] [Fact] public void OverloadResolution_27() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Action action) => Console.WriteLine(""Action""); static void F(Expression expression) => Console.WriteLine(""Expression""); static int GetValue() => 0; static void Main() { F(() => GetValue()); } }"; string expectedOutput = "Action"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(56319, "https://github.com/dotnet/roslyn/issues/56319")] [Fact] public void OverloadResolution_28() { var source = @"using System; var source = new C<int>(); source.Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i); class C<T> { } static class Extensions { public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, Func<TAccumulate> seedFactory, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } public static TResult Aggregate<TSource, TAccumulate, TResult>( this C<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc, Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc, Func<TAccumulate, TResult> resultSelector) { Console.WriteLine((typeof(TSource).FullName, typeof(TAccumulate).FullName, typeof(TResult).FullName)); return default; } }"; string expectedOutput = "(System.Int32, System.Int32, System.Int32)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_29() { var source = @"using System; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Func<object> x, Func<object> y) { Console.WriteLine(""M(Func<object> x, Func<object> y)""); } static void Main() { Func<object> fo = () => new A(); Func<A> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Func<object> x, Func<object> y) M(Func<object> x, Func<object> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_30() { var source = @"using System; class Program { static void M<T>(T t, Func<object> f) { Console.WriteLine(""M<T>(T t, Func<object> f)""); } static void M<T>(Func<object> f, T t) { Console.WriteLine(""M<T>(Func<object> f, T t)""); } static object F() => null; static void Main() { M(F, F); M(() => 1, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(F, F); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.M<T>(T, Func<object>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, System.Func<object>)").WithLocation(10, 9)); var expectedDiagnostics = new[] { // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(F, F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(9, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, Func<object>)' and 'Program.M<T>(Func<object>, T)' // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, System.Func<object>)", "Program.M<T>(System.Func<object>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_31() { var source = @"using System; using System.Linq.Expressions; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Expression<Func<object>> e) { Console.WriteLine(""M(Expression<Func<object>> e)""); } static void Main() { M(() => string.Empty); } }"; var expectedOutput = "M(Expression<Func<object>> e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_32() { var source = @"using System; using System.Linq.Expressions; class A { } class B : A { } class Program { static void M<T>(T x, T y) { Console.WriteLine(""M<T>(T x, T y)""); } static void M(Expression<Func<object>> x, Expression<Func<object>> y) { Console.WriteLine(""M(Expression<Func<object>> x, Expression<Func<object>> y)""); } static void Main() { Expression<Func<object>> fo = () => new A(); Expression<Func<A>> fa = () => new A(); M(() => new A(), () => new B()); M(fo, () => new B()); M(fa, () => new B()); } }"; var expectedOutput = @"M(Expression<Func<object>> x, Expression<Func<object>> y) M(Expression<Func<object>> x, Expression<Func<object>> y) M<T>(T x, T y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_33() { var source = @"using System; class Program { static void M<T>(object x, T y) { Console.WriteLine(""M<T>(object x, T y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(9, 9), // (10,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(10, 11), // (11,9): error CS0411: The type arguments for method 'Program.M<T>(object, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(object, T)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M<T, U>(T x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_34() { var source = @"using System; class Program { static void M<T, U>(Func<T> x, U y) { Console.WriteLine(""M<T, U>(Func<T> x, U y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(9, 9), // (11,9): error CS0411: The type arguments for method 'Program.M<T, U>(Func<T>, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(f, () => 2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T, U>(System.Func<T>, U)").WithLocation(11, 9)); var expectedOutput = @"M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) M<T, U>(Func<T> x, U y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_35() { var source = @"using System; class Program { static void M(Delegate x, Func<int> y) { Console.WriteLine(""M(Delegate x, Func<int> y)""); } static void M<T, U>(T x, U y) { Console.WriteLine(""M<T, U>(T x, U y)""); } static void Main() { Func<int> f = () => 0; M(() => 1, () => 2); M(() => 1, f); M(f, () => 2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, () => 2); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // M(() => 1, f); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(10, 11)); var expectedOutput = @"M<T, U>(T x, U y) M<T, U>(T x, U y) M(Delegate x, Func<int> y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_36() { var source = @"using System; class Program { static void F<T>(T t) { Console.WriteLine(""F<{0}>({0} t)"", typeof(T).Name); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "System.Delegate").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 11)); var expectedOutput = @"F<Action>(Action t) F<Func`1>(Func`1 t)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_37() { var source = @"using System; class Program { static void F(object o) { Console.WriteLine(""F(object o)""); } static void F(Delegate d) { Console.WriteLine(""F(Delegate d)""); } static void Main() { F(Main); F(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // F(Main); Diagnostic(ErrorCode.ERR_BadArgType, "Main").WithArguments("1", "method group", "object").WithLocation(8, 11), // (9,11): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // F(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "object").WithLocation(9, 11)); var expectedOutput = @"F(Delegate d) F(Delegate d)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_38() { var source = @"using System; class MyString { public static implicit operator MyString(string s) => new MyString(); } class Program { static void F(Delegate d1, Delegate d2, string s) { Console.WriteLine(""F(Delegate d1, Delegate d2, string s)""); } static void F(Func<int> f, Delegate d, MyString s) { Console.WriteLine(""F(Func<int> f, Delegate d, MyString s)""); } static void Main() { F(() => 1, () => 2, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,11): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 11), // (12,20): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Delegate").WithLocation(12, 20)); var expectedDiagnostics = new[] { // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.F(Delegate, Delegate, string)' and 'Program.F(Func<int>, Delegate, MyString)' // F(() => 1, () => 2, string.Empty); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Program.F(System.Delegate, System.Delegate, string)", "Program.F(System.Func<int>, System.Delegate, MyString)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_39() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static int F() => 0; static void Main() { M(F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11)); var expectedDiagnostics = new[] { // (10,11): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(10, 11) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_40() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(object o) { Console.WriteLine(""M(object o)""); } static void Main() { M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 11)); var expectedOutput = @"M(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_41() { var source = @"using System; using System.Linq.Expressions; class C { static void M(Expression e) { Console.WriteLine(""M(Expression e)""); } static void M(Delegate d) { Console.WriteLine(""M(Delegate d)""); } static int F() => 0; static void Main() { M(F); M(() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS1503: Argument 1: cannot convert from 'method group' to 'Expression' // M(F); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "System.Linq.Expressions.Expression").WithLocation(10, 11), // (11,11): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // M(() => 1); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 11)); var expectedDiagnostics = new[] { // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(F); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(10, 9), // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Expression)' and 'C.M(Delegate)' // M(() => 1); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Linq.Expressions.Expression)", "C.M(System.Delegate)").WithLocation(11, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_42() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""96A2DE64-6D44-4DA5-BBA4-25F5F07E0E6B"")] interface I { void F(Delegate d, short s); void F(Action a, ref int i); } class C : I { void I.F(Delegate d, short s) => Console.WriteLine(""I.F(Delegate d, short s)""); void I.F(Action a, ref int i) => Console.WriteLine(""I.F(Action a, ref int i)""); } class Program { static void M(I i) { i.F(() => { }, 1); } static void Main() { M(new C()); } }"; var expectedOutput = @"I.F(Action a, ref int i)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_43() { var source = @"using System; using System.Linq.Expressions; class Program { static int F() => 0; static void Main() { var c = new C(); c.M(F); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); var expectedDiagnostics = new[] { // (9,13): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // c.M(F); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(9, 13) }; // Breaking change from C#9 which binds to E.M. var comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void OverloadResolution_44() { var source = @"using System; using System.Linq.Expressions; class A { public static void F1(Func<int> f) { Console.WriteLine(""A.F1(Func<int> f)""); } public void F2(Func<int> f) { Console.WriteLine(""A.F2(Func<int> f)""); } } class B : A { public static void F1(Delegate d) { Console.WriteLine(""B.F1(Delegate d)""); } public void F2(Expression e) { Console.WriteLine(""B.F2(Expression e)""); } } class Program { static void Main() { B.F1(() => 1); var b = new B(); b.F2(() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.F1(Func<int> f) A.F2(Func<int> f)"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B.F1(Delegate d) B.F2(Expression e)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OverloadResolution_45() { var source = @"using System; using System.Linq.Expressions; class A { public object this[Func<int> f] => Report(""A.this[Func<int> f]""); public static object Report(string message) { Console.WriteLine(message); return null; } } class B1 : A { public object this[Delegate d] => Report(""B1.this[Delegate d]""); } class B2 : A { public object this[Expression e] => Report(""B2.this[Expression e]""); } class Program { static void Main() { var b1 = new B1(); _ = b1[() => 1]; var b2 = new B2(); _ = b2[() => 2]; } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"A.this[Func<int> f] A.this[Func<int> f]"); // Breaking change from C#9 which binds to methods from A. var expectedOutput = @"B1.this[Delegate d] B2.this[Expression e]"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_01() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { StringIntDelegate d = M; var a1 = new[] { d, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => int.Parse(s), d }; Report(a1[1]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_02() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void F(bool b) { StringIntDelegate d = M; var c1 = b ? d : ((string s) => int.Parse(s)); var c2 = b ? ((string s) => int.Parse(s)) : d; Report(c1); Report(c2); } static void Main() { F(false); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = @"StringIntDelegate StringIntDelegate"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void BestCommonType_03() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return (StringIntDelegate)M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return (StringIntDelegate)M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"StringIntDelegate StringIntDelegate"); } [Fact] public void BestCommonType_04() { var source = @"using System; delegate int StringIntDelegate(string s); class Program { static int M(string s) => s.Length; static void Main() { var f1 = (bool b) => { if (b) return M; return ((string s) => int.Parse(s)); }; var f2 = (bool b) => { if (b) return ((string s) => int.Parse(s)); return M; }; Report(f1(true)); Report(f2(true)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_05() { var source = @"using System; class Program { static int M1(string s) => s.Length; static int M2(string s) => int.Parse(s); static void Main() { var a1 = new[] { M1, (string s) => int.Parse(s) }; var a2 = new[] { (string s) => s.Length, M2 }; Report(a1[1]); Report(a2[1]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { M1, (string s) => int.Parse(s) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { M1, (string s) => int.Parse(s) }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (string s) => s.Length, M2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (string s) => s.Length, M2 }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Func`2[System.String,System.Int32]"); } [Fact] public void BestCommonType_06() { var source = @"using System; class Program { static void F1<T>(T t) { } static T F2<T>() => default; static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object>, F2<string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object>, F2<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object>, F2<string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Func`1[System.Object]"); } [Fact] public void BestCommonType_07() { var source = @"class Program { static void F1<T>(T t) { } static T F2<T>() => default; static T F3<T>(T t) => t; static void Main() { var a1 = new[] { F1<int>, F1<object> }; var a2 = new[] { F2<nint>, F2<System.IntPtr> }; var a3 = new[] { F3<string>, F3<object> }; } }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<int>, F1<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<int>, F1<object> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<nint>, F2<System.IntPtr> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<nint>, F2<System.IntPtr> }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F3<string>, F3<object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F3<string>, F3<object> }").WithLocation(10, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_08() { var source = @"#nullable enable using System; class Program { static void F<T>(T t) { } static void Main() { var a1 = new[] { F<string?>, F<string> }; var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<string?>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<string?>, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F<(int X, object Y)>, F<(int, dynamic)> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<(int X, object Y)>, F<(int, dynamic)> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action`1[System.String] System.Action`1[System.ValueTuple`2[System.Int32,System.Object]]"); } [Fact] public void BestCommonType_09() { var source = @"using System; class Program { static void Main() { var a1 = new[] { (object o) => { }, (string s) => { } }; var a2 = new[] { () => (object)null, () => (string)null }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object o) => { }, (string s) => { } }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { () => (object)null, () => (string)null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => (object)null, () => (string)null }").WithLocation(7, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,26): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(6, 26), // (6,34): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // var a1 = new[] { (object o) => { }, (string s) => { } }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(6, 34)); } [Fact] public void BestCommonType_10() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<string>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, string> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<string>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<string>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, string> }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000004}`2[System.String,System.Object] <>A{00000001}`2[System.Object,System.String]"); } [Fact] [WorkItem(55909, "https://github.com/dotnet/roslyn/issues/55909")] public void BestCommonType_11() { var source = @"using System; class Program { static void F1<T>(T t, ref object o) { } static void F2<T, U>(ref T t, U u) { } static void Main() { var a1 = new[] { F1<object>, F1<string> }; var a2 = new[] { F2<object, string>, F2<object, object> }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1<object>, F1<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1<object>, F1<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F2<object, string>, F2<object, object> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2<object, string>, F2<object, object> }").WithLocation(9, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/55909: ConversionsBase.HasImplicitSignatureConversion() // relies on the variance of FunctionTypeSymbol.GetInternalDelegateType() which fails for synthesized // delegate types where the type parameters are invariant. comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_12() { var source = @"class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, F<string> }; var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; } }"; var expectedDiagnostics = new[] { // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, F<string> }").WithLocation(6, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (string x, ref object y) => { } }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (object x, ref object y) => { }, (object x, ref string y) => { } }").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BestCommonType_13() { var source = @"using System; class Program { static void F<T>(ref T t) { } static void Main() { var a1 = new[] { F<object>, null }; var a2 = new[] { default, F<string> }; var a3 = new[] { null, default, (object x, ref string y) => { } }; Report(a1[0]); Report(a2[1]); Report(a3[2]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F<object>, null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F<object>, null }").WithLocation(7, 18), // (8,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { default, F<string> }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { default, F<string> }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { null, default, (object x, ref string y) => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null, default, (object x, ref string y) => { } }").WithLocation(9, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"<>A{00000001}`1[System.Object] <>A{00000001}`1[System.String] <>A{00000004}`2[System.Object,System.String] "); } /// <summary> /// Best common type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void BestCommonType_NoInferredSignature() { var source = @"class Program { static void F1() { } static int F1(int i) => i; static void F2() { } static void Main() { var a1 = new[] { F1 }; var a2 = new[] { F1, F2 }; var a3 = new[] { F2, F1 }; var a4 = new[] { x => x }; var a5 = new[] { x => x, (int y) => y }; var a6 = new[] { (int y) => y, static x => x }; var a7 = new[] { x => x, F1 }; var a8 = new[] { F1, (int y) => y }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (9,18): error CS0826: No best type found for implicitly-typed array // var a2 = new[] { F1, F2 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, F2 }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var a3 = new[] { F2, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F2, F1 }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var a5 = new[] { x => x, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, (int y) => y }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var a6 = new[] { (int y) => y, static x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { (int y) => y, static x => x }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var a8 = new[] { F1, (int y) => y }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1, (int y) => y }").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { F1 }").WithLocation(8, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var a4 = new[] { x => x }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x }").WithLocation(11, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var a7 = new[] { x => x, F1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x => x, F1 }").WithLocation(14, 18)); } [Fact] public void ArrayInitializer_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Func<int>[] { () => 1 }; var a2 = new Expression<Func<int>>[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; string expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]]"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void ArrayInitializer_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var a1 = new Delegate[] { () => 1 }; var a2 = new Expression[] { () => 2 }; Report(a1[0]); Report(a2[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,35): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // var a1 = new Delegate[] { () => 1 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 35), // (8,37): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // var a2 = new Expression[] { () => 2 }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 2").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(8, 37)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]]"); } [Fact] public void ArrayInitializer_03() { var source = @"using System; class Program { static void Main() { var a1 = new[] { () => 1 }; Report(a1[0]); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { () => 1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { () => 1 }").WithLocation(6, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32]"); } [Fact] public void ConditionalOperator_01() { var source = @"class Program { static void F<T>(T t) { } static void Main() { var c1 = F<object> ?? F<string>; var c2 = ((object o) => { }) ?? ((string s) => { }); var c3 = F<string> ?? ((object o) => { }); } }"; var expectedDiagnostics = new[] { // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // var c1 = F<object> ?? F<string>; Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<object> ?? F<string>").WithArguments("??", "method group", "method group").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'lambda expression' and 'lambda expression' // var c2 = ((object o) => { }) ?? ((string s) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "((object o) => { }) ?? ((string s) => { })").WithArguments("??", "lambda expression", "lambda expression").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'lambda expression' // var c3 = F<string> ?? ((object o) => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "F<string> ?? ((object o) => { })").WithArguments("??", "method group", "lambda expression").WithLocation(8, 18) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaReturn_01() { var source = @"using System; class Program { static void Main() { var a1 = () => () => 1; var a2 = () => Main; Report(a1()); Report(a2()); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Int32] System.Action"); } [Fact] public void InferredType_MethodGroup() { var source = @"class Program { static void Main() { System.Delegate d = Main; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Fact] public void InferredType_LambdaExpression() { var source = @"class Program { static void Main() { System.Delegate d = () => { }; System.Console.Write(d.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); Assert.Equal("System.Action", typeInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); var method = (IMethodSymbol)symbolInfo.Symbol!; Assert.Equal(MethodKind.LambdaMethod, method.MethodKind); Assert.True(HaveMatchingSignatures(((INamedTypeSymbol)typeInfo.Type!).DelegateInvokeMethod!, method)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_01() { var source = @"using System; class Program { static void Main() { Report(() => { return; }); Report((bool b) => { if (b) return; }); Report((bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Action System.Action`1[System.Boolean] System.Action`1[System.Boolean] "); } [Fact] public void InferredReturnType_02() { var source = @"using System; class Program { static void Main() { Report(async () => { return; }); Report(async (bool b) => { if (b) return; }); Report(async (bool b) => { if (b) return; else return; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] System.Func`2[System.Boolean,System.Threading.Tasks.Task] "); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_03() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return null; }); Report((bool b) => { if (b) return; else return null; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return null; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return null; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return null; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [WorkItem(55320, "https://github.com/dotnet/roslyn/issues/55320")] [Fact] public void InferredReturnType_04() { var source = @"using System; class Program { static void Main() { Report((bool b) => { if (b) return default; }); Report((bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return default; }").WithLocation(6, 16), // (7,16): error CS8917: The delegate type could not be inferred. // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(bool b) => { if (b) return; else return default; }").WithLocation(7, 16), // (7,50): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Report((bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 50)); } [Fact] public void ExplicitReturnType_01() { var source = @"using System; class Program { static void Main() { Report(object () => { return; }); Report(object (bool b) => { if (b) return null; }); Report(object (bool b) => { if (b) return; else return default; }); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (6,31): error CS0126: An object of a type convertible to 'object' is required // Report(object () => { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(6, 31), // (7,32): error CS1643: Not all code paths return a value in lambda expression of type 'Func<bool, object>' // Report(object (bool b) => { if (b) return null; }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<bool, object>").WithLocation(7, 32), // (8,44): error CS0126: An object of a type convertible to 'object' is required // Report(object (bool b) => { if (b) return; else return default; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(8, 44)); } [Fact] public void TypeInference_Constraints_01() { var source = @"using System; using System.Linq.Expressions; class Program { static T F1<T>(T t) where T : Delegate => t; static T F2<T>(T t) where T : Expression => t; static void Main() { Report(F1((int i) => { })); Report(F2(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((int i) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F2<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Action`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_02() { var source = @"using System; using System.Linq.Expressions; class A<T> { public static U F<U>(U u) where U : T => u; } class B { static void Main() { Report(A<object>.F(() => 1)); Report(A<ICloneable>.F(() => 1)); Report(A<Delegate>.F(() => 1)); Report(A<MulticastDelegate>.F(() => 1)); Report(A<Func<int>>.F(() => 1)); Report(A<Expression>.F(() => 1)); Report(A<LambdaExpression>.F(() => 1)); Report(A<Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_Constraints_03() { var source = @"using System; using System.Linq.Expressions; class A<T, U> where U : T { public static V F<V>(V v) where V : U => v; } class B { static void Main() { Report(A<object, object>.F(() => 1)); Report(A<object, Delegate>.F(() => 1)); Report(A<object, Func<int>>.F(() => 1)); Report(A<Delegate, Func<int>>.F(() => 1)); Report(A<object, Expression>.F(() => 1)); Report(A<object, Expression<Func<int>>>.F(() => 1)); Report(A<Expression, LambdaExpression>.F(() => 1)); Report(A<Expression, Expression<Func<int>>>.F(() => 1)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: $@"System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "); } [Fact] public void TypeInference_MatchingSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(string s) => s.Length; static void F2(string s) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_DistinctSignatures() { var source = @"using System; class Program { static T F<T>(T x, T y) => x; static int F1(object o) => o.GetHashCode(); static void F2(object o) { } static void Main() { Report(F(F1, (string s) => int.Parse(s))); Report(F((string s) => { }, F2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(F1, (string s) => int.Parse(s))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(9, 16), // (10,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, F2)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(10, 16)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.String,System.Int32] System.Action`1[System.String] "); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static T M<T>(T x, T y) => x; static int F1(int i) => i; static void F1() { } static T F2<T>(T t) => t; static void Main() { var f1 = M(x => x, (int y) => y); var f2 = M(F1, F2<int>); var f3 = M(F2<object>, z => z); Report(f1); Report(f2); Report(f3); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(F1, F2<int>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M(F2<object>, z => z); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(12, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Object,System.Object] "); } [Fact] public void TypeInference_02() { var source = @"using System; class Program { static T M<T>(T x, T y) where T : class => x ?? y; static T F<T>() => default; static void Main() { var f1 = M(F<object>, null); var f2 = M(default, F<string>); var f3 = M((object x, ref string y) => { }, default); var f4 = M(null, (ref object x, string y) => { }); Report(f1); Report(f2); Report(f3); Report(f4); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f1 = M(F<object>, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(8, 18), // (9,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f2 = M(default, F<string>); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(9, 18), // (10,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f3 = M((object x, ref string y) => { }, default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var f4 = M(null, (ref object x, string y) => { }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("Program.M<T>(T, T)").WithLocation(11, 18)); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"System.Func`1[System.Object] System.Func`1[System.String] <>A{00000004}`2[System.Object,System.String] <>A{00000001}`2[System.Object,System.String] "); } [Fact] public void TypeInference_LowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (string s) => { })); Report(F(() => 2, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F<T>(T x, T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F(d1, (object o) => { })); Report(F(() => 1.0, d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (11,22): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(11, 22), // (11,30): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F(d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(11, 30), // (12,24): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(12, 24), // (12,24): 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 // Report(F(() => 1.0, d2)); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("lambda expression").WithLocation(12, 24) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_LowerBoundsDistinctSignature_02() { var source = @"using System; class Program { static T F<T>(T x, T y) => y; static void Main() { Report(F((string s) => { }, (object o) => { })); Report(F(() => string.Empty, () => new object())); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(7, 16), // (8,16): error CS0411: The type arguments for method 'Program.F<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F(() => string.Empty, () => new object())); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(T, T)").WithLocation(8, 16)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,37): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(7, 37), // (7,45): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F((string s) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(7, 45)); } [Fact] public void TypeInference_UpperAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<int>> a2 = null; Report(F1(a1, (string s) => { })); Report(F2(() => 2, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Action<D1<string>> a1 = null; Action<D2<object>> a2 = null; Report(F1(a1, (object o) => { })); Report(F2(() => string.Empty, a2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,23): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 23), // (12,31): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(a1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 31) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_UpperAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(Action<T> x, T y) => y; static T F2<T>(T x, Action<T> y) => x; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,42): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(10, 50) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsMatchingSignature() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<int> d2 = () => 1; Report(F1(ref d1, (string s) => { })); Report(F2(() => 2, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedOutput = @"D1`1[System.String] D2`1[System.Int32] "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_01() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(ref T x, T y) => y; static T F2<T>(T x, ref T y) => y; static void Main() { D1<string> d1 = (string s) => { }; D2<object> d2 = () => new object(); Report(F1(ref d1, (object o) => { })); Report(F2(() => string.Empty, ref d2)); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (12,27): error CS1661: Cannot convert lambda expression to type 'D1<string>' because the parameter types do not match the delegate parameter types // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "D1<string>").WithLocation(12, 27), // (12,35): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Report(F1(ref d1, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(12, 35) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TypeInference_ExactAndLowerBoundsDistinctSignature_02() { var source = @"using System; delegate void D1<T>(T t); delegate T D2<T>(); class Program { static T F1<T>(in T x, T y) => y; static T F2<T>(T x, in T y) => y; static void Main() { Report(F1((D1<string> d) => { }, (object o) => { })); Report(F2(() => string.Empty, (D2<object> d) => { })); } static void Report(object obj) => Console.WriteLine(obj.GetType()); }"; var expectedDiagnostics = new[] { // (10,16): error CS0411: The type arguments for method 'Program.F1<T>(in T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(in T, T)").WithLocation(10, 16), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,42): error CS1661: Cannot convert lambda expression to type 'Action<D1<string>>' because the parameter types do not match the delegate parameter types // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<D1<string>>").WithLocation(10, 42), // (10,50): error CS1678: Parameter 1 is declared as type 'object' but should be 'D1<string>' // Report(F1((D1<string> d) => { }, (object o) => { })); Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "D1<string>").WithLocation(10, 50), // (11,16): error CS0411: The type arguments for method 'Program.F2<T>(T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Report(F2(() => 1.0, (D2<int> d) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(T, in T)").WithLocation(11, 16)); } [Fact] public void TypeInference_Nested_01() { var source = @"delegate void D<T>(T t); class Program { static T F1<T>(T t) => t; static D<T> F2<T>(D<T> d) => d; static void Main() { F2(F1((string s) => { })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(D<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(D<T>)").WithLocation(8, 9)); } [Fact] public void TypeInference_Nested_02() { var source = @"using System.Linq.Expressions; class Program { static T F1<T>(T x) => throw null; static Expression<T> F2<T>(Expression<T> e) => e; static void Main() { F2(F1((object x1) => 1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,12): error CS0411: The type arguments for method 'Program.F1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((string s) => { })); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T)").WithLocation(8, 12)); // Reports error on F1() in C#9, and reports error on F2() in C#10. comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(F1((object x1) => 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<T>)").WithLocation(8, 9)); } /// <summary> /// Method type inference with delegate signatures that cannot be inferred. /// </summary> [Fact] public void TypeInference_NoInferredSignature() { var source = @"class Program { static void F1() { } static void F1(int i) { } static void F2() { } static T M1<T>(T t) => t; static T M2<T>(T x, T y) => x; static void Main() { var a1 = M1(F1); var a2 = M2(F1, F2); var a3 = M2(F2, F1); var a4 = M1(x => x); var a5 = M2(x => x, (int y) => y); var a6 = M2((int y) => y, x => x); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (11,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a2 = M2(F1, F2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(11, 18), // (12,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a3 = M2(F2, F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(12, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18), // (14,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a5 = M2(x => x, (int y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(14, 18), // (15,18): error CS0411: The type arguments for method 'Program.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a6 = M2((int y) => y, x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Program.M2<T>(T, T)").WithLocation(15, 18)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a1 = M1(F1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(10, 18), // (13,18): error CS0411: The type arguments for method 'Program.M1<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var a4 = M1(x => x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T)").WithLocation(13, 18)); } [Fact] public void TypeInference_ExplicitReturnType_01() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T> f) { Console.WriteLine(f.GetType()); } static void F2<T>(Expression<Func<T>> e) { Console.WriteLine(e.GetType()); } static void Main() { F1(int () => throw new Exception()); F2(int () => default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int () => throw new Exception()); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(int () => default); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedOutput = $@"System.Func`1[System.Int32] {s_expressionOfTDelegate0ArgTypeName}[System.Func`1[System.Int32]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_02() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> f) { Console.WriteLine(f.GetType()); } static void F2<T>(Expression<Func<T, T>> e) { Console.WriteLine(e.GetType()); } static void Main() { F1(int (i) => i); F2(string (s) => s); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedOutput = $@"System.Func`2[System.Int32,System.Int32] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.String,System.String]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_03() { var source = @"using System; delegate ref T D1<T>(T t); delegate ref readonly T D2<T>(T t); class Program { static void F1<T>(D1<T> d) { Console.WriteLine(d.GetType()); } static void F2<T>(D2<T> d) { Console.WriteLine(d.GetType()); } static void Main() { F1((ref int (i) => ref i)); F2((ref readonly string (s) => ref s)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ref int").WithArguments("lambda return type", "10.0").WithLocation(10, 13), // (10,32): error CS8166: Cannot return a parameter by reference 'i' because it is not a ref or out parameter // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(10, 32), // (11,13): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ref readonly string").WithArguments("lambda return type", "10.0").WithLocation(11, 13), // (11,44): error CS8166: Cannot return a parameter by reference 's' because it is not a ref or out parameter // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "s").WithArguments("s").WithLocation(11, 44)); var expectedDiagnostics = new[] { // (10,32): error CS8166: Cannot return a parameter by reference 'i' because it is not a ref or out parameter // F1((ref int (i) => ref i)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "i").WithArguments("i").WithLocation(10, 32), // (11,44): error CS8166: Cannot return a parameter by reference 's' because it is not a ref or out parameter // F2((ref readonly string (s) => ref s)); Diagnostic(ErrorCode.ERR_RefReturnParameter, "s").WithArguments("s").WithLocation(11, 44) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, T y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, T y) { Console.WriteLine(x.GetType()); } static void Main() { F1(object (o) => o, 1); F1(int (i) => i, 2); F2(object (o) => o, string.Empty); F2(string (s) => s, string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (o) => o, 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i, 2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 12), // (11,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(object (o) => o, string.Empty); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(11, 12), // (12,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s, string.Empty); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(12, 12)); var expectedOutput = $@"System.Func`2[System.Object,System.Object] System.Func`2[System.Int32,System.Int32] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.Object,System.Object]] {s_expressionOfTDelegate1ArgTypeName}[System.Func`2[System.String,System.String]] "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_05() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, T y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, T y) { Console.WriteLine(x.GetType()); } static void Main() { F1(int (i) => i, (object)1); F2(string (s) => s, (object)2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, T)").WithLocation(9, 9), // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (10,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, T)").WithLocation(10, 9), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(10, 12)); var expectedDiagnostics = new[] { // (9,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (i) => i, (object)1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, T)").WithLocation(9, 9), // (10,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (s) => s, (object)2); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, T)").WithLocation(10, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_06() { var source = @"using System; using System.Linq.Expressions; interface I<T> { } class Program { static void F1<T>(Func<T, T> f) { } static void F2<T>(Func<T, I<T>> f) { } static void F3<T>(Func<I<T>, T> f) { } static void F4<T>(Func<I<T>, I<T>> f) { } static void F5<T>(Expression<Func<T, T>> e) { } static void F6<T>(Expression<Func<T, I<T>>> e) { } static void F7<T>(Expression<Func<I<T>, T>> e) { } static void F8<T>(Expression<Func<I<T>, I<T>>> e) { } static void Main() { F1(int (int i) => default); F2(I<int> (int i) => default); F3(int (I<int> i) => default); F4(I<int> (I<int> i) => default); F5(int (int i) => default); F6(I<int> (int i) => default); F7(int (I<int> i) => default); F8(I<int> (I<int> i) => default); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_07() { var source = @"using System; using System.Linq.Expressions; interface I<T> { } class Program { static void F1<T>(Func<T, T> f) { } static void F2<T>(Func<T, I<T>> f) { } static void F3<T>(Func<I<T>, T> f) { } static void F4<T>(Func<I<T>, I<T>> f) { } static void F5<T>(Expression<Func<T, T>> e) { } static void F6<T>(Expression<Func<T, I<T>>> e) { } static void F7<T>(Expression<Func<I<T>, T>> e) { } static void F8<T>(Expression<Func<I<T>, I<T>>> e) { } static void Main() { F1(int (object i) => default); F2(I<int> (object i) => default); F3(object (I<int> i) => default); F4(I<object> (I<int> i) => default); F5(object (int i) => default); F6(I<object> (int i) => default); F7(int (I<object> i) => default); F8(I<int> (I<object> i) => default); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(int (object i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>)").WithLocation(16, 9), // (17,9): error CS0411: The type arguments for method 'Program.F2<T>(Func<T, I<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(I<int> (object i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Func<T, I<T>>)").WithLocation(17, 9), // (18,9): error CS0411: The type arguments for method 'Program.F3<T>(Func<I<T>, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F3(object (I<int> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F3").WithArguments("Program.F3<T>(System.Func<I<T>, T>)").WithLocation(18, 9), // (19,9): error CS0411: The type arguments for method 'Program.F4<T>(Func<I<T>, I<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F4(I<object> (I<int> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F4").WithArguments("Program.F4<T>(System.Func<I<T>, I<T>>)").WithLocation(19, 9), // (20,9): error CS0411: The type arguments for method 'Program.F5<T>(Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F5(object (int i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F5").WithArguments("Program.F5<T>(System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(20, 9), // (21,9): error CS0411: The type arguments for method 'Program.F6<T>(Expression<Func<T, I<T>>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F6(I<object> (int i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F6").WithArguments("Program.F6<T>(System.Linq.Expressions.Expression<System.Func<T, I<T>>>)").WithLocation(21, 9), // (22,9): error CS0411: The type arguments for method 'Program.F7<T>(Expression<Func<I<T>, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F7(int (I<object> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F7").WithArguments("Program.F7<T>(System.Linq.Expressions.Expression<System.Func<I<T>, T>>)").WithLocation(22, 9), // (23,9): error CS0411: The type arguments for method 'Program.F8<T>(Expression<Func<I<T>, I<T>>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F8(I<int> (I<object> i) => default); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F8").WithArguments("Program.F8<T>(System.Linq.Expressions.Expression<System.Func<I<T>, I<T>>>)").WithLocation(23, 9)); } // Variance in inference from explicit return type is disallowed // (see https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md). [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_08() { var source = @"using System; using System.Linq.Expressions; class Program { static void F1<T>(Func<T, T> x, Func<T, T> y) { Console.WriteLine(x.GetType()); } static void F2<T>(Expression<Func<T, T>> x, Expression<Func<T, T>> y) { Console.WriteLine(x.GetType()); } static void Main() { F1(int (x) => x, int (y) => y); F1(object (x) => x, int (y) => y); F2(string (x) => x, string (y) => y); F2(string (x) => x, object (y) => y); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 12), // (9,26): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(int (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(9, 26), // (10,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, System.Func<T, T>)").WithLocation(10, 9), // (10,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(10, 12), // (10,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int").WithArguments("lambda return type", "10.0").WithLocation(10, 29), // (11,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, string (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(11, 12), // (11,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, string (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(11, 29), // (12,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(12, 9), // (12,12): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "string").WithArguments("lambda return type", "10.0").WithLocation(12, 12), // (12,29): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object").WithArguments("lambda return type", "10.0").WithLocation(12, 29)); var expectedDiagnostics = new[] { // (10,9): error CS0411: The type arguments for method 'Program.F1<T>(Func<T, T>, Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(object (x) => x, int (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(System.Func<T, T>, System.Func<T, T>)").WithLocation(10, 9), // (12,9): error CS0411: The type arguments for method 'Program.F2<T>(Expression<Func<T, T>>, Expression<Func<T, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F2(string (x) => x, object (y) => y); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F2").WithArguments("Program.F2<T>(System.Linq.Expressions.Expression<System.Func<T, T>>, System.Linq.Expressions.Expression<System.Func<T, T>>)").WithLocation(12, 9) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_09() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { F1(object (x1) => x1).ToString(); F2(object (x2) => x2).ToString(); F1(object? (y1) => y1).ToString(); F2(object? (y2) => y2).ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(object? (y1) => y1).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(object? (y1) => y1)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(object? (y2) => y2).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(object? (y2) => y2)").WithLocation(13, 9)); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_10() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { F1( #nullable disable object (x1) => #nullable enable x1).ToString(); F2( #nullable disable object (x2) => #nullable enable x2).ToString(); F1( #nullable disable object #nullable enable (y1) => y1).ToString(); F2( #nullable disable object #nullable enable (y2) => y2).ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_11() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { var x1 = F1( #nullable enable object? #nullable disable (x1) => #nullable enable x1); var x2 = F2( #nullable enable object? #nullable disable (x2) => #nullable enable x2); var y1 = F1( #nullable enable object #nullable disable (y1) => #nullable enable y1); var y2 = F2( #nullable enable object #nullable disable (y2) => #nullable enable y2); x1.ToString(); x2.ToString(); y1.ToString(); y2.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (38,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(38, 9), // (39,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(39, 9)); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_ExplicitReturnType_12() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static T F1<T>(Func<T, T> f) => default!; static T F2<T>(Expression<Func<T, T>> e) => default!; static void Main() { var x1 = F1(object (object x1) => x1); var x2 = F1(object (object? x2) => x2); var x3 = F1(object? (object x3) => x3); var x4 = F1(object? (object? x4) => x4); var y1 = F2(object (object y1) => y1); var y2 = F2(object (object? y2) => y2); var y3 = F2(object? (object y3) => y3); var y4 = F2(object? (object? y4) => y4); x1.ToString(); x2.ToString(); x3.ToString(); x4.ToString(); y1.ToString(); y2.ToString(); y3.ToString(); y4.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,21): warning CS8622: Nullability of reference types in type of parameter 'x2' of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var x2 = F1(object (object? x2) => x2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "object (object? x2) => x2").WithArguments("x2", "lambda expression", "System.Func<object, object>").WithLocation(11, 21), // (11,44): warning CS8603: Possible null reference return. // var x2 = F1(object (object? x2) => x2); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x2").WithLocation(11, 44), // (12,21): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var x3 = F1(object? (object x3) => x3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "object? (object x3) => x3").WithArguments("lambda expression", "System.Func<object, object>").WithLocation(12, 21), // (15,21): warning CS8622: Nullability of reference types in type of parameter 'y2' of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var y2 = F2(object (object? y2) => y2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "object (object? y2) => y2").WithArguments("y2", "lambda expression", "System.Func<object, object>").WithLocation(15, 21), // (15,44): warning CS8603: Possible null reference return. // var y2 = F2(object (object? y2) => y2); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(15, 44), // (16,21): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<object, object>' (possibly because of nullability attributes). // var y3 = F2(object? (object y3) => y3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "object? (object y3) => y3").WithArguments("lambda expression", "System.Func<object, object>").WithLocation(16, 21), // (21,9): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(21, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // y4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y4").WithLocation(25, 9)); } [Fact] public void Variance_01() { var source = @"using System; class Program { static void Main() { Action<string> a1 = s => { }; Action<string> a2 = (string s) => { }; Action<string> a3 = (object o) => { }; Action<string> a4 = (Action<object>)((object o) => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,29): error CS1661: Cannot convert lambda expression to type 'Action<string>' because the parameter types do not match the delegate parameter types // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(object o) => { }").WithArguments("lambda expression", "System.Action<string>").WithLocation(8, 29), // (8,37): error CS1678: Parameter 1 is declared as type 'object' but should be 'string' // Action<string> a3 = (object o) => { }; Diagnostic(ErrorCode.ERR_BadParamType, "o").WithArguments("1", "", "object", "", "string").WithLocation(8, 37)); } [Fact] public void Variance_02() { var source = @"using System; class Program { static void Main() { Func<object> f1 = () => string.Empty; Func<object> f2 = string () => string.Empty; Func<object> f3 = (Func<string>)(() => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,27): error CS8934: Cannot convert lambda expression to type 'Func<object>' because the return type does not match the delegate return type // Func<object> f2 = string () => string.Empty; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "string () => string.Empty").WithArguments("lambda expression", "System.Func<object>").WithLocation(7, 27)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } [Fact] public void BinaryOperator_01() { var source = @"using System; class Program { static void Main() { var b1 = (() => { }) == null; var b2 = null == Main; var b3 = Main == (() => { }); Console.WriteLine((b1, b2, b3)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and '<null>' // var b1 = (() => { }) == null; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(() => { }) == null").WithArguments("==", "lambda expression", "<null>").WithLocation(6, 18), // (7,18): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // var b2 = null == Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == Main").WithArguments("==", "<null>", "method group").WithLocation(7, 18), // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'lambda expression' // var b3 = Main == (() => { }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main == (() => { })").WithArguments("==", "method group", "lambda expression").WithLocation(8, 18)); var expectedOutput = @"(False, False, False)"; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_02() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Expression e) { Console.WriteLine(""operator=(C c, Expression e)""); return c; } static void Main() { var c = new C(); _ = c + Main; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (10,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'method group' // _ = c + Main; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + Main").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0034: Operator '+' is ambiguous on operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_03() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13), // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(11, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_04() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, object o) { Console.WriteLine(""operator+(C c, object o)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13), // (12,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'lambda expression' // _ = c + (() => 1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + (() => 1)").WithArguments("+", "C", "lambda expression").WithLocation(12, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_05() { var source = @"using System; class C { public static C operator+(C c, Delegate d) { Console.WriteLine(""operator+(C c, Delegate d)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; _ = c + (() => 1); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(10, 13)); var expectedOutput = @"operator+(C c, Delegate d) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_06() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static void Main() { var c = new C(); _ = c + (() => new object()); _ = c + (() => 1); } }"; var expectedOutput = @"operator+(C c, Func<object> f) operator+(C c, Func<object> f) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BinaryOperator_07() { var source = @"using System; using System.Linq.Expressions; class C { public static C operator+(C c, Expression e) { Console.WriteLine(""operator+(C c, Expression e)""); return c; } public static C operator+(C c, Func<object> f) { Console.WriteLine(""operator+(C c, Func<object> f)""); return c; } static int F() => 0; static void Main() { var c = new C(); _ = c + F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS0019: Operator '+' cannot be applied to operands of type 'C' and 'method group' // _ = c + F; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c + F").WithArguments("+", "C", "method group").WithLocation(11, 13)); var expectedDiagnostics = new[] { // (11,17): error CS0428: Cannot convert method group 'F' to non-delegate type 'Expression'. Did you intend to invoke the method? // _ = c + F; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "System.Linq.Expressions.Expression").WithLocation(11, 17) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void BinaryOperator_08() { var source = @"using System; class A { public static A operator+(A a, Func<int> f) { Console.WriteLine(""operator+(A a, Func<int> f)""); return a; } } class B : A { public static B operator+(B b, Delegate d) { Console.WriteLine(""operator+(B b, Delegate d)""); return b; } static int F() => 1; static void Main() { var b = new B(); _ = b + F; _ = b + (() => 2); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"operator+(A a, Func<int> f) operator+(A a, Func<int> f) "); // Breaking change from C#9. string expectedOutput = @"operator+(B b, Delegate d) operator+(B b, Delegate d) "; CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: expectedOutput); CompileAndVerify(source, expectedOutput: expectedOutput); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_18() { var source = @"using System; class Program { static void Main() { Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { return 1; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, out int _17) => { _17 = 0; return 2; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, ref int _17) => { return 3; }); Report((int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, in int _17) => { return 4; }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>F`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{200000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{100000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] <>F{300000000}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Int32] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_19() { var source = @"using System; class Program { static void F1(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18) { } static void F2(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, out object _18) { _18 = null; } static void F3(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, ref object _18) { } static void F4(ref int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, in object _18) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{800000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{400000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] <>A{c00000001}`18[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object] "); } [Fact] [WorkItem(55570, "https://github.com/dotnet/roslyn/issues/55570")] public void SynthesizedDelegateTypes_20() { var source = @"using System; class Program { static void F1( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, int _33) { } static void F2( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, out int _33) { _33 = 0; } static void F3( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, ref int _33) { } static void F4( int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17, object _18, int _19, object _20, int _21, object _22, int _23, object _24, int _25, object _26, int _27, object _28, int _29, object _30, int _31, ref object _32, in int _33) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"<>A{4000000000000000\,00000000}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000002}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000001}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] <>A{4000000000000000\,00000003}`33[System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32,System.Object,System.Int32] "); } /// <summary> /// Synthesized delegate types should only be emitted if used. /// </summary> [Fact] [WorkItem(55896, "https://github.com/dotnet/roslyn/issues/55896")] public void SynthesizedDelegateTypes_21() { var source = @"using System; delegate void D2(object x, ref object y); delegate void D4(out object x, ref object y); class Program { static void F1(ref object x, object y) { } static void F2(object x, ref object y) { } static void Main() { var d1 = F1; D2 d2 = F2; var d3 = (ref object x, out object y) => { y = null; }; D4 d4 = (out object x, ref object y) => { x = null; }; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, validator: validator, expectedOutput: @"<>A{00000001}`2[System.Object,System.Object] D2 <>A{00000009}`2[System.Object,System.Object] D4"); static void validator(PEAssembly assembly) { var reader = assembly.GetMetadataReader(); var actualTypes = reader.GetTypeDefNames().Select(h => reader.GetString(h)).ToArray(); // https://github.com/dotnet/roslyn/issues/55896: Should not include <>A{00000004}`2 or <>A{00000006}`2. string[] expectedTypes = new[] { "<Module>", "<>A{00000001}`2", "<>A{00000004}`2", "<>A{00000006}`2", "<>A{00000009}`2", "D2", "D4", "Program", "<>c", }; AssertEx.Equal(expectedTypes, actualTypes); } } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Semantic/Semantics/LambdaTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LambdaTests : CSharpTestBase { [Fact, WorkItem(37456, "https://github.com/dotnet/roslyn/issues/37456")] public void Verify37456() { var comp = CreateCompilation(@" using System; using System.Collections.Generic; using System.Linq; public static partial class EnumerableEx { public static void Join1<TA, TKey, T>(this IEnumerable<TA> a, Func<TA, TKey> aKey, Func<TA, T> aSel, Func<TA, TA, T> sel) { KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v); _ = a.GroupJoin(a, aKey, aKey, (f, ss) => Pair(f, ss.Select(s => Pair(true, s)))); // simplified repro } public static IEnumerable<T> Join2<TA, TB, TKey, T>(this IEnumerable<TA> a, IEnumerable<TB> b, Func<TA, TKey> aKey, Func<TB, TKey> bKey, Func<TA, T> aSel, Func<TA, TB, T> sel, IEqualityComparer<TKey> comp) { KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v); return from j in a.GroupJoin(b, aKey, bKey, (f, ss) => Pair(f, from s in ss select Pair(true, s)), comp) from s in j.Value.DefaultIfEmpty() select s.Key ? sel(j.Key, s.Value) : aSel(j.Key); } }"); comp.VerifyDiagnostics(); CompileAndVerify(comp); // emitting should not hang } [Fact, WorkItem(608181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608181")] public void BadInvocationInLambda() { var src = @" using System; using System.Linq.Expressions; class C { Expression<Action<dynamic>> e = x => new object[](x); }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(src); comp.VerifyDiagnostics( // (7,52): error CS1586: Array creation must have array size or array initializer // Expression<Action<dynamic>> e = x => new object[](x); Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(7, 52) ); } [Fact] public void TestLambdaErrors01() { var comp = CreateCompilationWithMscorlib40AndSystemCore(@" using System; using System.Linq.Expressions; namespace System.Linq.Expressions { public class Expression<T> {} } class C { delegate void D1(ref int x, out int y, int z); delegate void D2(out int x); void M() { int q1 = ()=>1; int q2 = delegate { return 1; }; Func<int> q3 = x3=>1; Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type D1 q6 = (double x6, ref int y6, ref int z6)=>1; // COMPATIBILITY: The C# 4 compiler produces two errors: // // error CS1676: Parameter 2 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D1' because it has one or more out parameters // // This seems redundant (because there is no 'parameter 2' in the source code) // I propose that we eliminate the first error. D1 q7 = delegate {}; Frob q8 = ()=>{}; D2 q9 = x9=>{}; D1 q10 = (x10,y10,z10)=>{}; // COMPATIBILITY: The C# 4 compiler produces two errors: // // error CS0127: Since 'System.Action' returns void, a return keyword must // not be followed by an object expression // // error CS1662: Cannot convert lambda expression to delegate type 'System.Action' // because some of the return types in the block are not implicitly convertible to // the delegate return type // // The problem is adequately characterized by the first message; I propose we // eliminate the second, which seems both redundant and wrong. Action q11 = ()=>{ return 1; }; Action q12 = ()=>1; Func<int> q13 = ()=>{ if (false) return 1; }; Func<int> q14 = ()=>123.456; // Note that the type error is still an error even if the offending // return is unreachable. Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; // In the native compiler these errors were caught at parse time. In Roslyn, these are now semantic // analysis errors. See changeset 1674 for details. Action<int[]> q16 = delegate (params int[] p) { }; Action<string[]> q17 = (params string[] s)=>{}; Action<int, double[]> q18 = (int x, params double[] s)=>{}; object q19 = new Action( (int x)=>{} ); Expression<int> ex1 = ()=>1; } }"); comp.VerifyDiagnostics( // (16,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // int q1 = ()=>1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "()=>1").WithArguments("lambda expression", "int").WithLocation(16, 18), // (17,18): error CS1660: Cannot convert anonymous method to type 'int' because it is not a delegate type // int q2 = delegate { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate { return 1; }").WithArguments("anonymous method", "int").WithLocation(17, 18), // (18,24): error CS1593: Delegate 'Func<int>' does not take 1 arguments // Func<int> q3 = x3=>1; Diagnostic(ErrorCode.ERR_BadDelArgCount, "x3=>1").WithArguments("System.Func<int>", "1").WithLocation(18, 24), // (19,37): error CS0234: The type or namespace name 'Itn23' does not exist in the namespace 'System' (are you missing an assembly reference?) // Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Itn23").WithArguments("Itn23", "System").WithLocation(19, 37), // (20,35): error CS0234: The type or namespace name 'Duobel' does not exist in the namespace 'System' (are you missing an assembly reference?) // Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Duobel").WithArguments("Duobel", "System").WithLocation(20, 35), // (20,27): error CS1593: Delegate 'Func<double>' does not take 1 arguments // Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type Diagnostic(ErrorCode.ERR_BadDelArgCount, "(System.Duobel x5)=>1").WithArguments("System.Func<double>", "1").WithLocation(20, 27), // (21,17): error CS1661: Cannot convert lambda expression to delegate type 'C.D1' because the parameter types do not match the delegate parameter types // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double x6, ref int y6, ref int z6)=>1").WithArguments("lambda expression", "C.D1").WithLocation(21, 17), // (21,25): error CS1678: Parameter 1 is declared as type 'double' but should be 'ref int' // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamType, "x6").WithArguments("1", "", "double", "ref ", "int").WithLocation(21, 25), // (21,37): error CS1676: Parameter 2 must be declared with the 'out' keyword // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamRef, "y6").WithArguments("2", "out").WithLocation(21, 37), // (21,49): error CS1677: Parameter 3 should not be declared with the 'ref' keyword // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamExtraRef, "z6").WithArguments("3", "ref").WithLocation(21, 49), // (32,17): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'C.D1' because it has one or more out parameters // D1 q7 = delegate {}; Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, "delegate {}").WithArguments("C.D1").WithLocation(32, 17), // (34,9): error CS0246: The type or namespace name 'Frob' could not be found (are you missing a using directive or an assembly reference?) // Frob q8 = ()=>{}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Frob").WithArguments("Frob").WithLocation(34, 9), // (36,17): error CS1676: Parameter 1 must be declared with the 'out' keyword // D2 q9 = x9=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "x9").WithArguments("1", "out").WithLocation(36, 17), // (38,19): error CS1676: Parameter 1 must be declared with the 'ref' keyword // D1 q10 = (x10,y10,z10)=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "x10").WithArguments("1", "ref").WithLocation(38, 19), // (38,23): error CS1676: Parameter 2 must be declared with the 'out' keyword // D1 q10 = (x10,y10,z10)=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "y10").WithArguments("2", "out").WithLocation(38, 23), // (52,28): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Action q11 = ()=>{ return 1; }; Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(52, 28), // (54,26): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // Action q12 = ()=>1; Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(54, 26), // (56,42): warning CS0162: Unreachable code detected // Func<int> q13 = ()=>{ if (false) return 1; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(56, 42), // (56,27): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // Func<int> q13 = ()=>{ if (false) return 1; }; Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(56, 27), // (58,29): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Func<int> q14 = ()=>123.456; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "123.456").WithArguments("double", "int").WithLocation(58, 29), // (58,29): 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<int> q14 = ()=>123.456; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "123.456").WithArguments("lambda expression").WithLocation(58, 29), // (62,51): error CS0266: Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?) // Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1m").WithArguments("decimal", "double").WithLocation(62, 51), // (62,51): 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<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1m").WithArguments("lambda expression").WithLocation(62, 51), // (62,44): warning CS0162: Unreachable code detected // Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(62, 44), // (66,39): error CS1670: params is not valid in this context // Action<int[]> q16 = delegate (params int[] p) { }; Diagnostic(ErrorCode.ERR_IllegalParams, "params int[] p").WithLocation(66, 39), // (67,33): error CS1670: params is not valid in this context // Action<string[]> q17 = (params string[] s)=>{}; Diagnostic(ErrorCode.ERR_IllegalParams, "params string[] s").WithLocation(67, 33), // (68,45): error CS1670: params is not valid in this context // Action<int, double[]> q18 = (int x, params double[] s)=>{}; Diagnostic(ErrorCode.ERR_IllegalParams, "params double[] s").WithLocation(68, 45), // (70,34): error CS1593: Delegate 'Action' does not take 1 arguments // object q19 = new Action( (int x)=>{} ); Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int x)=>{}").WithArguments("System.Action", "1").WithLocation(70, 34), // (72,9): warning CS0436: The type 'Expression<T>' in '' conflicts with the imported type 'Expression<TDelegate>' in 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // Expression<int> ex1 = ()=>1; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Expression<int>").WithArguments("", "System.Linq.Expressions.Expression<T>", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Linq.Expressions.Expression<TDelegate>").WithLocation(72, 9), // (72,31): error CS0835: Cannot convert lambda to an expression tree whose type argument 'int' is not a delegate type // Expression<int> ex1 = ()=>1; Diagnostic(ErrorCode.ERR_ExpressionTreeMustHaveDelegate, "()=>1").WithArguments("int").WithLocation(72, 31) ); } [Fact] // 5368 public void TestLambdaErrors02() { string code = @" class C { void M() { System.Func<int, int> del = x => x + 1; } }"; var compilation = CreateCompilation(code); compilation.VerifyDiagnostics(); // no errors expected } [WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")] [Fact] public void TestLambdaErrors03() { string source = @" using System; interface I : IComparable<IComparable<I>> { } class C { static void Goo(Func<IComparable<I>> x) { } static void Goo(Func<I> x) {} static void M() { Goo(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(Func<IComparable<I>>)' and 'C.Goo(Func<I>)' // Goo(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(System.Func<System.IComparable<I>>)", "C.Goo(System.Func<I>)").WithLocation(12, 9)); } [WorkItem(18645, "https://github.com/dotnet/roslyn/issues/18645")] [Fact] public void LambdaExpressionTreesErrors() { string source = @" using System; using System.Linq.Expressions; class C { void M() { Expression<Func<int,int>> ex1 = () => 1; Expression<Func<int,int>> ex2 = (double d) => 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (9,41): error CS1593: Delegate 'Func<int, int>' does not take 0 arguments // Expression<Func<int,int>> ex1 = () => 1; Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => 1").WithArguments("System.Func<int, int>", "0").WithLocation(9, 41), // (10,41): error CS1661: Cannot convert lambda expression to type 'Expression<Func<int, int>>' because the parameter types do not match the delegate parameter types // Expression<Func<int,int>> ex2 = (double d) => 1; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double d) => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int, int>>").WithLocation(10, 41), // (10,49): error CS1678: Parameter 1 is declared as type 'double' but should be 'int' // Expression<Func<int,int>> ex2 = (double d) => 1; Diagnostic(ErrorCode.ERR_BadParamType, "d").WithArguments("1", "", "double", "", "int").WithLocation(10, 49)); } [WorkItem(539976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539976")] [Fact] public void LambdaArgumentToOverloadedDelegate() { var text = @"class W { delegate T Func<A0, T>(A0 a0); static int F(Func<short, int> f) { return 0; } static int F(Func<short, double> f) { return 1; } static int Main() { return F(c => c); } } "; var comp = CreateCompilation(Parse(text)); comp.VerifyDiagnostics(); } [WorkItem(528044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528044")] [Fact] public void MissingReferenceInOverloadResolution() { var text1 = @" using System; public static class A { public static void Goo(Func<B, object> func) { } public static void Goo(Func<C, object> func) { } } public class B { public Uri GetUrl() { return null; } } public class C { public string GetUrl() { return null; } }"; var comp1 = CreateCompilationWithMscorlib40( new[] { Parse(text1) }, new[] { TestMetadata.Net451.System }); var text2 = @" class Program { static void Main() { A.Goo(x => x.GetUrl()); } } "; var comp2 = CreateCompilationWithMscorlib40( new[] { Parse(text2) }, new[] { new CSharpCompilationReference(comp1) }); Assert.Equal(0, comp2.GetDiagnostics().Count()); } [WorkItem(528047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528047")] [Fact()] public void OverloadResolutionWithEmbeddedInteropType() { var text1 = @" using System; using System.Collections.Generic; using stdole; public static class A { public static void Goo(Func<X> func) { System.Console.WriteLine(""X""); } public static void Goo(Func<Y> func) { System.Console.WriteLine(""Y""); } } public delegate void X(List<IDispatch> addin); public delegate void Y(List<string> addin); "; var comp1 = CreateCompilation( Parse(text1), new[] { TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseDll); var text2 = @" public class Program { public static void Main() { A.Goo(() => delegate { }); } } "; var comp2 = CreateCompilation( Parse(text2), new MetadataReference[] { new CSharpCompilationReference(comp1), TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp2, expectedOutput: "Y").Diagnostics.Verify(); var comp3 = CreateCompilation( Parse(text2), new MetadataReference[] { comp1.EmitToImageReference(), TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp3, expectedOutput: "Y").Diagnostics.Verify(); } [WorkItem(6358, "DevDiv_Projects/Roslyn")] [Fact] public void InvalidExpressionInvolveLambdaOperator() { var text1 = @" class C { static void X() { int x=0; int y=0; if(x-=>*y) // CS1525 return; return; } } "; var comp = CreateCompilation(Parse(text1)); var errs = comp.GetDiagnostics(); Assert.True(0 < errs.Count(), "Diagnostics not empty"); Assert.True(0 < errs.Where(e => e.Code == 1525).Select(e => e).Count(), "Diagnostics contains CS1525"); } [WorkItem(540219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540219")] [Fact] public void OverloadResolutionWithStaticType() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Sub Goo(x as Action(Of String)) End Sub Sub Goo(x as Action(Of GC)) End Sub End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.Goo(x => { }); } } "; var metadataStream = new MemoryStream(); var emitResult = vbProject.Emit(metadataStream, options: new EmitOptions(metadataOnly: true)); Assert.True(emitResult.Success); var csProject = CreateCompilation( Parse(csSource), new[] { MetadataReference.CreateFromImage(metadataStream.ToImmutable()) }); Assert.Equal(0, csProject.GetDiagnostics().Count()); } [Fact] public void OverloadResolutionWithStaticTypeError() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Public Dim F As Action(Of GC) End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.F = x=>{}; } } "; var vbMetadata = vbProject.EmitToArray(options: new EmitOptions(metadataOnly: true)); var csProject = CreateCompilation(Parse(csSource), new[] { MetadataReference.CreateFromImage(vbMetadata) }); csProject.VerifyDiagnostics( // (6,15): error CS0721: 'GC': static types cannot be used as parameters // M.F = x=>{}; Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "x").WithArguments("System.GC").WithLocation(6, 15)); } [WorkItem(540251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540251")] [Fact] public void AttributesCannotBeUsedInAnonymousMethods() { var csSource = @" using System; class Program { static void Main() { const string message = ""The parameter is obsolete""; Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { }; } } "; var csProject = CreateCompilation(csSource); csProject.VerifyEmitDiagnostics( // (8,22): warning CS0219: The variable 'message' is assigned but its value is never used // const string message = "The parameter is obsolete"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "message").WithArguments("message").WithLocation(8, 22), // (9,35): error CS7014: Attributes are not valid in this context. // Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[ObsoleteAttribute(message)]").WithLocation(9, 35)); } [WorkItem(540263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540263")] [Fact] public void ErrorsInUnboundLambdas() { var csSource = @"using System; class Program { static void Main() { ((Func<int>)delegate { return """"; })(); ((Func<int>)delegate { })(); ((Func<int>)delegate { 1 / 0; })(); } } "; CreateCompilation(csSource).VerifyDiagnostics( // (7,39): error CS0029: Cannot implicitly convert type 'string' to 'int' // ((Func<int>)delegate { return ""; })(); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(7, 39), // (7,39): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // ((Func<int>)delegate { return ""; })(); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""""").WithArguments("anonymous method").WithLocation(7, 39), // (8,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // ((Func<int>)delegate { })(); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(8, 21), // (9,32): error CS0020: Division by constant zero // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_IntDivByZero, "1 / 0").WithLocation(9, 32), // (9,32): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_IllegalStatement, "1 / 0").WithLocation(9, 32), // (9,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(9, 21) ); } [WorkItem(540181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540181")] [Fact] public void ErrorInLambdaArgumentList() { var csSource = @"using System; class Program { public Program(string x) : this(() => x) { } static void Main(string[] args) { ((Action<string>)(f => Console.WriteLine(f)))(nulF); } }"; CreateCompilation(csSource).VerifyDiagnostics( // (5,37): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type // public Program(string x) : this(() => x) { } Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => x").WithArguments("lambda expression", "string").WithLocation(5, 37), // (8,55): error CS0103: The name 'nulF' does not exist in the current context // ((Action<string>)(f => Console.WriteLine(f)))(nulF); Diagnostic(ErrorCode.ERR_NameNotInContext, "nulF").WithArguments("nulF").WithLocation(8, 55)); } [WorkItem(541725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541725")] [Fact] public void DelegateCreationIsNotStatement() { var csSource = @" delegate void D(); class Program { public static void Main(string[] args) { D d = () => new D(() => { }); new D(()=>{}); } }"; // Though it is legal to have an object-creation-expression, because it might be useful // for its side effects, a delegate-creation-expression is not allowed as a // statement expression. CreateCompilation(csSource).VerifyDiagnostics( // (7,21): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // D d = () => new D(() => { }); Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(() => { })"), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // new D(()=>{}); Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(()=>{})")); } [WorkItem(542336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542336")] [Fact] public void ThisInStaticContext() { var csSource = @" delegate void D(); class Program { public static void Main(string[] args) { D d = () => { object o = this; }; } }"; CreateCompilation(csSource).VerifyDiagnostics( // (8,24): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // object o = this; Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this") ); } [WorkItem(542431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542431")] [Fact] public void LambdaHasMoreParametersThanDelegate() { var csSource = @" class C { static void Main() { System.Func<int> f = new System.Func<int>(r => 0); } }"; CreateCompilation(csSource).VerifyDiagnostics( // (6,51): error CS1593: Delegate 'System.Func<int>' does not take 1 arguments Diagnostic(ErrorCode.ERR_BadDelArgCount, "r => 0").WithArguments("System.Func<int>", "1")); } [Fact, WorkItem(529054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529054")] public void LambdaInDynamicCall() { var source = @" public class Program { static void Main() { dynamic b = new string[] { ""AA"" }; bool exists = System.Array.Exists(b, o => o != ""BB""); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,46): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // bool exists = System.Array.Exists(b, o => o != "BB"); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, @"o => o != ""BB""") ); } [Fact, WorkItem(529389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529389")] public void ParenthesizedLambdaInCastExpression() { var source = @" using System; using System.Collections.Generic; class Program { static void Main() { int x = 1; byte y = (byte) (x + x); Func<int> f1 = (() => { return 1; }); Func<int> f2 = (Func<int>) (() => { return 2; }); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>(). Where(e => e.Kind() == SyntaxKind.AddExpression).Single(); var tinfo = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); // Not byte Assert.Equal("int", tinfo.Type.ToDisplayString()); var exprs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>(); expr = exprs.First(); tinfo = model.GetTypeInfo(expr); conv = model.GetConversion(expr); Assert.True(conv.IsAnonymousFunction, "LambdaConversion"); Assert.Null(tinfo.Type); var sym = model.GetSymbolInfo(expr).Symbol; Assert.NotNull(sym); Assert.Equal(SymbolKind.Method, sym.Kind); Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind); expr = exprs.Last(); tinfo = model.GetTypeInfo(expr); conv = model.GetConversion(expr); Assert.True(conv.IsAnonymousFunction, "LambdaConversion"); Assert.Null(tinfo.Type); sym = model.GetSymbolInfo(expr).Symbol; Assert.NotNull(sym); Assert.Equal(SymbolKind.Method, sym.Kind); Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind); } [WorkItem(544594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544594")] [Fact] public void LambdaInEnumMemberDecl() { var csSource = @" public class TestClass { public enum Test { aa = ((System.Func<int>)(() => 1))() } Test MyTest = Test.aa; public static void Main() { } } "; CreateCompilation(csSource).VerifyDiagnostics( // (4,29): error CS0133: The expression being assigned to 'TestClass.Test.aa' must be constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "((System.Func<int>)(() => 1))()").WithArguments("TestClass.Test.aa"), // (5,10): warning CS0414: The field 'TestClass.MyTest' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "MyTest").WithArguments("TestClass.MyTest")); } [WorkItem(544932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544932")] [Fact] public void AnonymousLambdaInEnumSubtraction() { string source = @" class Test { enum E1 : byte { A = byte.MinValue, C = 1 } static void Main() { int j = ((System.Func<Test.E1>)(() => E1.A))() - E1.C; System.Console.WriteLine(j); } } "; string expectedOutput = @"255"; CompileAndVerify(new[] { source }, expectedOutput: expectedOutput); } [WorkItem(545156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545156")] [Fact] public void SpeculativelyBindOverloadResolution() { string source = @" using System; using System.Collections; using System.Collections.Generic; class Program { static void Main() { Goo(() => () => { var x = (IEnumerable<int>)null; return x; }); } static void Goo(Func<Func<IEnumerable>> x) { } static void Goo(Func<Func<IFormattable>> x) { } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); // Used to throw a NRE because of the ExpressionSyntax's null SyntaxTree. model.GetSpeculativeSymbolInfo( invocation.SpanStart, SyntaxFactory.ParseExpression("Goo(() => () => { var x = null; return x; })"), // cast removed SpeculativeBindingOption.BindAsExpression); } [WorkItem(545343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545343")] [Fact] public void LambdaUsingFieldInConstructor() { string source = @" using System; public class Derived { int field = 1; Derived() { int local = 2; // A lambda that captures a local and refers to an instance field. Action a = () => Console.WriteLine(""Local = {0}, Field = {1}"", local, field); // NullReferenceException if the ""this"" field of the display class hasn't been set. a(); } public static void Main() { Derived d = new Derived(); } }"; CompileAndVerify(source, expectedOutput: "Local = 2, Field = 1"); } [WorkItem(642222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642222")] [Fact] public void SpeculativelyBindOverloadResolutionAndInferenceWithError() { string source = @" using System;using System.Linq.Expressions; namespace IntellisenseBug { public class Program { void M(Mapper<FromData, ToData> mapper) { // Intellisense is broken here when you type . after the x: mapper.Map(x => x/* */. } } public class Mapper<TTypeFrom, TTypeTo> { public void Map<TPropertyFrom, TPropertyTo>( Expression<Func<TTypeFrom, TPropertyFrom>> from, Expression<Func<TTypeTo, TPropertyTo>> to) { } } public class FromData { public int Int { get; set; } public string String { get; set; } } public class ToData { public int Id { get; set; } public string Name { get; set; } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); // We don't actually require any particular diagnostics, but these are what we get. compilation.VerifyDiagnostics( // (10,36): error CS1001: Identifier expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (10,36): error CS1026: ) expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (10,36): error CS1002: ; expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_SemicolonExpected, "") ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var xReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<ExpressionSyntax>() .Where(e => e.ToFullString() == "x/* */") .Last(); var typeInfo = model.GetTypeInfo(xReference); Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("String")); } [WorkItem(722288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722288")] [Fact] public void CompletionInLambdaInIncompleteInvocation() { string source = @" using System; using System.Linq.Expressions; public class SomeType { public string SomeProperty { get; set; } } public class IntelliSenseError { public static void Test1<T>(Expression<Func<T, object>> expr) { Console.WriteLine(((MemberExpression)expr.Body).Member.Name); } public static void Test2<T>(Expression<Func<T, object>> expr, bool additionalParameter) { Test1(expr); } public static void Main() { Test2<SomeType>(o => o/* */. } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); // We don't actually require any particular diagnostics, but these are what we get. compilation.VerifyDiagnostics( // (21,37): error CS1001: Identifier expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (21,37): error CS1026: ) expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (21,37): error CS1002: ; expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_SemicolonExpected, "") ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var oReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<NameSyntax>() .Where(e => e.ToFullString() == "o/* */") .Last(); var typeInfo = model.GetTypeInfo(oReference); Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("SomeProperty")); } [WorkItem(871896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871896")] [Fact] public void Bug871896() { string source = @" using System.Threading; using System.Threading.Tasks; class TestDataPointBase { private readonly IVisualStudioIntegrationService integrationService; protected void TryGetDocumentId(CancellationToken token) { DocumentId documentId = null; if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) { } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var oReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<ExpressionSyntax>() .OrderByDescending(s => s.SpanStart); foreach (var name in oReference) { CSharpExtensions.GetSymbolInfo(model, name); } // We should get a bunch of errors, but no asserts. compilation.VerifyDiagnostics( // (6,22): error CS0246: The type or namespace name 'IVisualStudioIntegrationService' could not be found (are you missing a using directive or an assembly reference?) // private readonly IVisualStudioIntegrationService integrationService; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVisualStudioIntegrationService").WithArguments("IVisualStudioIntegrationService").WithLocation(6, 22), // (9,9): error CS0246: The type or namespace name 'DocumentId' could not be found (are you missing a using directive or an assembly reference?) // DocumentId documentId = null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "DocumentId").WithArguments("DocumentId").WithLocation(9, 9), // (10,25): error CS0117: 'System.Threading.Tasks.Task' does not contain a definition for 'Run' // if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) Diagnostic(ErrorCode.ERR_NoSuchMember, "Run").WithArguments("System.Threading.Tasks.Task", "Run").WithLocation(10, 25), // (10,14): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)").WithLocation(10, 14), // (6,54): warning CS0649: Field 'TestDataPointBase.integrationService' is never assigned to, and will always have its default value null // private readonly IVisualStudioIntegrationService integrationService; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "integrationService").WithArguments("TestDataPointBase.integrationService", "null").WithLocation(6, 54) ); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_01() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { var tmp = new C(); tmp.M((a, b) => c.Add); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular9); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (9,15): error CS1660: Cannot convert lambda expression to type 'IList<C>' because it is not a delegate type // tmp.M((a, b) => c.Add); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(a, b) => c.Add").WithArguments("lambda expression", "System.Collections.Generic.IList<C>").WithLocation(9, 15)); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body; var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_02() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { int tmp = c.Add; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer.Value; var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_03() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { var tmp = new C(); tmp.M((a, b) => c.Add); } static void M(System.Func<int, int, System.Action<C>> x) {} } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body; var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(); class C { static void MD(D d) { } static int i = 0; static void M() { MD(() => ref i); MD(() => { return ref i; }); MD(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceDelegateCreation() { var text = @" delegate ref int D(); class C { static int i = 0; static void M() { var d = new D(() => ref i); d = new D(() => { return ref i; }); d = new D(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceOverloadedDelegateType() { var text = @" delegate ref int D(); delegate int E(); class C { static void M(D d) { } static void M(E e) { } static int i = 0; static void M() { M(() => ref i); M(() => { return ref i; }); M(delegate { return ref i; }); M(() => i); M(() => { return i; }); M(delegate { return i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceArgumentBadRefReturn() { var text = @" delegate int E(); class C { static void ME(E e) { } static int i = 0; static void M() { ME(() => ref i); ME(() => { return ref i; }); ME(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (11,22): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(() => ref i); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(11, 22), // (12,20): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(() => { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(12, 20), // (13,23): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(delegate { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(13, 23)); } [Fact] public void RefLambdaInferenceDelegateCreationBadRefReturn() { var text = @" delegate int E(); class C { static int i = 0; static void M() { var e = new E(() => ref i); e = new E(() => { return ref i; }); e = new E(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (9,33): error CS8149: By-reference returns may only be used in by-reference returning methods. // var e = new E(() => ref i); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(9, 33), // (10,27): error CS8149: By-reference returns may only be used in by-reference returning methods. // e = new E(() => { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(10, 27), // (11,30): error CS8149: By-reference returns may only be used in by-reference returning methods. // e = new E(delegate { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(11, 30)); } [Fact] public void RefLambdaInferenceMixedByValueAndByRefReturns() { var text = @" delegate ref int D(); delegate int E(); class C { static void MD(D e) { } static void ME(E e) { } static int i = 0; static void M() { MD(() => { if (i == 0) { return ref i; } return i; }); ME(() => { if (i == 0) { return ref i; } return i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (18,13): error CS8150: By-value returns may only be used in by-value returning methods. // return i; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(18, 13), // (23,17): error CS8149: By-reference returns may only be used in by-reference returning methods. // return ref i; Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(23, 17)); } [WorkItem(1112875, "DevDiv")] [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")] [Fact] public void Bug1112875_1() { var comp = CreateCompilation(@" using System; class Program { static void Main() { ICloneable c = """"; Goo(() => (c.Clone()), null); } static void Goo(Action x, string y) { } static void Goo(Func<object> x, object y) { Console.WriteLine(42); } }", options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")] [Fact] public void Bug1112875_2() { var comp = CreateCompilation(@" class Program { void M() { var d = new System.Action(() => (new object())); } } "); comp.VerifyDiagnostics( // (6,41): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // var d = new System.Action(() => (new object())); Diagnostic(ErrorCode.ERR_IllegalStatement, "(new object())").WithLocation(6, 41)); } [WorkItem(1830, "https://github.com/dotnet/roslyn/issues/1830")] [Fact] public void FuncOfVoid() { var comp = CreateCompilation(@" using System; class Program { void M1<T>(Func<T> f) {} void Main(string[] args) { M1(() => { return System.Console.Beep(); }); } } "); comp.VerifyDiagnostics( // (8,27): error CS4029: Cannot return an expression of type 'void' // M1(() => { return System.Console.Beep(); }); Diagnostic(ErrorCode.ERR_CantReturnVoid, "System.Console.Beep()").WithLocation(8, 27) ); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_01() { var src = @" using System; class Program { static Func<Program, string> stuff() { return a => a. } } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,23): error CS1001: Identifier expected // return a => a. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 23), // (8,23): error CS1002: ; expected // return a => a. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 23) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_02() { var src = @" using System; class Program { static void stuff() { Func<Program, string> l = a => a. } } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,42): error CS1001: Identifier expected // Func<Program, string> l = a => a. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 42), // (8,42): error CS1002: ; expected // Func<Program, string> l = a => a. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 42) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_03() { var src = @" using System; class Program { static void stuff() { M1(a => a.); } static void M1(Func<Program, string> l){} } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,20): error CS1001: Identifier expected // M1(a => a.); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 20) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_04() { var src = @" using System; class Program { static void stuff() { var l = (Func<Program, string>) (a => a.); } } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,49): error CS1001: Identifier expected // var l = (Func<Program, string>) (a => a.); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 49) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact] [WorkItem(3826, "https://github.com/dotnet/roslyn/issues/3826")] public void ExpressionTreeSelfAssignmentShouldError() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<int, int>> x = y => y = y; } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (9,45): warning CS1717: Assignment made to same variable; did you mean to assign something else? // Expression<Func<int, int>> x = y => y = y; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y = y").WithLocation(9, 45), // (9,45): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> x = y => y = y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "y = y").WithLocation(9, 45)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2(default(Struct1))); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2(default(Struct1))); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(Struct1)").WithArguments("Struct1").WithLocation(8, 40)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructDefaultExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2(default)); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2(default)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 40)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructDefaultCastExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2((Struct1) default)); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,50): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2((Struct1) default)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 50)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructNewExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2(new Struct1())); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2(new Struct1())); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "new Struct1()").WithArguments("Struct1").WithLocation(8, 40)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructParamExpressionTree() { var text = @" using System.Linq.Expressions; public delegate void Delegate1(Struct1 s); public class Class1 { public void Method1() { Method((Struct1 s) => Method2()); } public void Method2() { } public static void Method(Expression<Delegate1> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,25): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Struct1 s) => Method2()); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "s").WithArguments("Struct1").WithLocation(9, 25)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructParamLambda() { var text = @" public delegate void Delegate1(Struct1 s); public class Class1 { public void Method1() { Method((Struct1 s) => Method2()); } public void Method2() { } public static void Method(Delegate1 expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void TypedReferenceExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method(() => Method2(default)); } public void Method2(TypedReference tr) { } public static void Method(Expression<Action> expression) { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,30): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Method(() => Method2(default)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("TypedReference").WithLocation(8, 30)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void TypedReferenceParamExpressionTree() { var text = @" using System; using System.Linq.Expressions; public delegate void Delegate1(TypedReference tr); public class Class1 { public void Method1() { Method((TypedReference tr) => Method2()); } public void Method2() { } public static void Method(Expression<Delegate1> expression) { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,32): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Method((TypedReference tr) => Method2()); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "tr").WithArguments("TypedReference").WithLocation(9, 32)); } [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")] public void ReturnInferenceCache_Dynamic_vs_Object_01() { var source = @" using System; using System.Collections; using System.Collections.Generic; public static class Program { public static void Main(string[] args) { IEnumerable<dynamic> dynX = null; // CS1061 'object' does not contain a definition for 'Text'... // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic> var result = dynX.Select(_ => _.Text); } public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector) { throw new NotImplementedException(); } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector) { System.Console.WriteLine(""Select<T, S>""); return null; } } public interface IColumn { } "; var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: "Select<T, S>"); } [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")] public void ReturnInferenceCache_Dynamic_vs_Object_02() { var source = @" using System; using System.Collections; using System.Collections.Generic; public static class Program { public static void Main(string[] args) { IEnumerable<dynamic> dynX = null; // CS1061 'object' does not contain a definition for 'Text'... // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic> var result = dynX.Select(_ => _.Text); } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector) { System.Console.WriteLine(""Select<T, S>""); return null; } public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector) { throw new NotImplementedException(); } } public interface IColumn { } "; var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: "Select<T, S>"); } [Fact, WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void SyntaxAndSemanticErrorInLambda() { var source = @" using System; class C { public static void Main(string[] args) { Action a = () => { new X().ToString() }; a(); } } "; CreateCompilation(source).VerifyDiagnostics( // (7,47): error CS1002: ; expected // Action a = () => { new X().ToString() }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 47), // (7,32): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // Action a = () => { new X().ToString() }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(7, 32) ); } [Fact, WorkItem(4527, "https://github.com/dotnet/roslyn/issues/4527")] public void AnonymousMethodExpressionWithoutParameterList() { var source = @" using System; using System.Threading.Tasks; namespace RoslynAsyncDelegate { class Program { static EventHandler MyEvent; static void Main(string[] args) { MyEvent += async delegate { await Task.Delay(0); }; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AnonymousMethodExpression)).Single(); Assert.Equal("async delegate { await Task.Delay(0); }", node1.ToString()); Assert.Equal("void System.EventHandler.Invoke(System.Object sender, System.EventArgs e)", model.GetTypeInfo(node1).ConvertedType.GetMembers("Invoke").Single().ToTestDisplayString()); var lambdaParameters = ((IMethodSymbol)(model.GetSymbolInfo(node1)).Symbol).Parameters; Assert.Equal("System.Object <p0>", lambdaParameters[0].ToTestDisplayString()); Assert.Equal("System.EventArgs <p1>", lambdaParameters[1].ToTestDisplayString()); CompileAndVerify(compilation); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError01() { var source = @"using System.Linq; class C { C() { string.Empty.Select(() => { new Unbound1 }); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,58): error CS1526: A new expression requires (), [], or {} after type // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_BadNewExpr, "}").WithLocation(2, 58), // (2,58): error CS1002: ; expected // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 58), // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?) // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError02() { var source = @"using System.Linq; class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,62): error CS1002: ; expected // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 62), // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?) // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError03() { var source = @"using System.Linq; class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,61): error CS1003: Syntax error, ',' expected // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_SyntaxError, "Unbound2").WithArguments(",", "").WithLocation(2, 61), // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52), // (2,61): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 61), // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError04() { var source = @"using System.Linq; class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52), // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError05() { var source = @"using System.Linq; class C { C() { Unbound2.Select(x => Unbound1); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,17): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { Unbound2.Select(x => Unbound1); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 17), // (2,38): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { Unbound2.Select(x => Unbound1); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 38) ); } [Fact] [WorkItem(4480, "https://github.com/dotnet/roslyn/issues/4480")] public void TestLambdaWithError06() { var source = @"class Program { static void Main(string[] args) { // completion should work even in a syntactically invalid lambda var handler = new MyDelegateType((s, e) => { e. }); } } public delegate void MyDelegateType( object sender, MyArgumentType e ); public class MyArgumentType { public int SomePublicMember; }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source) .VerifyDiagnostics( // var handler = new MyDelegateType((s, e) => { e. }); Diagnostic(ErrorCode.ERR_IdentifierExpected, "}").WithLocation(6, 57), // (6,57): error CS1002: ; expected // var handler = new MyDelegateType((s, e) => { e. }); Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(6, 57) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("e", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal("MyArgumentType", typeInfo.Type.Name); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.NotEmpty(typeInfo.Type.GetMembers("SomePublicMember")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError07() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var parameter = new List<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public static class Enumerable { public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue) { return default(TSource); } public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource defaultValue) { return default(TSource); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (9,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError08() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var parameter = new List<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public static class Enumerable { public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, params TSource[] defaultValue) { return default(TSource); } public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, params TSource[] defaultValue) { return default(TSource); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (9,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError09() { var source = @"using System; public static class Program { public static void Main() { var parameter = new MyList<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public class MyList<TSource> { public TSource FirstOrDefault(TSource defaultValue) { return default(TSource); } public TSource FirstOrDefault(Func<TSource, bool> predicate, TSource defaultValue) { return default(TSource); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError10() { var source = @"using System; public static class Program { public static void Main() { var parameter = new MyList<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public class MyList<TSource> { public TSource FirstOrDefault(params TSource[] defaultValue) { return default(TSource); } public TSource FirstOrDefault(Func<TSource, bool> predicate, params TSource[] defaultValue) { return default(TSource); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(557, "https://github.com/dotnet/roslyn/issues/557")] public void TestLambdaWithError11() { var source = @"using System.Linq; public static class Program { public static void Main() { var x = new { X = """".Select(c => c. Y = 0, }; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("c", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Struct, typeInfo.Type.TypeKind); Assert.Equal("Char", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("IsHighSurrogate")); // check it is the char we know and love } [Fact] [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")] public void TestLambdaWithError12() { var source = @"using System.Linq; class Program { static void Main(string[] args) { var z = args.Select(a => a. var goo = } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("a", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] [Fact] public void TestLambdaWithError13() { // These tests ensure we attempt to perform type inference and bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is more than one method in the method group. // See https://github.com/dotnet/roslyn/issues/11901 for the case of one method in the group var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1(x => x, 1); // too many args t.X2(x => x); // too few args t.M2(string.Empty, x => x, 1); // too many args t.M3(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} // Ensure we have more than one method in the method group public void M2() {} public void M3() {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; // Ensure we have more than one method in the method group public static void X1(this object self) {} public static void X2(this object self) {} } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")] public void TestLambdaWithError15() { // These tests ensure we attempt to perform type inference and bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is exactly one method in the method group. var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1(x => x, 1); // too many args t.X2(x => x); // too few args t.M2(string.Empty, x => x, 1); // too many args t.M3(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")] public void TestLambdaWithError16() { // These tests ensure we use the substituted method to bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is exactly one method in the method group. var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1<string>(x => x, 1); // too many args t.X2<string>(x => x); // too few args t.M2<string>(string.Empty, x => x, 1); // too many args t.M3<string>(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError17() { var source = @"using System; class Program { static void Main(string[] args) { Ma(action: (x, y) => x.ToString(), t: string.Empty); Mb(action: (x, y) => x.ToString(), t: string.Empty); } static void Ma<T>(T t, Action<T, T, int> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mb() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError18() { var source = @"using System; class Program { static void Main(string[] args) { Ma(string.Empty, (x, y) => x.ToString()); Mb(string.Empty, (x, y) => x.ToString()); } static void Ma<T>(T t, Action<T, T, int> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mb() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError19() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { Ma(string.Empty, (x, y) => x.ToString()); Mb(string.Empty, (x, y) => x.ToString()); Mc(string.Empty, (x, y) => x.ToString()); } static void Ma<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mc<T>(T t, Expression<Action<T, T, int>> action) { } static void Mc() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } // See MaxParameterListsForErrorRecovery. [Fact] public void BuildArgumentsForErrorRecovery_ManyOverloads() { BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery - 1, tooMany: false); BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery, tooMany: true); } private void BuildArgumentsForErrorRecovery_ManyOverloads_Internal(int n, bool tooMany) { var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } builder.Append( @"class A { } class B { } class C { void M() { F(1, (t, a, b, c) => { }); var o = this[(a, b, c) => { }]; } "); // Too few parameters. AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, C{i}> a) {{ }}"); AppendLines(builder, n, i => $" object this[Action<A, C{i}> a] => {i}"); // Type inference failure. AppendLines(builder, n, i => $" void F<T, U>(T t, Action<T, U, C{i}> a) where U : T {{ }}"); // Too many parameters. AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, B, C, C{i}> a) {{ }}"); AppendLines(builder, n, i => $" object this[Action<A, B, C, C{i}> a] => {i}"); builder.AppendLine("}"); var source = builder.ToString(); var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambdas = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().ToArray(); // F(1, (t, a, b, c) => { }); var lambda = lambdas[0]; var parameters = lambda.ParameterList.Parameters; var parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]); Assert.False(parameter.Type.IsErrorType()); Assert.Equal("System.Int32 t", parameter.ToTestDisplayString()); parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[1]); Assert.False(parameter.Type.IsErrorType()); Assert.Equal("A a", parameter.ToTestDisplayString()); parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[3]); Assert.Equal(tooMany, parameter.Type.IsErrorType()); Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString()); // var o = this[(a, b, c) => { }]; lambda = lambdas[1]; parameters = lambda.ParameterList.Parameters; parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]); Assert.False(parameter.Type.IsErrorType()); Assert.Equal("A a", parameter.ToTestDisplayString()); parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[2]); Assert.Equal(tooMany, parameter.Type.IsErrorType()); Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString()); } private static void AppendLines(StringBuilder builder, int n, Func<int, string> getLine) { for (int i = 0; i < n; i++) { builder.AppendLine(getLine(i)); } } [Fact] [WorkItem(13797, "https://github.com/dotnet/roslyn/issues/13797")] public void DelegateAsAction() { var source = @" using System; public static class C { public static void M() => Dispatch(delegate { }); public static T Dispatch<T>(Func<T> func) => default(T); public static void Dispatch(Action func) { } }"; var comp = CreateCompilation(source); CompileAndVerify(comp); } [Fact, WorkItem(278481, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=278481")] public void LambdaReturningNull_1() { var src = @" public static class ExtensionMethods { public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Linq.IQueryable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector, System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) { return null; } public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Linq.IQueryable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector, System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector) { System.Console.WriteLine(""1""); return null; } public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Collections.Generic.IEnumerable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> fullResultSelector, System.Func<TOuter, TResult> partialResultSelector) { System.Console.WriteLine(""2""); return null; } public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Collections.Generic.IEnumerable<TOuter> outerQueryable, System.Collections.Generic.IEnumerable<TInner> innerQueryable, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> resultSelector) { return null; } } partial class C { public static void Main() { System.Linq.IQueryable<A> outerValue = null; System.Linq.IQueryable<B> innerValues = null; outerValue.LeftOuterJoin(innerValues, co => co.id, coa => coa.id, (co, coa) => null, co => co); } } class A { public int id=2; } class B { public int id = 2; }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "1"); } [Fact, WorkItem(296550, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296550")] public void LambdaReturningNull_2() { var src = @" class Test1<T> { public void M1(System.Func<T> x) {} public void M1<S>(System.Func<S> x) {} public void M2<S>(System.Func<S> x) {} public void M2(System.Func<T> x) {} } class Test2 : Test1<System.> { void Main() { M1(()=> null); M2(()=> null); } } "; var comp = CreateCompilation(src, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (10,32): error CS1001: Identifier expected // class Test2 : Test1<System.> Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(10, 32) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void LambdaSquigglesArea() { var src = @" class C { void M() { System.Func<bool, System.Action<bool>> x = x1 => x2 => { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,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 // System.Func<bool, System.Action<bool>> x = x1 => x2 => Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x2 =>").WithArguments("lambda expression").WithLocation(6, 58) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void LambdaSquigglesAreaInAsync() { var src = @" class C { void M() { System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 => { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,93): error CS4010: Cannot convert async lambda expression to delegate type 'Task<Action<bool>>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Task<Action<bool>>'. // System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 => Diagnostic(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, "x2 =>").WithArguments("lambda expression", "System.Threading.Tasks.Task<System.Action<bool>>").WithLocation(6, 93), // (6,90): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 => Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 90) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void DelegateSquigglesArea() { var src = @" class C { void M() { System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2) { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,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 // System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2) Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate(bool x2)").WithArguments("lambda expression").WithLocation(6, 58) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void DelegateWithoutArgumentsSquigglesArea() { var src = @" class C { void M() { System.Func<bool, System.Action> x = x1 => delegate { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,52): 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 // System.Func<bool, System.Action> x = x1 => delegate Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate").WithArguments("lambda expression").WithLocation(6, 52) ); } [Fact] public void ThrowExpression_Lambda() { var src = @"using System; class C { public static void Main() { Action a = () => throw new Exception(""1""); try { a(); } catch (Exception ex) { Console.Write(ex.Message); } Func<int, int> b = x => throw new Exception(""2""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } b = (int x) => throw new Exception(""3""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } b = (x) => throw new Exception(""4""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "1234"); } [Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] public void InMalformedEmbeddedStatement_01() { var source = @" class Program { void method1() { if (method2()) .Any(b => b.ContentType, out var chars) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single(); var model = comp.GetSemanticModel(tree); Assert.Equal("ContentType", contentType.ToString()); Assert.Null(model.GetSymbolInfo(contentType).Symbol); Assert.Equal(TypeKind.Error, model.GetTypeInfo(contentType).Type.TypeKind); ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single(); model = comp.GetSemanticModel(tree); Assert.Equal("b", b.ToString()); ISymbol symbol = model.GetSymbolInfo(b).Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("? b", symbol.ToTestDisplayString()); Assert.Equal(TypeKind.Error, model.GetTypeInfo(b).Type.TypeKind); ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); model = comp.GetSemanticModel(tree); symbol = model.GetDeclaredSymbol(parameterSyntax); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("? b", symbol.ToTestDisplayString()); } [Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] public void InMalformedEmbeddedStatement_02() { var source = @" class Program { void method1() { if (method2()) .Any(b => b.ContentType, out var chars) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single(); var model = comp.GetSemanticModel(tree); Assert.Equal("ContentType", contentType.ToString()); var lambda = (IMethodSymbol)model.GetEnclosingSymbol(contentType.SpanStart); Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind); ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single(); model = comp.GetSemanticModel(tree); Assert.Equal("b", b.ToString()); lambda = (IMethodSymbol)model.GetEnclosingSymbol(b.SpanStart); Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind); model = comp.GetSemanticModel(tree); ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); Assert.Equal("void Program.method1()", model.GetEnclosingSymbol(parameterSyntax.SpanStart).ToTestDisplayString()); } [Fact] public void ShadowNames_Local() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M() { Action a1 = () => { object x = 0; }; // local Action<string> a2 = x => { }; // parameter Action<string> a3 = (string x) => { }; // parameter object x = null; Action a4 = () => { void x() { } }; // method Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = () => { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36), // (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = x => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29), // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a3 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37), // (13,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a4 = () => { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(13, 34), // (14,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(14, 38)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Parameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static Action<object> F = (object x) => { Action a1 = () => { object x = 0; }; // local Action<string> a2 = x => { }; // parameter Action<string> a3 = (string x) => { }; // parameter Action a4 = () => { void x() { } }; // method Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable }; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = () => { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36), // (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = x => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29), // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a3 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37), // (13,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 38)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_TypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M<x>() { Action a1 = () => { object x = 0; }; // local Action<string> a2 = x => { }; // parameter Action<string> a3 = (string x) => { }; // parameter Action a4 = () => { void x() { } }; // method Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,36): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a1 = () => { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 36), // (10,29): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> a2 = x => { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 29), // (11,37): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> a3 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 37), // (12,34): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a4 = () => { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(12, 34), // (13,38): error CS1948: The range variable 'x' cannot have the same name as a method type parameter // Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(13, 38)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_QueryParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void Main(string[] args) { _ = from x in args select (Action)(() => { object x = 0; }); // local _ = from x in args select (Action<string>)(x => { }); // parameter _ = from x in args select (Action<string>)((string x) => { }); // parameter _ = from x in args select (Action)(() => { void x() { } }); // method _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,59): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // _ = from x in args select (Action)(() => { object x = 0; }); // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 59), // (10,52): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // _ = from x in args select (Action<string>)(x => { }); // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 52), // (11,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // _ = from x in args select (Action<string>)((string x) => { }); // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 60), // (13,61): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 61)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Local_Delegate() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M() { object x = null; Action a1 = delegate() { object x = 0; }; // local Action<string> a2 = delegate(string x) { }; // parameter Action a3 = delegate() { void x() { } }; // method Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (10,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = delegate() { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 41), // (11,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = delegate(string x) { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 45), // (12,39): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a3 = delegate() { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 39), // (13,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 43)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Parameter_Delegate() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static Action<object> F = (object x) => { Action a1 = delegate() { object x = 0; }; // local Action<string> a2 = delegate(string x) { }; // parameter Action a3 = delegate() { void x() { } }; // method Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable }; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = delegate() { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 41), // (10,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = delegate(string x) { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 45), // (12,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 43)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_TypeParameter_Delegate() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M<x>() { Action a1 = delegate() { object x = 0; }; // local Action<string> a2 = delegate(string x) { }; // parameter Action a3 = delegate() { void x() { } }; // method Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,41): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a1 = delegate() { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 41), // (10,45): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> a2 = delegate(string x) { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 45), // (11,39): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a3 = delegate() { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 39), // (12,43): error CS1948: The range variable 'x' cannot have the same name as a method type parameter // Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 43)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LambdaInsideLambda() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M<T>(object x) { Action a1 = () => { Action b1 = () => { object x = 1; }; // local Action<string> b2 = (string x) => { }; // parameter }; Action a2 = () => { Action b3 = () => { object T = 3; }; // local Action<string> b4 = T => { }; // parameter }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (10,40): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action b1 = () => { object x = 1; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 40), // (11,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> b2 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 41), // (15,40): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action b3 = () => { object T = 3; }; // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 40), // (16,33): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> b4 = T => { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(16, 33)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Underscore_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, Func<int, int>> f = _ => _ => _; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,44): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, Func<int, int>> f = _ => _ => _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 44)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Underscore_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, int, int> f = (_, _) => 0; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,37): error CS8370: Feature 'lambda discard parameters' is not available in C# 7.3. Please use language version 9.0 or greater. // Func<int, int, int> f = (_, _) => 0; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "_").WithArguments("lambda discard parameters", "9.0").WithLocation(8, 37)); comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void ShadowNames_Nested_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, Func<int, Func<int, int>>> f = x => x => x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,55): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, Func<int, Func<int, int>>> f = x => x => x => x; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 55), // (8,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, Func<int, Func<int, int>>> f = x => x => x => x; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 60)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Nested_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,87): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 87), // (8,94): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(8, 94), // (8,97): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 97)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LambdaInsideLocalFunction_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { void F1() { object x = null; Action a1 = () => { int x = 0; }; } void F2<T>() { Action a2 = () => { int T = 0; }; } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = () => { int x = 0; }; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37), // (15,37): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a2 = () => { int T = 0; }; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 37)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LambdaInsideLocalFunction_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M<T>() { object x = null; void F() { Action<int> a1 = (int x) => { Action b1 = () => { int T = 0; }; }; Action a2 = () => { int x = 0; Action<int> b2 = (int T) => { }; }; } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (11,35): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int> a1 = (int x) => Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 35), // (13,41): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action b1 = () => { int T = 0; }; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(13, 41), // (17,21): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x = 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(17, 21), // (18,39): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<int> b2 = (int T) => { }; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(18, 39)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void LambdaAttributes_01() { var sourceA = @"using System; class A : Attribute { } class B : Attribute { } partial class Program { static Delegate D1() => (Action)([A] () => { }); static Delegate D2(int x) => (Func<int, int, int>)((int y, [A][B] int z) => x); static Delegate D3() => (Action<int, object>)(([A]_, y) => { }); Delegate D4() => (Func<int>)([return: A][B] () => GetHashCode()); }"; var sourceB = @"using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; partial class Program { static string GetAttributeString(object a) { return a.GetType().FullName; } static void Report(Delegate d) { var m = d.Method; var forMethod = ToString(""method"", m.GetCustomAttributes(inherit: false)); var forReturn = ToString(""return"", m.ReturnTypeCustomAttributes.GetCustomAttributes(inherit: false)); var forParameters = ToString(""parameter"", m.GetParameters().SelectMany(p => p.GetCustomAttributes(inherit: false))); Console.WriteLine(""{0}:{1}{2}{3}"", m.Name, forMethod, forReturn, forParameters); } static string ToString(string target, IEnumerable<object> attributes) { var builder = new StringBuilder(); foreach (var attribute in attributes) builder.Append($"" [{target}: {attribute}]""); return builder.ToString(); } static void Main() { Report(D1()); Report(D2(0)); Report(D3()); Report(new Program().D4()); } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>(); var pairs = exprs.Select(e => (e, model.GetSymbolInfo(e).Symbol)).ToArray(); var expectedAttributes = new[] { "[A] () => { }: [method: A]", "(int y, [A][B] int z) => x: [parameter: A] [parameter: B]", "([A]_, y) => { }: [parameter: A]", "[return: A][B] () => GetHashCode(): [method: B] [return: A]", }; AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesInternal(p.Item1, p.Item2))); AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesPublic(p.Item1, p.Item2))); CompileAndVerify(comp, expectedOutput: @"<D1>b__0_0: [method: A] <D2>b__0: [parameter: A] [parameter: B] <D3>b__2_0: [parameter: A] <D4>b__3_0: [method: System.Runtime.CompilerServices.CompilerGeneratedAttribute] [method: B] [return: A]"); static string getAttributesInternal(LambdaExpressionSyntax expr, ISymbol symbol) { var method = symbol.GetSymbol<MethodSymbol>(); return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes())); } static string getAttributesPublic(LambdaExpressionSyntax expr, ISymbol symbol) { var method = (IMethodSymbol)symbol; return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes())); } static string format(LambdaExpressionSyntax expr, IEnumerable<object> methodAttributes, IEnumerable<object> returnAttributes, IEnumerable<object> parameterAttributes) { var forMethod = toString("method", methodAttributes); var forReturn = toString("return", returnAttributes); var forParameters = toString("parameter", parameterAttributes); return $"{expr}:{forMethod}{forReturn}{forParameters}"; } static string toString(string target, IEnumerable<object> attributes) { var builder = new StringBuilder(); foreach (var attribute in attributes) builder.Append($" [{target}: {attribute}]"); return builder.ToString(); } } [Fact] public void LambdaAttributes_02() { var source = @"using System; class AAttribute : Attribute { } class BAttribute : Attribute { } class C { static void Main() { Action<object, object> a; a = [A, B] (x, y) => { }; a = ([A] x, [B] y) => { }; a = (object x, [A][B] object y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,13): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = [A, B] (x, y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A, B]").WithArguments("lambda attributes", "10.0").WithLocation(9, 13), // (10,14): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = ([A] x, [B] y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(10, 14), // (10,21): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = ([A] x, [B] y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(10, 21), // (11,24): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = (object x, [A][B] object y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(11, 24), // (11,27): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = (object x, [A][B] object y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(11, 27)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void LambdaAttributes_03() { var source = @"using System; class AAttribute : Attribute { } class BAttribute : Attribute { } class C { static void Main() { Action<object, object> a = delegate (object x, [A][B] object y) { }; Func<object, object> f = [A][B] x => x; } }"; var expectedDiagnostics = new[] { // (8,56): error CS7014: Attributes are not valid in this context. // Action<object, object> a = delegate (object x, [A][B] object y) { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 56), // (8,59): error CS7014: Attributes are not valid in this context. // Action<object, object> a = delegate (object x, [A][B] object y) { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[B]").WithLocation(8, 59), // (9,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list. // Func<object, object> f = [A][B] x => x; Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[A]").WithLocation(9, 34), // (9,37): error CS8916: Attributes on lambda expressions require a parenthesized parameter list. // Func<object, object> f = [A][B] x => x; Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[B]").WithLocation(9, 37) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaAttributes_04() { var sourceA = @"namespace N1 { class A1Attribute : System.Attribute { } } namespace N2 { class A2Attribute : System.Attribute { } }"; var sourceB = @"using N1; using N2; class Program { static void Main() { System.Action a1 = [A1] () => { }; System.Action<object> a2 = ([A2] object obj) => { }; } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void LambdaAttributes_05() { var source = @"class Program { static void Main() { System.Action a1 = [A1] () => { }; System.Func<object> a2 = [return: A2] () => null; System.Action<object> a3 = ([A3] object obj) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,29): error CS0246: The type or namespace name 'A1Attribute' could not be found (are you missing a using directive or an assembly reference?) // System.Action a1 = [A1] () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1Attribute").WithLocation(5, 29), // (5,29): error CS0246: The type or namespace name 'A1' could not be found (are you missing a using directive or an assembly reference?) // System.Action a1 = [A1] () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1").WithLocation(5, 29), // (6,43): error CS0246: The type or namespace name 'A2Attribute' could not be found (are you missing a using directive or an assembly reference?) // System.Func<object> a2 = [return: A2] () => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2Attribute").WithLocation(6, 43), // (6,43): error CS0246: The type or namespace name 'A2' could not be found (are you missing a using directive or an assembly reference?) // System.Func<object> a2 = [return: A2] () => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2").WithLocation(6, 43), // (7,38): error CS0246: The type or namespace name 'A3Attribute' could not be found (are you missing a using directive or an assembly reference?) // System.Action<object> a3 = ([A3] object obj) => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3Attribute").WithLocation(7, 38), // (7,38): error CS0246: The type or namespace name 'A3' could not be found (are you missing a using directive or an assembly reference?) // System.Action<object> a3 = ([A3] object obj) => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3").WithLocation(7, 38)); } [Fact] public void LambdaAttributes_06() { var source = @"using System; class AAttribute : Attribute { public AAttribute(Action a) { } } [A([B] () => { })] class BAttribute : Attribute { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,2): error CS0181: Attribute constructor parameter 'a' has type 'Action', which is not a valid attribute parameter type // [A([B] () => { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "System.Action").WithLocation(6, 2)); } [Fact] public void LambdaAttributes_BadAttributeLocation() { var source = @"using System; [AttributeUsage(AttributeTargets.Property)] class PropAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] class MethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.ReturnValue)] class ReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] class ParamAttribute : Attribute { } [AttributeUsage(AttributeTargets.GenericParameter)] class TypeParamAttribute : Attribute { } class Program { static void Main() { Action<object> a = [Prop] // 1 [Return] // 2 [Method] [return: Prop] // 3 [return: Return] [return: Method] // 4 ( [Param] [TypeParam] // 5 object o) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (23,14): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [Prop] // 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(23, 14), // (24,14): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations. // [Return] // 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(24, 14), // (26,22): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [return: Prop] // 3 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(26, 22), // (28,22): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations. // [return: Method] // 4 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(28, 22), // (31,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations. // [TypeParam] // 5 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(31, 14)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lambda = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var symbol = (IMethodSymbol)model.GetSymbolInfo(lambda).Symbol; Assert.NotNull(symbol); verifyAttributes(symbol.GetAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute"); verifyAttributes(symbol.GetReturnTypeAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute"); verifyAttributes(symbol.Parameters[0].GetAttributes(), "ParamAttribute", "TypeParamAttribute"); void verifyAttributes(ImmutableArray<AttributeData> attributes, params string[] expectedAttributeNames) { var actualAttributes = attributes.SelectAsArray(a => a.AttributeClass.GetSymbol()); var expectedAttributes = expectedAttributeNames.Select(n => comp.GetTypeByMetadataName(n)); AssertEx.Equal(expectedAttributes, actualAttributes); } } [Fact] public void LambdaAttributes_AttributeSemanticModel() { var source = @"using System; class AAttribute : Attribute { } class BAttribute : Attribute { } class CAttribute : Attribute { } class DAttribute : Attribute { } class Program { static void Main() { Action a = [A] () => { }; Func<object> b = [return: B] () => null; Action<object> c = ([C] object obj) => { }; Func<object, object> d = [D] x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (13,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list. // Func<object, object> d = [D] x => x; Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[D]").WithLocation(13, 34)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>(); var actualAttributes = attributeSyntaxes.Select(a => model.GetSymbolInfo(a).Symbol.GetSymbol<MethodSymbol>()).ToImmutableArray(); var expectedAttributes = new[] { "AAttribute", "BAttribute", "CAttribute", "DAttribute" }.Select(a => comp.GetTypeByMetadataName(a).InstanceConstructors.Single()).ToImmutableArray(); AssertEx.Equal(expectedAttributes, actualAttributes); } [Theory] [InlineData("Action a = [A] () => { };")] [InlineData("Func<object> f = [return: A] () => null;")] [InlineData("Action<int> a = ([A] int i) => { };")] public void LambdaAttributes_SpeculativeSemanticModel(string statement) { string source = $@"using System; class AAttribute : Attribute {{ }} class Program {{ static void Main() {{ {statement} }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var a = (IdentifierNameSyntax)tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name; Assert.Equal("A", a.Identifier.Text); var attrInfo = model.GetSymbolInfo(a); var attrType = comp.GetMember<NamedTypeSymbol>("AAttribute").GetPublicSymbol(); var attrCtor = attrType.GetMember(".ctor"); Assert.Equal(attrCtor, attrInfo.Symbol); // Assert that this is also true for the speculative semantic model var newTree = SyntaxFactory.ParseSyntaxTree(source + " "); var m = newTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model)); a = (IdentifierNameSyntax)newTree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name; Assert.Equal("A", a.Identifier.Text); // If we aren't using the right binder here, the compiler crashes going through the binder factory var info = model.GetSymbolInfo(a); // This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135 Assert.Equal(attrType, info.Symbol); } [Fact] public void LambdaAttributes_DisallowedAttributes() { var source = @"using System; using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : Attribute { } public class IsUnmanagedAttribute : Attribute { } public class IsByRefLikeAttribute : Attribute { } public class NullableContextAttribute : Attribute { public NullableContextAttribute(byte b) { } } } class Program { static void Main() { Action a = [IsReadOnly] // 1 [IsUnmanaged] // 2 [IsByRefLike] // 3 [Extension] // 4 [NullableContext(0)] // 5 () => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (15,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [IsReadOnly] // 1 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(15, 14), // (16,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] // 2 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(16, 14), // (17,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [IsByRefLike] // 3 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(17, 14), // (18,14): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] // 4 Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(18, 14), // (19,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage. // [NullableContext(0)] // 5 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(19, 14)); } [Fact] public void LambdaAttributes_DisallowedSecurityAttributes() { var source = @"using System; using System.Security; class Program { static void Main() { Action a = [SecurityCritical] // 1 [SecuritySafeCriticalAttribute] // 2 async () => { }; // 3 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,14): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method. // [SecurityCritical] // 1 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(8, 14), // (9,14): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method. // [SecuritySafeCriticalAttribute] // 2 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(9, 14), // (10,22): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async () => { }; // 3 Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(10, 22)); } [Fact] public void LambdaAttributes_ObsoleteAttribute() { var source = @"using System; class Program { static void Report(Action a) { foreach (var attribute in a.Method.GetCustomAttributes(inherit: false)) Console.Write(attribute); } static void Main() { Report([Obsolete] () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.ObsoleteAttribute"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal("System.ObsoleteAttribute", symbol.GetAttributes().Single().ToString()); } [Fact] public void LambdaParameterAttributes_Conditional() { var source = @"using System; using System.Diagnostics; class Program { static void Report(Action a) { } static void Main() { Report([Conditional(""DEBUG"")] static () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,17): error CS0577: The Conditional attribute is not valid on 'lambda expression' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // Report([Conditional("DEBUG")] static () => { }); Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional(""DEBUG"")").WithArguments("lambda expression").WithLocation(10, 17)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single(); Assert.Equal(new[] { "DEBUG" }, lambda.GetAppliedConditionalSymbols()); } [Fact] public void LambdaAttributes_WellKnownAttributes() { var sourceA = @"using System; using System.Runtime.InteropServices; using System.Security; class Program { static void Main() { Action a1 = [DllImport(""MyModule.dll"")] static () => { }; Action a2 = [DynamicSecurityMethod] () => { }; Action a3 = [SuppressUnmanagedCodeSecurity] () => { }; Func<object> a4 = [return: MarshalAs((short)0)] () => null; } }"; var sourceB = @"namespace System.Security { internal class DynamicSecurityMethodAttribute : Attribute { } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // Action a1 = [DllImport("MyModule.dll")] static () => { }; Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(8, 22)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(4, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Null(lambdas[0].GetDllImportData()); // [DllImport] is ignored if there are errors. Assert.True(lambdas[1].RequiresSecurityObject); Assert.True(lambdas[2].HasDeclarativeSecurity); Assert.Equal(default, lambdas[3].ReturnValueMarshallingInformation.UnmanagedType); } [Fact] public void LambdaAttributes_Permissions() { var source = @"#pragma warning disable 618 using System; using System.Security.Permissions; class Program { static void Main() { Action a1 = [PermissionSet(SecurityAction.Deny)] () => { }; } }"; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single(); Assert.NotEmpty(lambda.GetSecurityInformation()); } [Fact] public void LambdaAttributes_NullableAttributes_01() { var source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Func<object> a1 = [return: MaybeNull][return: NotNull] () => null; Func<object, object> a2 = [return: NotNullIfNotNull(""obj"")] (object obj) => obj; Func<bool> a4 = [MemberNotNull(""x"")][MemberNotNullWhen(false, ""y"")][MemberNotNullWhen(true, ""z"")] () => true; } }"; var comp = CreateCompilation( new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition, NotNullIfNotNullAttributeDefinition, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(3, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Equal(FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull, lambdas[0].ReturnTypeFlowAnalysisAnnotations); Assert.Equal(new[] { "obj" }, lambdas[1].ReturnNotNullIfParameterNotNull); Assert.Equal(new[] { "x" }, lambdas[2].NotNullMembers); Assert.Equal(new[] { "y" }, lambdas[2].NotNullWhenFalseMembers); Assert.Equal(new[] { "z" }, lambdas[2].NotNullWhenTrueMembers); } [Fact] public void LambdaAttributes_NullableAttributes_02() { var source = @"#nullable enable using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Func<object> a1 = [return: MaybeNull] () => null; Func<object?> a2 = [return: NotNull] () => null; } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Report WRN_NullReferenceReturn for a2, not for a1. comp.VerifyDiagnostics( // (8,53): warning CS8603: Possible null reference return. // Func<object> a1 = [return: MaybeNull] () => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 53)); } [Fact] public void LambdaAttributes_NullableAttributes_03() { var source = @"#nullable enable using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Action<object> a1 = ([AllowNull] x) => { x.ToString(); }; Action<object?> a2 = ([DisallowNull] x) => { x.ToString(); }; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Report nullability mismatch warning assigning lambda to a2. comp.VerifyDiagnostics( // (8,50): warning CS8602: Dereference of a possibly null reference. // Action<object> a1 = ([AllowNull] x) => { x.ToString(); }; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 50)); } [WorkItem(55013, "https://github.com/dotnet/roslyn/issues/55013")] [Fact] public void NullableTypeArraySwitchPattern() { var source = @"#nullable enable class C { object? field; string Prop => field switch { string?[] a => ""a"" }; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // object? field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 13), // (5,26): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // string Prop => field switch Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 26)); } [Fact] public void LambdaAttributes_DoesNotReturn() { var source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Action a1 = [DoesNotReturn] () => { }; Action a2 = [DoesNotReturn] () => throw new Exception(); } }"; var comp = CreateCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Report warning that lambda expression in a1 initializer returns. comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(2, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[0].FlowAnalysisAnnotations); Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[1].FlowAnalysisAnnotations); } [Fact] public void LambdaAttributes_UnmanagedCallersOnly() { var source = @"using System; using System.Runtime.InteropServices; class Program { static void Main() { Action a = [UnmanagedCallersOnly] static () => { }; } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,21): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // Action a = [UnmanagedCallersOnly] static () => { }; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 21)); } [Fact] public void LambdaParameterAttributes_OptionalAndDefaultValueAttributes() { var source = @"using System; using System.Runtime.InteropServices; class Program { static void Main() { Action<int> a1 = ([Optional, DefaultParameterValue(2)] int i) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single(); var parameter = (SourceParameterSymbol)lambda.Parameters[0]; Assert.True(parameter.HasOptionalAttribute); Assert.False(parameter.HasExplicitDefaultValue); Assert.Equal(2, parameter.DefaultValueFromAttributes.Value); } [ConditionalFact(typeof(DesktopOnly))] public void LambdaParameterAttributes_WellKnownAttributes() { var source = @"using System; using System.Runtime.CompilerServices; class Program { static void Main() { Action<object> a1 = ([IDispatchConstant] object obj) => { }; Action<object> a2 = ([IUnknownConstant] object obj) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(2, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.True(lambdas[0].Parameters[0].IsIDispatchConstant); Assert.True(lambdas[1].Parameters[0].IsIUnknownConstant); } [Fact] public void LambdaParameterAttributes_NullableAttributes_01() { var source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Action<object> a1 = ([AllowNull][MaybeNullWhen(false)] object obj) => { }; Action<object, object> a2 = (object x, [NotNullIfNotNull(""x"")] object y) => { }; } }"; var comp = CreateCompilation( new[] { source, AllowNullAttributeDefinition, MaybeNullWhenAttributeDefinition, NotNullIfNotNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(2, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Equal(FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.MaybeNullWhenFalse, lambdas[0].Parameters[0].FlowAnalysisAnnotations); Assert.Equal(new[] { "x" }, lambdas[1].Parameters[1].NotNullIfParameterNotNull); } [Fact] public void LambdaParameterAttributes_NullableAttributes_02() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; delegate bool D(out object? obj); class Program { static void Main() { D d = ([NotNullWhen(true)] out object? obj) => { obj = null; return true; }; } }"; var comp = CreateCompilation(new[] { source, NotNullWhenAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Should report WRN_ParameterConditionallyDisallowsNull. comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var lambda = GetLambdaSymbol(model, expr); Assert.Equal(FlowAnalysisAnnotations.NotNullWhenTrue, lambda.Parameters[0].FlowAnalysisAnnotations); } [Fact] public void LambdaReturnType_01() { var source = @"using System; class Program { static void F<T>() { Func<T> f1 = T () => default; Func<T, T> f2 = T (x) => { return x; }; Func<T, T> f3 = T (T x) => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,22): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // Func<T> f1 = T () => default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(6, 22), // (7,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // Func<T, T> f2 = T (x) => { return x; }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(7, 25), // (8,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // Func<T, T> f3 = T (T x) => x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(8, 25)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void LambdaReturnType_02() { var source = @"using System; class Program { static void F<T, U>() { Func<T> f1; Func<U> f2; f1 = T () => default; f2 = T () => default; f1 = U () => default; f2 = U () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type // f2 = T () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14), // (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type // f1 = U () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14)); } [Fact] public void LambdaReturnType_03() { var source = @"using System; class Program { static void F<T, U>() where U : T { Func<T> f1; Func<U> f2; f1 = T () => default; f2 = T () => default; f1 = U () => default; f2 = U () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type // f2 = T () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14), // (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type // f1 = U () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14)); } [Fact] public void LambdaReturnType_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F<T, U>() { Expression<Func<T>> e1; Expression<Func<U>> e2; e1 = T () => default; e2 = T () => default; e1 = U () => default; e2 = U () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<U>>' because the return type does not match the delegate return type // e2 = T () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<U>>").WithLocation(10, 14), // (11,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<T>>' because the return type does not match the delegate return type // e1 = U () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<T>>").WithLocation(11, 14)); } [Fact] public void LambdaReturnType_05() { var source = @"#nullable enable using System; class Program { static void Main() { Func<dynamic> f1 = object () => default!; Func<(int, int)> f2 = (int X, int Y) () => default; Func<string?> f3 = string () => default!; Func<IntPtr> f4 = nint () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes). // Func<string?> f3 = string () => default!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => default!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28)); } [Fact] public void LambdaReturnType_06() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<object>> e1 = dynamic () => default!; Expression<Func<(int X, int Y)>> e2 = (int, int) () => default; Expression<Func<string>> e3 = string? () => default; Expression<Func<nint>> e4 = IntPtr () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,39): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Expression<Func<string>> e3 = string? () => default; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => default").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 39)); } [Fact] public void LambdaReturnType_07() { var source = @"#nullable enable using System; struct S<T> { } class Program { static void Main() { Delegate d1 = string? () => default; Delegate d2 = string () => default; Delegate d3 = S<object?> () => default(S<object?>); Delegate d4 = S<object?> () => default(S<object>); Delegate d5 = S<object> () => default(S<object?>); Delegate d6 = S<object> () => default(S<object>); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,36): warning CS8603: Possible null reference return. // Delegate d2 = string () => default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(9, 36), // (11,40): warning CS8619: Nullability of reference types in value of type 'S<object>' doesn't match target type 'S<object?>'. // Delegate d4 = S<object?> () => default(S<object>); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object>)").WithArguments("S<object>", "S<object?>").WithLocation(11, 40), // (12,39): warning CS8619: Nullability of reference types in value of type 'S<object?>' doesn't match target type 'S<object>'. // Delegate d5 = S<object> () => default(S<object?>); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object?>)").WithArguments("S<object?>", "S<object>").WithLocation(12, 39)); } [Fact] public void LambdaReturnType_08() { var source = @"#nullable enable using System; struct S<T> { } class Program { static void Main() { Func<string?> f1 = string? () => throw null!; Func<string?> f2 = string () => throw null!; Func<string> f3 = string? () => throw null!; Func<string> f4 = string () => throw null!; Func<S<object?>> f5 = S<object?> () => throw null!; Func<S<object?>> f6 = S<object> () => throw null!; Func<S<object>> f7 = S<object?> () => throw null!; Func<S<object>> f8 = S<object> () => throw null!; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes). // Func<string?> f2 = string () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => throw null!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28), // (10,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Func<string> f3 = string? () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => throw null!").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 27), // (13,31): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object?>>' (possibly because of nullability attributes). // Func<S<object?>> f6 = S<object> () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object> () => throw null!").WithArguments("lambda expression", "System.Func<S<object?>>").WithLocation(13, 31), // (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object>>' (possibly because of nullability attributes). // Func<S<object>> f7 = S<object?> () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object?> () => throw null!").WithArguments("lambda expression", "System.Func<S<object>>").WithLocation(14, 30)); } [Fact] public void LambdaReturnType_09() { var source = @"#nullable enable struct S<T> { } delegate ref T D1<T>(); delegate ref readonly T D2<T>(); class Program { static void Main() { D1<S<object?>> f1 = (ref S<object?> () => throw null!); D1<S<object?>> f2 = (ref S<object> () => throw null!); D1<S<object>> f3 = (ref S<object?> () => throw null!); D1<S<object>> f4 = (ref S<object> () => throw null!); D2<S<object?>> f5 = (ref readonly S<object?> () => throw null!); D2<S<object?>> f6 = (ref readonly S<object> () => throw null!); D2<S<object>> f7 = (ref readonly S<object?> () => throw null!); D2<S<object>> f8 = (ref readonly S<object> () => throw null!); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object?>>' (possibly because of nullability attributes). // D1<S<object?>> f2 = (ref S<object> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object> () => throw null!").WithArguments("lambda expression", "D1<S<object?>>").WithLocation(10, 30), // (11,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object>>' (possibly because of nullability attributes). // D1<S<object>> f3 = (ref S<object?> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object?> () => throw null!").WithArguments("lambda expression", "D1<S<object>>").WithLocation(11, 29), // (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object?>>' (possibly because of nullability attributes). // D2<S<object?>> f6 = (ref readonly S<object> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object> () => throw null!").WithArguments("lambda expression", "D2<S<object?>>").WithLocation(14, 30), // (15,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object>>' (possibly because of nullability attributes). // D2<S<object>> f7 = (ref readonly S<object?> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object?> () => throw null!").WithArguments("lambda expression", "D2<S<object>>").WithLocation(15, 29)); } [Fact] public void LambdaReturnType_10() { var source = @"delegate T D1<T>(ref T t); delegate ref T D2<T>(ref T t); delegate ref readonly T D3<T>(ref T t); class Program { static void F<T>() { D1<T> d1; D2<T> d2; D3<T> d3; d1 = T (ref T t) => t; d2 = T (ref T t) => t; d3 = T (ref T t) => t; d1 = (ref T (ref T t) => ref t); d2 = (ref T (ref T t) => ref t); d3 = (ref T (ref T t) => ref t); d1 = (ref readonly T (ref T t) => ref t); d2 = (ref readonly T (ref T t) => ref t); d3 = (ref readonly T (ref T t) => ref t); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,14): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type // d2 = T (ref T t) => t; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D2<T>").WithLocation(12, 14), // (13,14): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type // d3 = T (ref T t) => t; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D3<T>").WithLocation(13, 14), // (14,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type // d1 = (ref T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(14, 15), // (16,15): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type // d3 = (ref T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D3<T>").WithLocation(16, 15), // (17,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type // d1 = (ref readonly T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(17, 15), // (18,15): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type // d2 = (ref readonly T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D2<T>").WithLocation(18, 15)); } [Fact] public void LambdaReturnType_11() { var source = @"using System; class Program { static void Main() { Delegate d; d = (ref void () => { }); d = (ref readonly void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,14): error CS8917: The delegate type could not be inferred. // d = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 14), // (7,18): error CS1547: Keyword 'void' cannot be used in this context // d = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 18), // (8,14): error CS8917: The delegate type could not be inferred. // d = (ref readonly void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref readonly void () => { }").WithLocation(8, 14), // (8,27): error CS1547: Keyword 'void' cannot be used in this context // d = (ref readonly void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(8, 27)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void LambdaReturnType_12() { var source = @"using System; class Program { static void Main() { Delegate d; d = TypedReference () => throw null; d = RuntimeArgumentHandle () => throw null; d = ArgIterator () => throw null; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'TypedReference' // d = TypedReference () => throw null; Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference").WithLocation(7, 13), // (7,13): error CS8917: The delegate type could not be inferred. // d = TypedReference () => throw null; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "TypedReference () => throw null").WithLocation(7, 13), // (8,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'RuntimeArgumentHandle' // d = RuntimeArgumentHandle () => throw null; Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = RuntimeArgumentHandle () => throw null; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "RuntimeArgumentHandle () => throw null").WithLocation(8, 13), // (9,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'ArgIterator' // d = ArgIterator () => throw null; Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator").WithLocation(9, 13), // (9,13): error CS8917: The delegate type could not be inferred. // d = ArgIterator () => throw null; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ArgIterator () => throw null").WithLocation(9, 13)); } [Fact] public void LambdaReturnType_13() { var source = @"static class S { } delegate S D(); class Program { static void Main() { D d = S () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,15): error CS0722: 'S': static types cannot be used as return types // D d = S () => default; Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S").WithArguments("S").WithLocation(7, 15)); } [Fact] public void LambdaReturnType_14() { var source = @"using System; class Program { static void Main() { Delegate d = async int () => 0; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,35): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // Delegate d = async int () => 0; Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=>").WithLocation(6, 35), // (6,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // Delegate d = async int () => 0; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 35)); } [Fact] public void LambdaReturnType_15() { var source = @"using System; using System.Threading.Tasks; delegate ref Task D(string s); class Program { static void Main() { Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,23): error CS8917: The delegate type could not be inferred. // Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "async ref Task (s) => { _ = s.Length; await Task.Yield(); }").WithLocation(8, 23), // (8,29): error CS1073: Unexpected token 'ref' // Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29), // (9,22): error CS1073: Unexpected token 'ref' // D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22)); } [Fact] public void LambdaReturnType_16() { var source = @"using System; using System.Threading.Tasks; delegate ref Task D(string s); class Program { static void Main() { Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,29): error CS1073: Unexpected token 'ref' // Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29), // (9,22): error CS1073: Unexpected token 'ref' // D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22)); } [Fact] public void LambdaReturnType_17() { var source = @"#nullable enable using System; class Program { static void F(string? x, string y) { Func<string?> f1 = string () => { if (x is null) return x; return y; }; Func<string> f2 = string? () => { if (x is not null) return x; return y; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes). // Func<string?> f1 = string () => { if (x is null) return x; return y; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => { if (x is null) return x; return y; }").WithArguments("lambda expression", "System.Func<string?>").WithLocation(7, 28), // (7,65): warning CS8603: Possible null reference return. // Func<string?> f1 = string () => { if (x is null) return x; return y; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(7, 65), // (8,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Func<string> f2 = string? () => { if (x is not null) return x; return y; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => { if (x is not null) return x; return y; }").WithArguments("lambda expression", "System.Func<string>").WithLocation(8, 27)); } [Fact] public void LambdaReturnType_CustomModifiers_01() { var sourceA = @".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { } .method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) Invoke () runtime managed { } .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } .method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { } }"; var refA = CompileIL(sourceA); var sourceB = @"class Program { static void F(D d) { System.Console.WriteLine(d()); } static void Main() { F(() => 1); F(int () => 2); } }"; CompileAndVerify(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 2"); } [Fact] public void LambdaReturnType_CustomModifiers_02() { var sourceA = @".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) Invoke () runtime managed { } .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { } }"; var refA = CompileIL(sourceA); var sourceB = @"class Program { static void F(D d) { System.Console.WriteLine(d()); } static void Main() { F(() => 1); F(int () => 2); } }"; var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,34): error CS0570: 'D.Invoke()' is not supported by the language // System.Console.WriteLine(d()); Diagnostic(ErrorCode.ERR_BindToBogus, "d()").WithArguments("D.Invoke()").WithLocation(5, 34), // (9,11): error CS0570: 'D.Invoke()' is not supported by the language // F(() => 1); Diagnostic(ErrorCode.ERR_BindToBogus, "() => 1").WithArguments("D.Invoke()").WithLocation(9, 11), // (10,11): error CS0570: 'D.Invoke()' is not supported by the language // F(int () => 2); Diagnostic(ErrorCode.ERR_BindToBogus, "int () => 2").WithArguments("D.Invoke()").WithLocation(10, 11)); } [Fact] public void LambdaReturnType_UseSiteErrors() { var sourceA = @".class public sealed A extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void F<T>(Func<T> f) { } static void Main() { F(A () => default); } }"; var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,11): error CS0648: 'A' is a type not supported by the language // F(A () => default); Diagnostic(ErrorCode.ERR_BogusType, "A").WithArguments("A").WithLocation(7, 11)); } [Fact] public void AsyncLambdaParameters_01() { var source = @"using System; using System.Threading.Tasks; delegate Task D(ref string s); class Program { static void Main() { Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,41): error CS1988: Async methods cannot have ref, in or out parameters // Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(8, 41), // (9,34): error CS1988: Async methods cannot have ref, in or out parameters // D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(9, 34)); } [ConditionalFact(typeof(DesktopOnly))] public void AsyncLambdaParameters_02() { var source = @"using System; using System.Threading.Tasks; delegate void D1(TypedReference r); delegate void D2(RuntimeArgumentHandle h); delegate void D3(ArgIterator i); class Program { static void Main() { D1 d1 = async (TypedReference r) => { await Task.Yield(); }; D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); }; D3 d3 = async (ArgIterator i) => { await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,39): error CS4012: Parameters or locals of type 'TypedReference' cannot be declared in async methods or async lambda expressions. // D1 d1 = async (TypedReference r) => { await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "r").WithArguments("System.TypedReference").WithLocation(10, 39), // (11,46): error CS4012: Parameters or locals of type 'RuntimeArgumentHandle' cannot be declared in async methods or async lambda expressions. // D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "h").WithArguments("System.RuntimeArgumentHandle").WithLocation(11, 46), // (12,36): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // D3 d3 = async (ArgIterator i) => { await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "i").WithArguments("System.ArgIterator").WithLocation(12, 36)); } [Fact] public void BestType_01() { var source = @"using System; class A { } class B1 : A { } class B2 : A { } interface I { } class C1 : I { } class C2 : I { } class Program { static void F<T>(Func<bool, T> f) { } static void Main() { F((bool b) => { if (b) return new B1(); return new B2(); }); F((bool b) => { if (b) return new C1(); return new C2(); }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (13,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F((bool b) => { if (b) return new B1(); return new B2(); }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(13, 9), // (14,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F((bool b) => { if (b) return new C1(); return new C2(); }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(14, 9)); } // As above but with explicit return type. [Fact] public void BestType_02() { var source = @"using System; class A { } class B1 : A { } class B2 : A { } interface I { } class C1 : I { } class C2 : I { } class Program { static void F<T>(Func<bool, T> f) { Console.WriteLine(typeof(T)); } static void Main() { F(A (bool b) => { if (b) return new B1(); return new B2(); }); F(I (bool b) => { if (b) return new C1(); return new C2(); }); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"A I"); } [Fact] public void BestType_03() { var source = @"using System; class A { } class B1 : A { } class B2 : A { } class Program { static void F<T>(Func<T> x, Func<T> y) { } static void Main() { F(B2 () => null, B2 () => null); F(A () => null, B2 () => null); F(B1 () => null, B2 () => null); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,25): error CS8934: Cannot convert lambda expression to type 'Func<A>' because the return type does not match the delegate return type // F(A () => null, B2 () => null); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "B2 () => null").WithArguments("lambda expression", "System.Func<A>").WithLocation(11, 25), // (12,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T>, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(B1 () => null, B2 () => null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T>, System.Func<T>)").WithLocation(12, 9)); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static void F<T>(Func<object, T> f) { Console.WriteLine(typeof(T)); } static void Main() { F(long (o) => 1); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"System.Int64"); } // Should method type inference make an explicit type inference // from the lambda expression return type? [Fact] public void TypeInference_02() { var source = @"using System; class Program { static void F<T>(Func<T, T> f) { Console.WriteLine(typeof(T)); } static void Main() { F(int (i) => i); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(int (i) => i); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T, T>)").WithLocation(10, 9)); } // CS4031 is not reported for async lambda in [SecurityCritical] type. [Fact] [WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")] public void SecurityCritical_AsyncLambda() { var source = @"using System; using System.Security; using System.Threading.Tasks; [SecurityCritical] class Program { static void Main() { Func<Task> f = async () => await Task.Yield(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // CS4031 is not reported for async lambda in [SecurityCritical] type. [Fact] [WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")] public void SecurityCritical_AsyncLambda_AttributeArgument() { var source = @"using System; using System.Security; using System.Threading.Tasks; class A : Attribute { internal A(int i) { } } [SecurityCritical] [A(F(async () => await Task.Yield()))] class Program { internal static int F(Func<Task> f) => 0; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(F(async () => await Task.Yield()))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F(async () => await Task.Yield())").WithLocation(9, 4)); } private static LambdaSymbol GetLambdaSymbol(SemanticModel model, LambdaExpressionSyntax syntax) { return model.GetSymbolInfo(syntax).Symbol.GetSymbol<LambdaSymbol>(); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_01() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A] (x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_02() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A][A] (x) => x; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A][A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A][A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_03() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = ([A] x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,37): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = ([A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "x").WithLocation(5, 37) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_04() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = ([A][A] x) => x; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,40): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = ([A][A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "x").WithLocation(5, 40) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_05() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int, int>> e = ([A] x, [A] y) => x + y; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,42): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int, int>> e = ([A] x, [A] y) => x + y; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "x").WithLocation(5, 42) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_06() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [return: A] (x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [return: A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[return: A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_07() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [return: A][return: A] (x) => x; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [return: A][return: A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[return: A][return: A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_08() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A][return: A] (x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A][return: A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A][return: A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_09() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A] ([A] x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A] ([A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A] ([A] x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_10() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [return: A] ([A] x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [return: A] ([A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[return: A] ([A] x) => x").WithLocation(5, 32) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LambdaTests : CSharpTestBase { [Fact, WorkItem(37456, "https://github.com/dotnet/roslyn/issues/37456")] public void Verify37456() { var comp = CreateCompilation(@" using System; using System.Collections.Generic; using System.Linq; public static partial class EnumerableEx { public static void Join1<TA, TKey, T>(this IEnumerable<TA> a, Func<TA, TKey> aKey, Func<TA, T> aSel, Func<TA, TA, T> sel) { KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v); _ = a.GroupJoin(a, aKey, aKey, (f, ss) => Pair(f, ss.Select(s => Pair(true, s)))); // simplified repro } public static IEnumerable<T> Join2<TA, TB, TKey, T>(this IEnumerable<TA> a, IEnumerable<TB> b, Func<TA, TKey> aKey, Func<TB, TKey> bKey, Func<TA, T> aSel, Func<TA, TB, T> sel, IEqualityComparer<TKey> comp) { KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v); return from j in a.GroupJoin(b, aKey, bKey, (f, ss) => Pair(f, from s in ss select Pair(true, s)), comp) from s in j.Value.DefaultIfEmpty() select s.Key ? sel(j.Key, s.Value) : aSel(j.Key); } }"); comp.VerifyDiagnostics(); CompileAndVerify(comp); // emitting should not hang } [Fact, WorkItem(608181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608181")] public void BadInvocationInLambda() { var src = @" using System; using System.Linq.Expressions; class C { Expression<Action<dynamic>> e = x => new object[](x); }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(src); comp.VerifyDiagnostics( // (7,52): error CS1586: Array creation must have array size or array initializer // Expression<Action<dynamic>> e = x => new object[](x); Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(7, 52) ); } [Fact] public void TestLambdaErrors01() { var comp = CreateCompilationWithMscorlib40AndSystemCore(@" using System; using System.Linq.Expressions; namespace System.Linq.Expressions { public class Expression<T> {} } class C { delegate void D1(ref int x, out int y, int z); delegate void D2(out int x); void M() { int q1 = ()=>1; int q2 = delegate { return 1; }; Func<int> q3 = x3=>1; Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type D1 q6 = (double x6, ref int y6, ref int z6)=>1; // COMPATIBILITY: The C# 4 compiler produces two errors: // // error CS1676: Parameter 2 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D1' because it has one or more out parameters // // This seems redundant (because there is no 'parameter 2' in the source code) // I propose that we eliminate the first error. D1 q7 = delegate {}; Frob q8 = ()=>{}; D2 q9 = x9=>{}; D1 q10 = (x10,y10,z10)=>{}; // COMPATIBILITY: The C# 4 compiler produces two errors: // // error CS0127: Since 'System.Action' returns void, a return keyword must // not be followed by an object expression // // error CS1662: Cannot convert lambda expression to delegate type 'System.Action' // because some of the return types in the block are not implicitly convertible to // the delegate return type // // The problem is adequately characterized by the first message; I propose we // eliminate the second, which seems both redundant and wrong. Action q11 = ()=>{ return 1; }; Action q12 = ()=>1; Func<int> q13 = ()=>{ if (false) return 1; }; Func<int> q14 = ()=>123.456; // Note that the type error is still an error even if the offending // return is unreachable. Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; // In the native compiler these errors were caught at parse time. In Roslyn, these are now semantic // analysis errors. See changeset 1674 for details. Action<int[]> q16 = delegate (params int[] p) { }; Action<string[]> q17 = (params string[] s)=>{}; Action<int, double[]> q18 = (int x, params double[] s)=>{}; object q19 = new Action( (int x)=>{} ); Expression<int> ex1 = ()=>1; } }"); comp.VerifyDiagnostics( // (16,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // int q1 = ()=>1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "()=>1").WithArguments("lambda expression", "int").WithLocation(16, 18), // (17,18): error CS1660: Cannot convert anonymous method to type 'int' because it is not a delegate type // int q2 = delegate { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate { return 1; }").WithArguments("anonymous method", "int").WithLocation(17, 18), // (18,24): error CS1593: Delegate 'Func<int>' does not take 1 arguments // Func<int> q3 = x3=>1; Diagnostic(ErrorCode.ERR_BadDelArgCount, "x3=>1").WithArguments("System.Func<int>", "1").WithLocation(18, 24), // (19,37): error CS0234: The type or namespace name 'Itn23' does not exist in the namespace 'System' (are you missing an assembly reference?) // Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Itn23").WithArguments("Itn23", "System").WithLocation(19, 37), // (20,35): error CS0234: The type or namespace name 'Duobel' does not exist in the namespace 'System' (are you missing an assembly reference?) // Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Duobel").WithArguments("Duobel", "System").WithLocation(20, 35), // (20,27): error CS1593: Delegate 'Func<double>' does not take 1 arguments // Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type Diagnostic(ErrorCode.ERR_BadDelArgCount, "(System.Duobel x5)=>1").WithArguments("System.Func<double>", "1").WithLocation(20, 27), // (21,17): error CS1661: Cannot convert lambda expression to delegate type 'C.D1' because the parameter types do not match the delegate parameter types // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double x6, ref int y6, ref int z6)=>1").WithArguments("lambda expression", "C.D1").WithLocation(21, 17), // (21,25): error CS1678: Parameter 1 is declared as type 'double' but should be 'ref int' // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamType, "x6").WithArguments("1", "", "double", "ref ", "int").WithLocation(21, 25), // (21,37): error CS1676: Parameter 2 must be declared with the 'out' keyword // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamRef, "y6").WithArguments("2", "out").WithLocation(21, 37), // (21,49): error CS1677: Parameter 3 should not be declared with the 'ref' keyword // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamExtraRef, "z6").WithArguments("3", "ref").WithLocation(21, 49), // (32,17): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'C.D1' because it has one or more out parameters // D1 q7 = delegate {}; Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, "delegate {}").WithArguments("C.D1").WithLocation(32, 17), // (34,9): error CS0246: The type or namespace name 'Frob' could not be found (are you missing a using directive or an assembly reference?) // Frob q8 = ()=>{}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Frob").WithArguments("Frob").WithLocation(34, 9), // (36,17): error CS1676: Parameter 1 must be declared with the 'out' keyword // D2 q9 = x9=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "x9").WithArguments("1", "out").WithLocation(36, 17), // (38,19): error CS1676: Parameter 1 must be declared with the 'ref' keyword // D1 q10 = (x10,y10,z10)=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "x10").WithArguments("1", "ref").WithLocation(38, 19), // (38,23): error CS1676: Parameter 2 must be declared with the 'out' keyword // D1 q10 = (x10,y10,z10)=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "y10").WithArguments("2", "out").WithLocation(38, 23), // (52,28): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Action q11 = ()=>{ return 1; }; Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(52, 28), // (54,26): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // Action q12 = ()=>1; Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(54, 26), // (56,42): warning CS0162: Unreachable code detected // Func<int> q13 = ()=>{ if (false) return 1; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(56, 42), // (56,27): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // Func<int> q13 = ()=>{ if (false) return 1; }; Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(56, 27), // (58,29): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Func<int> q14 = ()=>123.456; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "123.456").WithArguments("double", "int").WithLocation(58, 29), // (58,29): 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<int> q14 = ()=>123.456; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "123.456").WithArguments("lambda expression").WithLocation(58, 29), // (62,51): error CS0266: Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?) // Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1m").WithArguments("decimal", "double").WithLocation(62, 51), // (62,51): 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<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1m").WithArguments("lambda expression").WithLocation(62, 51), // (62,44): warning CS0162: Unreachable code detected // Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(62, 44), // (66,39): error CS1670: params is not valid in this context // Action<int[]> q16 = delegate (params int[] p) { }; Diagnostic(ErrorCode.ERR_IllegalParams, "params int[] p").WithLocation(66, 39), // (67,33): error CS1670: params is not valid in this context // Action<string[]> q17 = (params string[] s)=>{}; Diagnostic(ErrorCode.ERR_IllegalParams, "params string[] s").WithLocation(67, 33), // (68,45): error CS1670: params is not valid in this context // Action<int, double[]> q18 = (int x, params double[] s)=>{}; Diagnostic(ErrorCode.ERR_IllegalParams, "params double[] s").WithLocation(68, 45), // (70,34): error CS1593: Delegate 'Action' does not take 1 arguments // object q19 = new Action( (int x)=>{} ); Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int x)=>{}").WithArguments("System.Action", "1").WithLocation(70, 34), // (72,9): warning CS0436: The type 'Expression<T>' in '' conflicts with the imported type 'Expression<TDelegate>' in 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // Expression<int> ex1 = ()=>1; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Expression<int>").WithArguments("", "System.Linq.Expressions.Expression<T>", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Linq.Expressions.Expression<TDelegate>").WithLocation(72, 9), // (72,31): error CS0835: Cannot convert lambda to an expression tree whose type argument 'int' is not a delegate type // Expression<int> ex1 = ()=>1; Diagnostic(ErrorCode.ERR_ExpressionTreeMustHaveDelegate, "()=>1").WithArguments("int").WithLocation(72, 31) ); } [Fact] // 5368 public void TestLambdaErrors02() { string code = @" class C { void M() { System.Func<int, int> del = x => x + 1; } }"; var compilation = CreateCompilation(code); compilation.VerifyDiagnostics(); // no errors expected } [WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")] [Fact] public void TestLambdaErrors03() { string source = @" using System; interface I : IComparable<IComparable<I>> { } class C { static void Goo(Func<IComparable<I>> x) { } static void Goo(Func<I> x) {} static void M() { Goo(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(Func<IComparable<I>>)' and 'C.Goo(Func<I>)' // Goo(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(System.Func<System.IComparable<I>>)", "C.Goo(System.Func<I>)").WithLocation(12, 9)); } [WorkItem(18645, "https://github.com/dotnet/roslyn/issues/18645")] [Fact] public void LambdaExpressionTreesErrors() { string source = @" using System; using System.Linq.Expressions; class C { void M() { Expression<Func<int,int>> ex1 = () => 1; Expression<Func<int,int>> ex2 = (double d) => 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (9,41): error CS1593: Delegate 'Func<int, int>' does not take 0 arguments // Expression<Func<int,int>> ex1 = () => 1; Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => 1").WithArguments("System.Func<int, int>", "0").WithLocation(9, 41), // (10,41): error CS1661: Cannot convert lambda expression to type 'Expression<Func<int, int>>' because the parameter types do not match the delegate parameter types // Expression<Func<int,int>> ex2 = (double d) => 1; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double d) => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int, int>>").WithLocation(10, 41), // (10,49): error CS1678: Parameter 1 is declared as type 'double' but should be 'int' // Expression<Func<int,int>> ex2 = (double d) => 1; Diagnostic(ErrorCode.ERR_BadParamType, "d").WithArguments("1", "", "double", "", "int").WithLocation(10, 49)); } [WorkItem(539976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539976")] [Fact] public void LambdaArgumentToOverloadedDelegate() { var text = @"class W { delegate T Func<A0, T>(A0 a0); static int F(Func<short, int> f) { return 0; } static int F(Func<short, double> f) { return 1; } static int Main() { return F(c => c); } } "; var comp = CreateCompilation(Parse(text)); comp.VerifyDiagnostics(); } [WorkItem(528044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528044")] [Fact] public void MissingReferenceInOverloadResolution() { var text1 = @" using System; public static class A { public static void Goo(Func<B, object> func) { } public static void Goo(Func<C, object> func) { } } public class B { public Uri GetUrl() { return null; } } public class C { public string GetUrl() { return null; } }"; var comp1 = CreateCompilationWithMscorlib40( new[] { Parse(text1) }, new[] { TestMetadata.Net451.System }); var text2 = @" class Program { static void Main() { A.Goo(x => x.GetUrl()); } } "; var comp2 = CreateCompilationWithMscorlib40( new[] { Parse(text2) }, new[] { new CSharpCompilationReference(comp1) }); Assert.Equal(0, comp2.GetDiagnostics().Count()); } [WorkItem(528047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528047")] [Fact()] public void OverloadResolutionWithEmbeddedInteropType() { var text1 = @" using System; using System.Collections.Generic; using stdole; public static class A { public static void Goo(Func<X> func) { System.Console.WriteLine(""X""); } public static void Goo(Func<Y> func) { System.Console.WriteLine(""Y""); } } public delegate void X(List<IDispatch> addin); public delegate void Y(List<string> addin); "; var comp1 = CreateCompilation( Parse(text1), new[] { TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseDll); var text2 = @" public class Program { public static void Main() { A.Goo(() => delegate { }); } } "; var comp2 = CreateCompilation( Parse(text2), new MetadataReference[] { new CSharpCompilationReference(comp1), TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp2, expectedOutput: "Y").Diagnostics.Verify(); var comp3 = CreateCompilation( Parse(text2), new MetadataReference[] { comp1.EmitToImageReference(), TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp3, expectedOutput: "Y").Diagnostics.Verify(); } [WorkItem(6358, "DevDiv_Projects/Roslyn")] [Fact] public void InvalidExpressionInvolveLambdaOperator() { var text1 = @" class C { static void X() { int x=0; int y=0; if(x-=>*y) // CS1525 return; return; } } "; var comp = CreateCompilation(Parse(text1)); var errs = comp.GetDiagnostics(); Assert.True(0 < errs.Count(), "Diagnostics not empty"); Assert.True(0 < errs.Where(e => e.Code == 1525).Select(e => e).Count(), "Diagnostics contains CS1525"); } [WorkItem(540219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540219")] [Fact] public void OverloadResolutionWithStaticType() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Sub Goo(x as Action(Of String)) End Sub Sub Goo(x as Action(Of GC)) End Sub End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.Goo(x => { }); } } "; var metadataStream = new MemoryStream(); var emitResult = vbProject.Emit(metadataStream, options: new EmitOptions(metadataOnly: true)); Assert.True(emitResult.Success); var csProject = CreateCompilation( Parse(csSource), new[] { MetadataReference.CreateFromImage(metadataStream.ToImmutable()) }); Assert.Equal(0, csProject.GetDiagnostics().Count()); } [Fact] public void OverloadResolutionWithStaticTypeError() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Public Dim F As Action(Of GC) End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.F = x=>{}; } } "; var vbMetadata = vbProject.EmitToArray(options: new EmitOptions(metadataOnly: true)); var csProject = CreateCompilation(Parse(csSource), new[] { MetadataReference.CreateFromImage(vbMetadata) }); csProject.VerifyDiagnostics( // (6,15): error CS0721: 'GC': static types cannot be used as parameters // M.F = x=>{}; Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "x").WithArguments("System.GC").WithLocation(6, 15)); } [WorkItem(540251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540251")] [Fact] public void AttributesCannotBeUsedInAnonymousMethods() { var csSource = @" using System; class Program { static void Main() { const string message = ""The parameter is obsolete""; Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { }; } } "; var csProject = CreateCompilation(csSource); csProject.VerifyEmitDiagnostics( // (8,22): warning CS0219: The variable 'message' is assigned but its value is never used // const string message = "The parameter is obsolete"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "message").WithArguments("message").WithLocation(8, 22), // (9,35): error CS7014: Attributes are not valid in this context. // Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[ObsoleteAttribute(message)]").WithLocation(9, 35)); } [WorkItem(540263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540263")] [Fact] public void ErrorsInUnboundLambdas() { var csSource = @"using System; class Program { static void Main() { ((Func<int>)delegate { return """"; })(); ((Func<int>)delegate { })(); ((Func<int>)delegate { 1 / 0; })(); } } "; CreateCompilation(csSource).VerifyDiagnostics( // (7,39): error CS0029: Cannot implicitly convert type 'string' to 'int' // ((Func<int>)delegate { return ""; })(); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(7, 39), // (7,39): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // ((Func<int>)delegate { return ""; })(); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""""").WithArguments("anonymous method").WithLocation(7, 39), // (8,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // ((Func<int>)delegate { })(); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(8, 21), // (9,32): error CS0020: Division by constant zero // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_IntDivByZero, "1 / 0").WithLocation(9, 32), // (9,32): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_IllegalStatement, "1 / 0").WithLocation(9, 32), // (9,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(9, 21) ); } [WorkItem(540181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540181")] [Fact] public void ErrorInLambdaArgumentList() { var csSource = @"using System; class Program { public Program(string x) : this(() => x) { } static void Main(string[] args) { ((Action<string>)(f => Console.WriteLine(f)))(nulF); } }"; CreateCompilation(csSource).VerifyDiagnostics( // (5,37): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type // public Program(string x) : this(() => x) { } Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => x").WithArguments("lambda expression", "string").WithLocation(5, 37), // (8,55): error CS0103: The name 'nulF' does not exist in the current context // ((Action<string>)(f => Console.WriteLine(f)))(nulF); Diagnostic(ErrorCode.ERR_NameNotInContext, "nulF").WithArguments("nulF").WithLocation(8, 55)); } [WorkItem(541725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541725")] [Fact] public void DelegateCreationIsNotStatement() { var csSource = @" delegate void D(); class Program { public static void Main(string[] args) { D d = () => new D(() => { }); new D(()=>{}); } }"; // Though it is legal to have an object-creation-expression, because it might be useful // for its side effects, a delegate-creation-expression is not allowed as a // statement expression. CreateCompilation(csSource).VerifyDiagnostics( // (7,21): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // D d = () => new D(() => { }); Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(() => { })"), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // new D(()=>{}); Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(()=>{})")); } [WorkItem(542336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542336")] [Fact] public void ThisInStaticContext() { var csSource = @" delegate void D(); class Program { public static void Main(string[] args) { D d = () => { object o = this; }; } }"; CreateCompilation(csSource).VerifyDiagnostics( // (8,24): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // object o = this; Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this") ); } [WorkItem(542431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542431")] [Fact] public void LambdaHasMoreParametersThanDelegate() { var csSource = @" class C { static void Main() { System.Func<int> f = new System.Func<int>(r => 0); } }"; CreateCompilation(csSource).VerifyDiagnostics( // (6,51): error CS1593: Delegate 'System.Func<int>' does not take 1 arguments Diagnostic(ErrorCode.ERR_BadDelArgCount, "r => 0").WithArguments("System.Func<int>", "1")); } [Fact, WorkItem(529054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529054")] public void LambdaInDynamicCall() { var source = @" public class Program { static void Main() { dynamic b = new string[] { ""AA"" }; bool exists = System.Array.Exists(b, o => o != ""BB""); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,46): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // bool exists = System.Array.Exists(b, o => o != "BB"); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, @"o => o != ""BB""") ); } [Fact, WorkItem(529389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529389")] public void ParenthesizedLambdaInCastExpression() { var source = @" using System; using System.Collections.Generic; class Program { static void Main() { int x = 1; byte y = (byte) (x + x); Func<int> f1 = (() => { return 1; }); Func<int> f2 = (Func<int>) (() => { return 2; }); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>(). Where(e => e.Kind() == SyntaxKind.AddExpression).Single(); var tinfo = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); // Not byte Assert.Equal("int", tinfo.Type.ToDisplayString()); var exprs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>(); expr = exprs.First(); tinfo = model.GetTypeInfo(expr); conv = model.GetConversion(expr); Assert.True(conv.IsAnonymousFunction, "LambdaConversion"); Assert.Null(tinfo.Type); var sym = model.GetSymbolInfo(expr).Symbol; Assert.NotNull(sym); Assert.Equal(SymbolKind.Method, sym.Kind); Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind); expr = exprs.Last(); tinfo = model.GetTypeInfo(expr); conv = model.GetConversion(expr); Assert.True(conv.IsAnonymousFunction, "LambdaConversion"); Assert.Null(tinfo.Type); sym = model.GetSymbolInfo(expr).Symbol; Assert.NotNull(sym); Assert.Equal(SymbolKind.Method, sym.Kind); Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind); } [WorkItem(544594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544594")] [Fact] public void LambdaInEnumMemberDecl() { var csSource = @" public class TestClass { public enum Test { aa = ((System.Func<int>)(() => 1))() } Test MyTest = Test.aa; public static void Main() { } } "; CreateCompilation(csSource).VerifyDiagnostics( // (4,29): error CS0133: The expression being assigned to 'TestClass.Test.aa' must be constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "((System.Func<int>)(() => 1))()").WithArguments("TestClass.Test.aa"), // (5,10): warning CS0414: The field 'TestClass.MyTest' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "MyTest").WithArguments("TestClass.MyTest")); } [WorkItem(544932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544932")] [Fact] public void AnonymousLambdaInEnumSubtraction() { string source = @" class Test { enum E1 : byte { A = byte.MinValue, C = 1 } static void Main() { int j = ((System.Func<Test.E1>)(() => E1.A))() - E1.C; System.Console.WriteLine(j); } } "; string expectedOutput = @"255"; CompileAndVerify(new[] { source }, expectedOutput: expectedOutput); } [WorkItem(545156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545156")] [Fact] public void SpeculativelyBindOverloadResolution() { string source = @" using System; using System.Collections; using System.Collections.Generic; class Program { static void Main() { Goo(() => () => { var x = (IEnumerable<int>)null; return x; }); } static void Goo(Func<Func<IEnumerable>> x) { } static void Goo(Func<Func<IFormattable>> x) { } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); // Used to throw a NRE because of the ExpressionSyntax's null SyntaxTree. model.GetSpeculativeSymbolInfo( invocation.SpanStart, SyntaxFactory.ParseExpression("Goo(() => () => { var x = null; return x; })"), // cast removed SpeculativeBindingOption.BindAsExpression); } [WorkItem(545343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545343")] [Fact] public void LambdaUsingFieldInConstructor() { string source = @" using System; public class Derived { int field = 1; Derived() { int local = 2; // A lambda that captures a local and refers to an instance field. Action a = () => Console.WriteLine(""Local = {0}, Field = {1}"", local, field); // NullReferenceException if the ""this"" field of the display class hasn't been set. a(); } public static void Main() { Derived d = new Derived(); } }"; CompileAndVerify(source, expectedOutput: "Local = 2, Field = 1"); } [WorkItem(642222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642222")] [Fact] public void SpeculativelyBindOverloadResolutionAndInferenceWithError() { string source = @" using System;using System.Linq.Expressions; namespace IntellisenseBug { public class Program { void M(Mapper<FromData, ToData> mapper) { // Intellisense is broken here when you type . after the x: mapper.Map(x => x/* */. } } public class Mapper<TTypeFrom, TTypeTo> { public void Map<TPropertyFrom, TPropertyTo>( Expression<Func<TTypeFrom, TPropertyFrom>> from, Expression<Func<TTypeTo, TPropertyTo>> to) { } } public class FromData { public int Int { get; set; } public string String { get; set; } } public class ToData { public int Id { get; set; } public string Name { get; set; } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); // We don't actually require any particular diagnostics, but these are what we get. compilation.VerifyDiagnostics( // (10,36): error CS1001: Identifier expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (10,36): error CS1026: ) expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (10,36): error CS1002: ; expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_SemicolonExpected, "") ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var xReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<ExpressionSyntax>() .Where(e => e.ToFullString() == "x/* */") .Last(); var typeInfo = model.GetTypeInfo(xReference); Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("String")); } [WorkItem(722288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722288")] [Fact] public void CompletionInLambdaInIncompleteInvocation() { string source = @" using System; using System.Linq.Expressions; public class SomeType { public string SomeProperty { get; set; } } public class IntelliSenseError { public static void Test1<T>(Expression<Func<T, object>> expr) { Console.WriteLine(((MemberExpression)expr.Body).Member.Name); } public static void Test2<T>(Expression<Func<T, object>> expr, bool additionalParameter) { Test1(expr); } public static void Main() { Test2<SomeType>(o => o/* */. } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); // We don't actually require any particular diagnostics, but these are what we get. compilation.VerifyDiagnostics( // (21,37): error CS1001: Identifier expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (21,37): error CS1026: ) expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (21,37): error CS1002: ; expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_SemicolonExpected, "") ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var oReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<NameSyntax>() .Where(e => e.ToFullString() == "o/* */") .Last(); var typeInfo = model.GetTypeInfo(oReference); Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("SomeProperty")); } [WorkItem(871896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871896")] [Fact] public void Bug871896() { string source = @" using System.Threading; using System.Threading.Tasks; class TestDataPointBase { private readonly IVisualStudioIntegrationService integrationService; protected void TryGetDocumentId(CancellationToken token) { DocumentId documentId = null; if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) { } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var oReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<ExpressionSyntax>() .OrderByDescending(s => s.SpanStart); foreach (var name in oReference) { CSharpExtensions.GetSymbolInfo(model, name); } // We should get a bunch of errors, but no asserts. compilation.VerifyDiagnostics( // (6,22): error CS0246: The type or namespace name 'IVisualStudioIntegrationService' could not be found (are you missing a using directive or an assembly reference?) // private readonly IVisualStudioIntegrationService integrationService; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVisualStudioIntegrationService").WithArguments("IVisualStudioIntegrationService").WithLocation(6, 22), // (9,9): error CS0246: The type or namespace name 'DocumentId' could not be found (are you missing a using directive or an assembly reference?) // DocumentId documentId = null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "DocumentId").WithArguments("DocumentId").WithLocation(9, 9), // (10,25): error CS0117: 'System.Threading.Tasks.Task' does not contain a definition for 'Run' // if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) Diagnostic(ErrorCode.ERR_NoSuchMember, "Run").WithArguments("System.Threading.Tasks.Task", "Run").WithLocation(10, 25), // (10,14): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)").WithLocation(10, 14), // (6,54): warning CS0649: Field 'TestDataPointBase.integrationService' is never assigned to, and will always have its default value null // private readonly IVisualStudioIntegrationService integrationService; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "integrationService").WithArguments("TestDataPointBase.integrationService", "null").WithLocation(6, 54) ); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_01() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { var tmp = new C(); tmp.M((a, b) => c.Add); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular9); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (9,15): error CS1660: Cannot convert lambda expression to type 'IList<C>' because it is not a delegate type // tmp.M((a, b) => c.Add); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(a, b) => c.Add").WithArguments("lambda expression", "System.Collections.Generic.IList<C>").WithLocation(9, 15)); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body; var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_02() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { int tmp = c.Add; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer.Value; var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_03() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { var tmp = new C(); tmp.M((a, b) => c.Add); } static void M(System.Func<int, int, System.Action<C>> x) {} } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body; var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(); class C { static void MD(D d) { } static int i = 0; static void M() { MD(() => ref i); MD(() => { return ref i; }); MD(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceDelegateCreation() { var text = @" delegate ref int D(); class C { static int i = 0; static void M() { var d = new D(() => ref i); d = new D(() => { return ref i; }); d = new D(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceOverloadedDelegateType() { var text = @" delegate ref int D(); delegate int E(); class C { static void M(D d) { } static void M(E e) { } static int i = 0; static void M() { M(() => ref i); M(() => { return ref i; }); M(delegate { return ref i; }); M(() => i); M(() => { return i; }); M(delegate { return i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceArgumentBadRefReturn() { var text = @" delegate int E(); class C { static void ME(E e) { } static int i = 0; static void M() { ME(() => ref i); ME(() => { return ref i; }); ME(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (11,22): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(() => ref i); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(11, 22), // (12,20): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(() => { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(12, 20), // (13,23): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(delegate { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(13, 23)); } [Fact] public void RefLambdaInferenceDelegateCreationBadRefReturn() { var text = @" delegate int E(); class C { static int i = 0; static void M() { var e = new E(() => ref i); e = new E(() => { return ref i; }); e = new E(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (9,33): error CS8149: By-reference returns may only be used in by-reference returning methods. // var e = new E(() => ref i); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(9, 33), // (10,27): error CS8149: By-reference returns may only be used in by-reference returning methods. // e = new E(() => { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(10, 27), // (11,30): error CS8149: By-reference returns may only be used in by-reference returning methods. // e = new E(delegate { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(11, 30)); } [Fact] public void RefLambdaInferenceMixedByValueAndByRefReturns() { var text = @" delegate ref int D(); delegate int E(); class C { static void MD(D e) { } static void ME(E e) { } static int i = 0; static void M() { MD(() => { if (i == 0) { return ref i; } return i; }); ME(() => { if (i == 0) { return ref i; } return i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (18,13): error CS8150: By-value returns may only be used in by-value returning methods. // return i; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(18, 13), // (23,17): error CS8149: By-reference returns may only be used in by-reference returning methods. // return ref i; Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(23, 17)); } [WorkItem(1112875, "DevDiv")] [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")] [Fact] public void Bug1112875_1() { var comp = CreateCompilation(@" using System; class Program { static void Main() { ICloneable c = """"; Goo(() => (c.Clone()), null); } static void Goo(Action x, string y) { } static void Goo(Func<object> x, object y) { Console.WriteLine(42); } }", options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")] [Fact] public void Bug1112875_2() { var comp = CreateCompilation(@" class Program { void M() { var d = new System.Action(() => (new object())); } } "); comp.VerifyDiagnostics( // (6,41): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // var d = new System.Action(() => (new object())); Diagnostic(ErrorCode.ERR_IllegalStatement, "(new object())").WithLocation(6, 41)); } [WorkItem(1830, "https://github.com/dotnet/roslyn/issues/1830")] [Fact] public void FuncOfVoid() { var comp = CreateCompilation(@" using System; class Program { void M1<T>(Func<T> f) {} void Main(string[] args) { M1(() => { return System.Console.Beep(); }); } } "); comp.VerifyDiagnostics( // (8,27): error CS4029: Cannot return an expression of type 'void' // M1(() => { return System.Console.Beep(); }); Diagnostic(ErrorCode.ERR_CantReturnVoid, "System.Console.Beep()").WithLocation(8, 27) ); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_01() { var src = @" using System; class Program { static Func<Program, string> stuff() { return a => a. } } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,23): error CS1001: Identifier expected // return a => a. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 23), // (8,23): error CS1002: ; expected // return a => a. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 23) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_02() { var src = @" using System; class Program { static void stuff() { Func<Program, string> l = a => a. } } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,42): error CS1001: Identifier expected // Func<Program, string> l = a => a. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 42), // (8,42): error CS1002: ; expected // Func<Program, string> l = a => a. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 42) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_03() { var src = @" using System; class Program { static void stuff() { M1(a => a.); } static void M1(Func<Program, string> l){} } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,20): error CS1001: Identifier expected // M1(a => a.); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 20) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_04() { var src = @" using System; class Program { static void stuff() { var l = (Func<Program, string>) (a => a.); } } "; var compilation = CreateCompilation(src); compilation.VerifyDiagnostics( // (8,49): error CS1001: Identifier expected // var l = (Func<Program, string>) (a => a.); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 49) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact] [WorkItem(3826, "https://github.com/dotnet/roslyn/issues/3826")] public void ExpressionTreeSelfAssignmentShouldError() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<int, int>> x = y => y = y; } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (9,45): warning CS1717: Assignment made to same variable; did you mean to assign something else? // Expression<Func<int, int>> x = y => y = y; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y = y").WithLocation(9, 45), // (9,45): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> x = y => y = y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "y = y").WithLocation(9, 45)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2(default(Struct1))); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2(default(Struct1))); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(Struct1)").WithArguments("Struct1").WithLocation(8, 40)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructDefaultExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2(default)); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2(default)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 40)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructDefaultCastExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2((Struct1) default)); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,50): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2((Struct1) default)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 50)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructNewExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method((Class1 c) => c.Method2(new Struct1())); } public void Method2(Struct1 s1) { } public static void Method<T>(Expression<Action<T>> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Class1 c) => c.Method2(new Struct1())); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "new Struct1()").WithArguments("Struct1").WithLocation(8, 40)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructParamExpressionTree() { var text = @" using System.Linq.Expressions; public delegate void Delegate1(Struct1 s); public class Class1 { public void Method1() { Method((Struct1 s) => Method2()); } public void Method2() { } public static void Method(Expression<Delegate1> expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,25): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'. // Method((Struct1 s) => Method2()); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "s").WithArguments("Struct1").WithLocation(9, 25)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void RefStructParamLambda() { var text = @" public delegate void Delegate1(Struct1 s); public class Class1 { public void Method1() { Method((Struct1 s) => Method2()); } public void Method2() { } public static void Method(Delegate1 expression) { } } public ref struct Struct1 { } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void TypedReferenceExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class Class1 { public void Method1() { Method(() => Method2(default)); } public void Method2(TypedReference tr) { } public static void Method(Expression<Action> expression) { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,30): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Method(() => Method2(default)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("TypedReference").WithLocation(8, 30)); } [Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")] public void TypedReferenceParamExpressionTree() { var text = @" using System; using System.Linq.Expressions; public delegate void Delegate1(TypedReference tr); public class Class1 { public void Method1() { Method((TypedReference tr) => Method2()); } public void Method2() { } public static void Method(Expression<Delegate1> expression) { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,32): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Method((TypedReference tr) => Method2()); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "tr").WithArguments("TypedReference").WithLocation(9, 32)); } [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")] public void ReturnInferenceCache_Dynamic_vs_Object_01() { var source = @" using System; using System.Collections; using System.Collections.Generic; public static class Program { public static void Main(string[] args) { IEnumerable<dynamic> dynX = null; // CS1061 'object' does not contain a definition for 'Text'... // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic> var result = dynX.Select(_ => _.Text); } public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector) { throw new NotImplementedException(); } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector) { System.Console.WriteLine(""Select<T, S>""); return null; } } public interface IColumn { } "; var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: "Select<T, S>"); } [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")] public void ReturnInferenceCache_Dynamic_vs_Object_02() { var source = @" using System; using System.Collections; using System.Collections.Generic; public static class Program { public static void Main(string[] args) { IEnumerable<dynamic> dynX = null; // CS1061 'object' does not contain a definition for 'Text'... // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic> var result = dynX.Select(_ => _.Text); } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector) { System.Console.WriteLine(""Select<T, S>""); return null; } public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector) { throw new NotImplementedException(); } } public interface IColumn { } "; var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: "Select<T, S>"); } [Fact, WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void SyntaxAndSemanticErrorInLambda() { var source = @" using System; class C { public static void Main(string[] args) { Action a = () => { new X().ToString() }; a(); } } "; CreateCompilation(source).VerifyDiagnostics( // (7,47): error CS1002: ; expected // Action a = () => { new X().ToString() }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 47), // (7,32): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // Action a = () => { new X().ToString() }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(7, 32) ); } [Fact, WorkItem(4527, "https://github.com/dotnet/roslyn/issues/4527")] public void AnonymousMethodExpressionWithoutParameterList() { var source = @" using System; using System.Threading.Tasks; namespace RoslynAsyncDelegate { class Program { static EventHandler MyEvent; static void Main(string[] args) { MyEvent += async delegate { await Task.Delay(0); }; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AnonymousMethodExpression)).Single(); Assert.Equal("async delegate { await Task.Delay(0); }", node1.ToString()); Assert.Equal("void System.EventHandler.Invoke(System.Object sender, System.EventArgs e)", model.GetTypeInfo(node1).ConvertedType.GetMembers("Invoke").Single().ToTestDisplayString()); var lambdaParameters = ((IMethodSymbol)(model.GetSymbolInfo(node1)).Symbol).Parameters; Assert.Equal("System.Object <p0>", lambdaParameters[0].ToTestDisplayString()); Assert.Equal("System.EventArgs <p1>", lambdaParameters[1].ToTestDisplayString()); CompileAndVerify(compilation); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError01() { var source = @"using System.Linq; class C { C() { string.Empty.Select(() => { new Unbound1 }); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,58): error CS1526: A new expression requires (), [], or {} after type // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_BadNewExpr, "}").WithLocation(2, 58), // (2,58): error CS1002: ; expected // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 58), // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?) // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError02() { var source = @"using System.Linq; class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,62): error CS1002: ; expected // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 62), // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?) // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError03() { var source = @"using System.Linq; class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,61): error CS1003: Syntax error, ',' expected // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_SyntaxError, "Unbound2").WithArguments(",", "").WithLocation(2, 61), // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52), // (2,61): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 61), // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError04() { var source = @"using System.Linq; class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52), // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError05() { var source = @"using System.Linq; class C { C() { Unbound2.Select(x => Unbound1); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (2,17): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { Unbound2.Select(x => Unbound1); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 17), // (2,38): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { Unbound2.Select(x => Unbound1); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 38) ); } [Fact] [WorkItem(4480, "https://github.com/dotnet/roslyn/issues/4480")] public void TestLambdaWithError06() { var source = @"class Program { static void Main(string[] args) { // completion should work even in a syntactically invalid lambda var handler = new MyDelegateType((s, e) => { e. }); } } public delegate void MyDelegateType( object sender, MyArgumentType e ); public class MyArgumentType { public int SomePublicMember; }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source) .VerifyDiagnostics( // var handler = new MyDelegateType((s, e) => { e. }); Diagnostic(ErrorCode.ERR_IdentifierExpected, "}").WithLocation(6, 57), // (6,57): error CS1002: ; expected // var handler = new MyDelegateType((s, e) => { e. }); Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(6, 57) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("e", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal("MyArgumentType", typeInfo.Type.Name); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.NotEmpty(typeInfo.Type.GetMembers("SomePublicMember")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError07() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var parameter = new List<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public static class Enumerable { public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue) { return default(TSource); } public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource defaultValue) { return default(TSource); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (9,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError08() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var parameter = new List<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public static class Enumerable { public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, params TSource[] defaultValue) { return default(TSource); } public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, params TSource[] defaultValue) { return default(TSource); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (9,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError09() { var source = @"using System; public static class Program { public static void Main() { var parameter = new MyList<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public class MyList<TSource> { public TSource FirstOrDefault(TSource defaultValue) { return default(TSource); } public TSource FirstOrDefault(Func<TSource, bool> predicate, TSource defaultValue) { return default(TSource); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError10() { var source = @"using System; public static class Program { public static void Main() { var parameter = new MyList<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public class MyList<TSource> { public TSource FirstOrDefault(params TSource[] defaultValue) { return default(TSource); } public TSource FirstOrDefault(Func<TSource, bool> predicate, params TSource[] defaultValue) { return default(TSource); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(557, "https://github.com/dotnet/roslyn/issues/557")] public void TestLambdaWithError11() { var source = @"using System.Linq; public static class Program { public static void Main() { var x = new { X = """".Select(c => c. Y = 0, }; } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("c", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Struct, typeInfo.Type.TypeKind); Assert.Equal("Char", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("IsHighSurrogate")); // check it is the char we know and love } [Fact] [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")] public void TestLambdaWithError12() { var source = @"using System.Linq; class Program { static void Main(string[] args) { var z = args.Select(a => a. var goo = } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("a", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] [Fact] public void TestLambdaWithError13() { // These tests ensure we attempt to perform type inference and bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is more than one method in the method group. // See https://github.com/dotnet/roslyn/issues/11901 for the case of one method in the group var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1(x => x, 1); // too many args t.X2(x => x); // too few args t.M2(string.Empty, x => x, 1); // too many args t.M3(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} // Ensure we have more than one method in the method group public void M2() {} public void M3() {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; // Ensure we have more than one method in the method group public static void X1(this object self) {} public static void X2(this object self) {} } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")] public void TestLambdaWithError15() { // These tests ensure we attempt to perform type inference and bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is exactly one method in the method group. var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1(x => x, 1); // too many args t.X2(x => x); // too few args t.M2(string.Empty, x => x, 1); // too many args t.M3(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")] public void TestLambdaWithError16() { // These tests ensure we use the substituted method to bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is exactly one method in the method group. var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1<string>(x => x, 1); // too many args t.X2<string>(x => x); // too few args t.M2<string>(string.Empty, x => x, 1); // too many args t.M3<string>(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError17() { var source = @"using System; class Program { static void Main(string[] args) { Ma(action: (x, y) => x.ToString(), t: string.Empty); Mb(action: (x, y) => x.ToString(), t: string.Empty); } static void Ma<T>(T t, Action<T, T, int> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mb() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError18() { var source = @"using System; class Program { static void Main(string[] args) { Ma(string.Empty, (x, y) => x.ToString()); Mb(string.Empty, (x, y) => x.ToString()); } static void Ma<T>(T t, Action<T, T, int> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mb() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError19() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { Ma(string.Empty, (x, y) => x.ToString()); Mb(string.Empty, (x, y) => x.ToString()); Mc(string.Empty, (x, y) => x.ToString()); } static void Ma<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mc<T>(T t, Expression<Action<T, T, int>> action) { } static void Mc() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } // See MaxParameterListsForErrorRecovery. [Fact] public void BuildArgumentsForErrorRecovery_ManyOverloads() { BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery - 1, tooMany: false); BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery, tooMany: true); } private void BuildArgumentsForErrorRecovery_ManyOverloads_Internal(int n, bool tooMany) { var builder = new StringBuilder(); builder.AppendLine("using System;"); for (int i = 0; i < n; i++) { builder.AppendLine($"class C{i} {{ }}"); } builder.Append( @"class A { } class B { } class C { void M() { F(1, (t, a, b, c) => { }); var o = this[(a, b, c) => { }]; } "); // Too few parameters. AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, C{i}> a) {{ }}"); AppendLines(builder, n, i => $" object this[Action<A, C{i}> a] => {i}"); // Type inference failure. AppendLines(builder, n, i => $" void F<T, U>(T t, Action<T, U, C{i}> a) where U : T {{ }}"); // Too many parameters. AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, B, C, C{i}> a) {{ }}"); AppendLines(builder, n, i => $" object this[Action<A, B, C, C{i}> a] => {i}"); builder.AppendLine("}"); var source = builder.ToString(); var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambdas = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().ToArray(); // F(1, (t, a, b, c) => { }); var lambda = lambdas[0]; var parameters = lambda.ParameterList.Parameters; var parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]); Assert.False(parameter.Type.IsErrorType()); Assert.Equal("System.Int32 t", parameter.ToTestDisplayString()); parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[1]); Assert.False(parameter.Type.IsErrorType()); Assert.Equal("A a", parameter.ToTestDisplayString()); parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[3]); Assert.Equal(tooMany, parameter.Type.IsErrorType()); Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString()); // var o = this[(a, b, c) => { }]; lambda = lambdas[1]; parameters = lambda.ParameterList.Parameters; parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]); Assert.False(parameter.Type.IsErrorType()); Assert.Equal("A a", parameter.ToTestDisplayString()); parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[2]); Assert.Equal(tooMany, parameter.Type.IsErrorType()); Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString()); } private static void AppendLines(StringBuilder builder, int n, Func<int, string> getLine) { for (int i = 0; i < n; i++) { builder.AppendLine(getLine(i)); } } [Fact] [WorkItem(13797, "https://github.com/dotnet/roslyn/issues/13797")] public void DelegateAsAction() { var source = @" using System; public static class C { public static void M() => Dispatch(delegate { }); public static T Dispatch<T>(Func<T> func) => default(T); public static void Dispatch(Action func) { } }"; var comp = CreateCompilation(source); CompileAndVerify(comp); } [Fact, WorkItem(278481, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=278481")] public void LambdaReturningNull_1() { var src = @" public static class ExtensionMethods { public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Linq.IQueryable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector, System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) { return null; } public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Linq.IQueryable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector, System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector) { System.Console.WriteLine(""1""); return null; } public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Collections.Generic.IEnumerable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> fullResultSelector, System.Func<TOuter, TResult> partialResultSelector) { System.Console.WriteLine(""2""); return null; } public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Collections.Generic.IEnumerable<TOuter> outerQueryable, System.Collections.Generic.IEnumerable<TInner> innerQueryable, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> resultSelector) { return null; } } partial class C { public static void Main() { System.Linq.IQueryable<A> outerValue = null; System.Linq.IQueryable<B> innerValues = null; outerValue.LeftOuterJoin(innerValues, co => co.id, coa => coa.id, (co, coa) => null, co => co); } } class A { public int id=2; } class B { public int id = 2; }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "1"); } [Fact, WorkItem(296550, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296550")] public void LambdaReturningNull_2() { var src = @" class Test1<T> { public void M1(System.Func<T> x) {} public void M1<S>(System.Func<S> x) {} public void M2<S>(System.Func<S> x) {} public void M2(System.Func<T> x) {} } class Test2 : Test1<System.> { void Main() { M1(()=> null); M2(()=> null); } } "; var comp = CreateCompilation(src, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (10,32): error CS1001: Identifier expected // class Test2 : Test1<System.> Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(10, 32) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void LambdaSquigglesArea() { var src = @" class C { void M() { System.Func<bool, System.Action<bool>> x = x1 => x2 => { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,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 // System.Func<bool, System.Action<bool>> x = x1 => x2 => Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x2 =>").WithArguments("lambda expression").WithLocation(6, 58) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void LambdaSquigglesAreaInAsync() { var src = @" class C { void M() { System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 => { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,93): error CS4010: Cannot convert async lambda expression to delegate type 'Task<Action<bool>>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Task<Action<bool>>'. // System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 => Diagnostic(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, "x2 =>").WithArguments("lambda expression", "System.Threading.Tasks.Task<System.Action<bool>>").WithLocation(6, 93), // (6,90): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 => Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 90) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void DelegateSquigglesArea() { var src = @" class C { void M() { System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2) { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,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 // System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2) Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate(bool x2)").WithArguments("lambda expression").WithLocation(6, 58) ); } [Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")] public void DelegateWithoutArgumentsSquigglesArea() { var src = @" class C { void M() { System.Func<bool, System.Action> x = x1 => delegate { error(); }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'error' does not exist in the current context // error(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13), // (6,52): 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 // System.Func<bool, System.Action> x = x1 => delegate Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate").WithArguments("lambda expression").WithLocation(6, 52) ); } [Fact] public void ThrowExpression_Lambda() { var src = @"using System; class C { public static void Main() { Action a = () => throw new Exception(""1""); try { a(); } catch (Exception ex) { Console.Write(ex.Message); } Func<int, int> b = x => throw new Exception(""2""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } b = (int x) => throw new Exception(""3""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } b = (x) => throw new Exception(""4""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "1234"); } [Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] public void InMalformedEmbeddedStatement_01() { var source = @" class Program { void method1() { if (method2()) .Any(b => b.ContentType, out var chars) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single(); var model = comp.GetSemanticModel(tree); Assert.Equal("ContentType", contentType.ToString()); Assert.Null(model.GetSymbolInfo(contentType).Symbol); Assert.Equal(TypeKind.Error, model.GetTypeInfo(contentType).Type.TypeKind); ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single(); model = comp.GetSemanticModel(tree); Assert.Equal("b", b.ToString()); ISymbol symbol = model.GetSymbolInfo(b).Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("? b", symbol.ToTestDisplayString()); Assert.Equal(TypeKind.Error, model.GetTypeInfo(b).Type.TypeKind); ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); model = comp.GetSemanticModel(tree); symbol = model.GetDeclaredSymbol(parameterSyntax); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("? b", symbol.ToTestDisplayString()); } [Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")] public void InMalformedEmbeddedStatement_02() { var source = @" class Program { void method1() { if (method2()) .Any(b => b.ContentType, out var chars) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single(); var model = comp.GetSemanticModel(tree); Assert.Equal("ContentType", contentType.ToString()); var lambda = (IMethodSymbol)model.GetEnclosingSymbol(contentType.SpanStart); Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind); ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single(); model = comp.GetSemanticModel(tree); Assert.Equal("b", b.ToString()); lambda = (IMethodSymbol)model.GetEnclosingSymbol(b.SpanStart); Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind); model = comp.GetSemanticModel(tree); ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); Assert.Equal("void Program.method1()", model.GetEnclosingSymbol(parameterSyntax.SpanStart).ToTestDisplayString()); } [Fact] public void ShadowNames_Local() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M() { Action a1 = () => { object x = 0; }; // local Action<string> a2 = x => { }; // parameter Action<string> a3 = (string x) => { }; // parameter object x = null; Action a4 = () => { void x() { } }; // method Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = () => { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36), // (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = x => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29), // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a3 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37), // (13,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a4 = () => { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(13, 34), // (14,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(14, 38)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Parameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static Action<object> F = (object x) => { Action a1 = () => { object x = 0; }; // local Action<string> a2 = x => { }; // parameter Action<string> a3 = (string x) => { }; // parameter Action a4 = () => { void x() { } }; // method Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable }; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = () => { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36), // (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = x => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29), // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a3 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37), // (13,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 38)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_TypeParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M<x>() { Action a1 = () => { object x = 0; }; // local Action<string> a2 = x => { }; // parameter Action<string> a3 = (string x) => { }; // parameter Action a4 = () => { void x() { } }; // method Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,36): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a1 = () => { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 36), // (10,29): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> a2 = x => { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 29), // (11,37): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> a3 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 37), // (12,34): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a4 = () => { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(12, 34), // (13,38): error CS1948: The range variable 'x' cannot have the same name as a method type parameter // Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(13, 38)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_QueryParameter() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void Main(string[] args) { _ = from x in args select (Action)(() => { object x = 0; }); // local _ = from x in args select (Action<string>)(x => { }); // parameter _ = from x in args select (Action<string>)((string x) => { }); // parameter _ = from x in args select (Action)(() => { void x() { } }); // method _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,59): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // _ = from x in args select (Action)(() => { object x = 0; }); // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 59), // (10,52): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // _ = from x in args select (Action<string>)(x => { }); // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 52), // (11,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // _ = from x in args select (Action<string>)((string x) => { }); // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 60), // (13,61): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 61)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Local_Delegate() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M() { object x = null; Action a1 = delegate() { object x = 0; }; // local Action<string> a2 = delegate(string x) { }; // parameter Action a3 = delegate() { void x() { } }; // method Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (10,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = delegate() { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 41), // (11,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = delegate(string x) { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 45), // (12,39): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a3 = delegate() { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 39), // (13,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 43)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Parameter_Delegate() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static Action<object> F = (object x) => { Action a1 = delegate() { object x = 0; }; // local Action<string> a2 = delegate(string x) { }; // parameter Action a3 = delegate() { void x() { } }; // method Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable }; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = delegate() { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 41), // (10,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> a2 = delegate(string x) { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 45), // (12,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 43)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_TypeParameter_Delegate() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; using System.Linq; class Program { static void M<x>() { Action a1 = delegate() { object x = 0; }; // local Action<string> a2 = delegate(string x) { }; // parameter Action a3 = delegate() { void x() { } }; // method Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (9,41): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a1 = delegate() { object x = 0; }; // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 41), // (10,45): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> a2 = delegate(string x) { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 45), // (11,39): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a3 = delegate() { void x() { } }; // method Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 39), // (12,43): error CS1948: The range variable 'x' cannot have the same name as a method type parameter // Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 43)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LambdaInsideLambda() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M<T>(object x) { Action a1 = () => { Action b1 = () => { object x = 1; }; // local Action<string> b2 = (string x) => { }; // parameter }; Action a2 = () => { Action b3 = () => { object T = 3; }; // local Action<string> b4 = T => { }; // parameter }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (10,40): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action b1 = () => { object x = 1; }; // local Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 40), // (11,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<string> b2 = (string x) => { }; // parameter Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 41), // (15,40): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action b3 = () => { object T = 3; }; // local Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 40), // (16,33): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<string> b4 = T => { }; // parameter Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(16, 33)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Underscore_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, Func<int, int>> f = _ => _ => _; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,44): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, Func<int, int>> f = _ => _ => _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 44)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Underscore_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, int, int> f = (_, _) => 0; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,37): error CS8370: Feature 'lambda discard parameters' is not available in C# 7.3. Please use language version 9.0 or greater. // Func<int, int, int> f = (_, _) => 0; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "_").WithArguments("lambda discard parameters", "9.0").WithLocation(8, 37)); comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void ShadowNames_Nested_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, Func<int, Func<int, int>>> f = x => x => x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,55): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, Func<int, Func<int, int>>> f = x => x => x => x; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 55), // (8,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, Func<int, Func<int, int>>> f = x => x => x => x; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 60)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_Nested_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (8,87): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 87), // (8,94): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(8, 94), // (8,97): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 97)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LambdaInsideLocalFunction_01() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M() { void F1() { object x = null; Action a1 = () => { int x = 0; }; } void F2<T>() { Action a2 = () => { int T = 0; }; } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action a1 = () => { int x = 0; }; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37), // (15,37): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action a2 = () => { int T = 0; }; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 37)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ShadowNames_LambdaInsideLocalFunction_02() { var source = @"#pragma warning disable 0219 #pragma warning disable 8321 using System; class Program { static void M<T>() { object x = null; void F() { Action<int> a1 = (int x) => { Action b1 = () => { int T = 0; }; }; Action a2 = () => { int x = 0; Action<int> b2 = (int T) => { }; }; } } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (11,35): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Action<int> a1 = (int x) => Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 35), // (13,41): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action b1 = () => { int T = 0; }; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(13, 41), // (17,21): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x = 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(17, 21), // (18,39): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter // Action<int> b2 = (int T) => { }; Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(18, 39)); comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void LambdaAttributes_01() { var sourceA = @"using System; class A : Attribute { } class B : Attribute { } partial class Program { static Delegate D1() => (Action)([A] () => { }); static Delegate D2(int x) => (Func<int, int, int>)((int y, [A][B] int z) => x); static Delegate D3() => (Action<int, object>)(([A]_, y) => { }); Delegate D4() => (Func<int>)([return: A][B] () => GetHashCode()); }"; var sourceB = @"using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; partial class Program { static string GetAttributeString(object a) { return a.GetType().FullName; } static void Report(Delegate d) { var m = d.Method; var forMethod = ToString(""method"", m.GetCustomAttributes(inherit: false)); var forReturn = ToString(""return"", m.ReturnTypeCustomAttributes.GetCustomAttributes(inherit: false)); var forParameters = ToString(""parameter"", m.GetParameters().SelectMany(p => p.GetCustomAttributes(inherit: false))); Console.WriteLine(""{0}:{1}{2}{3}"", m.Name, forMethod, forReturn, forParameters); } static string ToString(string target, IEnumerable<object> attributes) { var builder = new StringBuilder(); foreach (var attribute in attributes) builder.Append($"" [{target}: {attribute}]""); return builder.ToString(); } static void Main() { Report(D1()); Report(D2(0)); Report(D3()); Report(new Program().D4()); } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>(); var pairs = exprs.Select(e => (e, model.GetSymbolInfo(e).Symbol)).ToArray(); var expectedAttributes = new[] { "[A] () => { }: [method: A]", "(int y, [A][B] int z) => x: [parameter: A] [parameter: B]", "([A]_, y) => { }: [parameter: A]", "[return: A][B] () => GetHashCode(): [method: B] [return: A]", }; AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesInternal(p.Item1, p.Item2))); AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesPublic(p.Item1, p.Item2))); CompileAndVerify(comp, expectedOutput: @"<D1>b__0_0: [method: A] <D2>b__0: [parameter: A] [parameter: B] <D3>b__2_0: [parameter: A] <D4>b__3_0: [method: System.Runtime.CompilerServices.CompilerGeneratedAttribute] [method: B] [return: A]"); static string getAttributesInternal(LambdaExpressionSyntax expr, ISymbol symbol) { var method = symbol.GetSymbol<MethodSymbol>(); return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes())); } static string getAttributesPublic(LambdaExpressionSyntax expr, ISymbol symbol) { var method = (IMethodSymbol)symbol; return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes())); } static string format(LambdaExpressionSyntax expr, IEnumerable<object> methodAttributes, IEnumerable<object> returnAttributes, IEnumerable<object> parameterAttributes) { var forMethod = toString("method", methodAttributes); var forReturn = toString("return", returnAttributes); var forParameters = toString("parameter", parameterAttributes); return $"{expr}:{forMethod}{forReturn}{forParameters}"; } static string toString(string target, IEnumerable<object> attributes) { var builder = new StringBuilder(); foreach (var attribute in attributes) builder.Append($" [{target}: {attribute}]"); return builder.ToString(); } } [Fact] public void LambdaAttributes_02() { var source = @"using System; class AAttribute : Attribute { } class BAttribute : Attribute { } class C { static void Main() { Action<object, object> a; a = [A, B] (x, y) => { }; a = ([A] x, [B] y) => { }; a = (object x, [A][B] object y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,13): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = [A, B] (x, y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A, B]").WithArguments("lambda attributes", "10.0").WithLocation(9, 13), // (10,14): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = ([A] x, [B] y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(10, 14), // (10,21): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = ([A] x, [B] y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(10, 21), // (11,24): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = (object x, [A][B] object y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(11, 24), // (11,27): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater. // a = (object x, [A][B] object y) => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(11, 27)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void LambdaAttributes_03() { var source = @"using System; class AAttribute : Attribute { } class BAttribute : Attribute { } class C { static void Main() { Action<object, object> a = delegate (object x, [A][B] object y) { }; Func<object, object> f = [A][B] x => x; } }"; var expectedDiagnostics = new[] { // (8,56): error CS7014: Attributes are not valid in this context. // Action<object, object> a = delegate (object x, [A][B] object y) { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 56), // (8,59): error CS7014: Attributes are not valid in this context. // Action<object, object> a = delegate (object x, [A][B] object y) { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[B]").WithLocation(8, 59), // (9,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list. // Func<object, object> f = [A][B] x => x; Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[A]").WithLocation(9, 34), // (9,37): error CS8916: Attributes on lambda expressions require a parenthesized parameter list. // Func<object, object> f = [A][B] x => x; Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[B]").WithLocation(9, 37) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void LambdaAttributes_04() { var sourceA = @"namespace N1 { class A1Attribute : System.Attribute { } } namespace N2 { class A2Attribute : System.Attribute { } }"; var sourceB = @"using N1; using N2; class Program { static void Main() { System.Action a1 = [A1] () => { }; System.Action<object> a2 = ([A2] object obj) => { }; } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void LambdaAttributes_05() { var source = @"class Program { static void Main() { System.Action a1 = [A1] () => { }; System.Func<object> a2 = [return: A2] () => null; System.Action<object> a3 = ([A3] object obj) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,29): error CS0246: The type or namespace name 'A1Attribute' could not be found (are you missing a using directive or an assembly reference?) // System.Action a1 = [A1] () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1Attribute").WithLocation(5, 29), // (5,29): error CS0246: The type or namespace name 'A1' could not be found (are you missing a using directive or an assembly reference?) // System.Action a1 = [A1] () => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1").WithLocation(5, 29), // (6,43): error CS0246: The type or namespace name 'A2Attribute' could not be found (are you missing a using directive or an assembly reference?) // System.Func<object> a2 = [return: A2] () => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2Attribute").WithLocation(6, 43), // (6,43): error CS0246: The type or namespace name 'A2' could not be found (are you missing a using directive or an assembly reference?) // System.Func<object> a2 = [return: A2] () => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2").WithLocation(6, 43), // (7,38): error CS0246: The type or namespace name 'A3Attribute' could not be found (are you missing a using directive or an assembly reference?) // System.Action<object> a3 = ([A3] object obj) => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3Attribute").WithLocation(7, 38), // (7,38): error CS0246: The type or namespace name 'A3' could not be found (are you missing a using directive or an assembly reference?) // System.Action<object> a3 = ([A3] object obj) => { }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3").WithLocation(7, 38)); } [Fact] public void LambdaAttributes_06() { var source = @"using System; class AAttribute : Attribute { public AAttribute(Action a) { } } [A([B] () => { })] class BAttribute : Attribute { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,2): error CS0181: Attribute constructor parameter 'a' has type 'Action', which is not a valid attribute parameter type // [A([B] () => { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "System.Action").WithLocation(6, 2)); } [Fact] public void LambdaAttributes_BadAttributeLocation() { var source = @"using System; [AttributeUsage(AttributeTargets.Property)] class PropAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] class MethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.ReturnValue)] class ReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] class ParamAttribute : Attribute { } [AttributeUsage(AttributeTargets.GenericParameter)] class TypeParamAttribute : Attribute { } class Program { static void Main() { Action<object> a = [Prop] // 1 [Return] // 2 [Method] [return: Prop] // 3 [return: Return] [return: Method] // 4 ( [Param] [TypeParam] // 5 object o) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (23,14): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [Prop] // 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(23, 14), // (24,14): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations. // [Return] // 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(24, 14), // (26,22): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [return: Prop] // 3 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(26, 22), // (28,22): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations. // [return: Method] // 4 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(28, 22), // (31,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations. // [TypeParam] // 5 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(31, 14)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lambda = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var symbol = (IMethodSymbol)model.GetSymbolInfo(lambda).Symbol; Assert.NotNull(symbol); verifyAttributes(symbol.GetAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute"); verifyAttributes(symbol.GetReturnTypeAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute"); verifyAttributes(symbol.Parameters[0].GetAttributes(), "ParamAttribute", "TypeParamAttribute"); void verifyAttributes(ImmutableArray<AttributeData> attributes, params string[] expectedAttributeNames) { var actualAttributes = attributes.SelectAsArray(a => a.AttributeClass.GetSymbol()); var expectedAttributes = expectedAttributeNames.Select(n => comp.GetTypeByMetadataName(n)); AssertEx.Equal(expectedAttributes, actualAttributes); } } [Fact] public void LambdaAttributes_AttributeSemanticModel() { var source = @"using System; class AAttribute : Attribute { } class BAttribute : Attribute { } class CAttribute : Attribute { } class DAttribute : Attribute { } class Program { static void Main() { Action a = [A] () => { }; Func<object> b = [return: B] () => null; Action<object> c = ([C] object obj) => { }; Func<object, object> d = [D] x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (13,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list. // Func<object, object> d = [D] x => x; Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[D]").WithLocation(13, 34)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>(); var actualAttributes = attributeSyntaxes.Select(a => model.GetSymbolInfo(a).Symbol.GetSymbol<MethodSymbol>()).ToImmutableArray(); var expectedAttributes = new[] { "AAttribute", "BAttribute", "CAttribute", "DAttribute" }.Select(a => comp.GetTypeByMetadataName(a).InstanceConstructors.Single()).ToImmutableArray(); AssertEx.Equal(expectedAttributes, actualAttributes); } [Theory] [InlineData("Action a = [A] () => { };")] [InlineData("Func<object> f = [return: A] () => null;")] [InlineData("Action<int> a = ([A] int i) => { };")] public void LambdaAttributes_SpeculativeSemanticModel(string statement) { string source = $@"using System; class AAttribute : Attribute {{ }} class Program {{ static void Main() {{ {statement} }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var a = (IdentifierNameSyntax)tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name; Assert.Equal("A", a.Identifier.Text); var attrInfo = model.GetSymbolInfo(a); var attrType = comp.GetMember<NamedTypeSymbol>("AAttribute").GetPublicSymbol(); var attrCtor = attrType.GetMember(".ctor"); Assert.Equal(attrCtor, attrInfo.Symbol); // Assert that this is also true for the speculative semantic model var newTree = SyntaxFactory.ParseSyntaxTree(source + " "); var m = newTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model)); a = (IdentifierNameSyntax)newTree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name; Assert.Equal("A", a.Identifier.Text); // If we aren't using the right binder here, the compiler crashes going through the binder factory var info = model.GetSymbolInfo(a); // This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135 Assert.Equal(attrType, info.Symbol); } [Fact] public void LambdaAttributes_DisallowedAttributes() { var source = @"using System; using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : Attribute { } public class IsUnmanagedAttribute : Attribute { } public class IsByRefLikeAttribute : Attribute { } public class NullableContextAttribute : Attribute { public NullableContextAttribute(byte b) { } } } class Program { static void Main() { Action a = [IsReadOnly] // 1 [IsUnmanaged] // 2 [IsByRefLike] // 3 [Extension] // 4 [NullableContext(0)] // 5 () => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (15,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [IsReadOnly] // 1 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(15, 14), // (16,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] // 2 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(16, 14), // (17,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [IsByRefLike] // 3 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(17, 14), // (18,14): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] // 4 Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(18, 14), // (19,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage. // [NullableContext(0)] // 5 Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(19, 14)); } [Fact] public void LambdaAttributes_DisallowedSecurityAttributes() { var source = @"using System; using System.Security; class Program { static void Main() { Action a = [SecurityCritical] // 1 [SecuritySafeCriticalAttribute] // 2 async () => { }; // 3 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,14): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method. // [SecurityCritical] // 1 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(8, 14), // (9,14): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method. // [SecuritySafeCriticalAttribute] // 2 Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(9, 14), // (10,22): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async () => { }; // 3 Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(10, 22)); } [Fact] public void LambdaAttributes_ObsoleteAttribute() { var source = @"using System; class Program { static void Report(Action a) { foreach (var attribute in a.Method.GetCustomAttributes(inherit: false)) Console.Write(attribute); } static void Main() { Report([Obsolete] () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.ObsoleteAttribute"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol; Assert.Equal("System.ObsoleteAttribute", symbol.GetAttributes().Single().ToString()); } [Fact] public void LambdaParameterAttributes_Conditional() { var source = @"using System; using System.Diagnostics; class Program { static void Report(Action a) { } static void Main() { Report([Conditional(""DEBUG"")] static () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,17): error CS0577: The Conditional attribute is not valid on 'lambda expression' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // Report([Conditional("DEBUG")] static () => { }); Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional(""DEBUG"")").WithArguments("lambda expression").WithLocation(10, 17)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single(); Assert.Equal(new[] { "DEBUG" }, lambda.GetAppliedConditionalSymbols()); } [Fact] public void LambdaAttributes_WellKnownAttributes() { var sourceA = @"using System; using System.Runtime.InteropServices; using System.Security; class Program { static void Main() { Action a1 = [DllImport(""MyModule.dll"")] static () => { }; Action a2 = [DynamicSecurityMethod] () => { }; Action a3 = [SuppressUnmanagedCodeSecurity] () => { }; Func<object> a4 = [return: MarshalAs((short)0)] () => null; } }"; var sourceB = @"namespace System.Security { internal class DynamicSecurityMethodAttribute : Attribute { } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // Action a1 = [DllImport("MyModule.dll")] static () => { }; Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(8, 22)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(4, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Null(lambdas[0].GetDllImportData()); // [DllImport] is ignored if there are errors. Assert.True(lambdas[1].RequiresSecurityObject); Assert.True(lambdas[2].HasDeclarativeSecurity); Assert.Equal(default, lambdas[3].ReturnValueMarshallingInformation.UnmanagedType); } [Fact] public void LambdaAttributes_Permissions() { var source = @"#pragma warning disable 618 using System; using System.Security.Permissions; class Program { static void Main() { Action a1 = [PermissionSet(SecurityAction.Deny)] () => { }; } }"; var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single(); Assert.NotEmpty(lambda.GetSecurityInformation()); } [Fact] public void LambdaAttributes_NullableAttributes_01() { var source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Func<object> a1 = [return: MaybeNull][return: NotNull] () => null; Func<object, object> a2 = [return: NotNullIfNotNull(""obj"")] (object obj) => obj; Func<bool> a4 = [MemberNotNull(""x"")][MemberNotNullWhen(false, ""y"")][MemberNotNullWhen(true, ""z"")] () => true; } }"; var comp = CreateCompilation( new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition, NotNullIfNotNullAttributeDefinition, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(3, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Equal(FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull, lambdas[0].ReturnTypeFlowAnalysisAnnotations); Assert.Equal(new[] { "obj" }, lambdas[1].ReturnNotNullIfParameterNotNull); Assert.Equal(new[] { "x" }, lambdas[2].NotNullMembers); Assert.Equal(new[] { "y" }, lambdas[2].NotNullWhenFalseMembers); Assert.Equal(new[] { "z" }, lambdas[2].NotNullWhenTrueMembers); } [Fact] public void LambdaAttributes_NullableAttributes_02() { var source = @"#nullable enable using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Func<object> a1 = [return: MaybeNull] () => null; Func<object?> a2 = [return: NotNull] () => null; } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Report WRN_NullReferenceReturn for a2, not for a1. comp.VerifyDiagnostics( // (8,53): warning CS8603: Possible null reference return. // Func<object> a1 = [return: MaybeNull] () => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 53)); } [Fact] public void LambdaAttributes_NullableAttributes_03() { var source = @"#nullable enable using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Action<object> a1 = ([AllowNull] x) => { x.ToString(); }; Action<object?> a2 = ([DisallowNull] x) => { x.ToString(); }; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Report nullability mismatch warning assigning lambda to a2. comp.VerifyDiagnostics( // (8,50): warning CS8602: Dereference of a possibly null reference. // Action<object> a1 = ([AllowNull] x) => { x.ToString(); }; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 50)); } [WorkItem(55013, "https://github.com/dotnet/roslyn/issues/55013")] [Fact] public void NullableTypeArraySwitchPattern() { var source = @"#nullable enable class C { object? field; string Prop => field switch { string?[] a => ""a"" }; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // object? field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 13), // (5,26): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // string Prop => field switch Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 26)); } [Fact] public void LambdaAttributes_DoesNotReturn() { var source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Action a1 = [DoesNotReturn] () => { }; Action a2 = [DoesNotReturn] () => throw new Exception(); } }"; var comp = CreateCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Report warning that lambda expression in a1 initializer returns. comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(2, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[0].FlowAnalysisAnnotations); Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[1].FlowAnalysisAnnotations); } [Fact] public void LambdaAttributes_UnmanagedCallersOnly() { var source = @"using System; using System.Runtime.InteropServices; class Program { static void Main() { Action a = [UnmanagedCallersOnly] static () => { }; } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,21): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // Action a = [UnmanagedCallersOnly] static () => { }; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 21)); } [Fact] public void LambdaParameterAttributes_OptionalAndDefaultValueAttributes() { var source = @"using System; using System.Runtime.InteropServices; class Program { static void Main() { Action<int> a1 = ([Optional, DefaultParameterValue(2)] int i) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single(); var parameter = (SourceParameterSymbol)lambda.Parameters[0]; Assert.True(parameter.HasOptionalAttribute); Assert.False(parameter.HasExplicitDefaultValue); Assert.Equal(2, parameter.DefaultValueFromAttributes.Value); } [ConditionalFact(typeof(DesktopOnly))] public void LambdaParameterAttributes_WellKnownAttributes() { var source = @"using System; using System.Runtime.CompilerServices; class Program { static void Main() { Action<object> a1 = ([IDispatchConstant] object obj) => { }; Action<object> a2 = ([IUnknownConstant] object obj) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(2, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.True(lambdas[0].Parameters[0].IsIDispatchConstant); Assert.True(lambdas[1].Parameters[0].IsIUnknownConstant); } [Fact] public void LambdaParameterAttributes_NullableAttributes_01() { var source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void Main() { Action<object> a1 = ([AllowNull][MaybeNullWhen(false)] object obj) => { }; Action<object, object> a2 = (object x, [NotNullIfNotNull(""x"")] object y) => { }; } }"; var comp = CreateCompilation( new[] { source, AllowNullAttributeDefinition, MaybeNullWhenAttributeDefinition, NotNullIfNotNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray(); Assert.Equal(2, exprs.Length); var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)); Assert.Equal(FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.MaybeNullWhenFalse, lambdas[0].Parameters[0].FlowAnalysisAnnotations); Assert.Equal(new[] { "x" }, lambdas[1].Parameters[1].NotNullIfParameterNotNull); } [Fact] public void LambdaParameterAttributes_NullableAttributes_02() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; delegate bool D(out object? obj); class Program { static void Main() { D d = ([NotNullWhen(true)] out object? obj) => { obj = null; return true; }; } }"; var comp = CreateCompilation(new[] { source, NotNullWhenAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/52827: Should report WRN_ParameterConditionallyDisallowsNull. comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var lambda = GetLambdaSymbol(model, expr); Assert.Equal(FlowAnalysisAnnotations.NotNullWhenTrue, lambda.Parameters[0].FlowAnalysisAnnotations); } [Fact] public void LambdaReturnType_01() { var source = @"using System; class Program { static void F<T>() { Func<T> f1 = T () => default; Func<T, T> f2 = T (x) => { return x; }; Func<T, T> f3 = T (T x) => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,22): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // Func<T> f1 = T () => default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(6, 22), // (7,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // Func<T, T> f2 = T (x) => { return x; }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(7, 25), // (8,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // Func<T, T> f3 = T (T x) => x; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(8, 25)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void LambdaReturnType_02() { var source = @"using System; class Program { static void F<T, U>() { Func<T> f1; Func<U> f2; f1 = T () => default; f2 = T () => default; f1 = U () => default; f2 = U () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type // f2 = T () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14), // (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type // f1 = U () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14)); } [Fact] public void LambdaReturnType_03() { var source = @"using System; class Program { static void F<T, U>() where U : T { Func<T> f1; Func<U> f2; f1 = T () => default; f2 = T () => default; f1 = U () => default; f2 = U () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type // f2 = T () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14), // (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type // f1 = U () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14)); } [Fact] public void LambdaReturnType_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void F<T, U>() { Expression<Func<T>> e1; Expression<Func<U>> e2; e1 = T () => default; e2 = T () => default; e1 = U () => default; e2 = U () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<U>>' because the return type does not match the delegate return type // e2 = T () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<U>>").WithLocation(10, 14), // (11,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<T>>' because the return type does not match the delegate return type // e1 = U () => default; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<T>>").WithLocation(11, 14)); } [Fact] public void LambdaReturnType_05() { var source = @"#nullable enable using System; class Program { static void Main() { Func<dynamic> f1 = object () => default!; Func<(int, int)> f2 = (int X, int Y) () => default; Func<string?> f3 = string () => default!; Func<IntPtr> f4 = nint () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes). // Func<string?> f3 = string () => default!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => default!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28)); } [Fact] public void LambdaReturnType_06() { var source = @"#nullable enable using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<object>> e1 = dynamic () => default!; Expression<Func<(int X, int Y)>> e2 = (int, int) () => default; Expression<Func<string>> e3 = string? () => default; Expression<Func<nint>> e4 = IntPtr () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,39): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Expression<Func<string>> e3 = string? () => default; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => default").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 39)); } [Fact] public void LambdaReturnType_07() { var source = @"#nullable enable using System; struct S<T> { } class Program { static void Main() { Delegate d1 = string? () => default; Delegate d2 = string () => default; Delegate d3 = S<object?> () => default(S<object?>); Delegate d4 = S<object?> () => default(S<object>); Delegate d5 = S<object> () => default(S<object?>); Delegate d6 = S<object> () => default(S<object>); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,36): warning CS8603: Possible null reference return. // Delegate d2 = string () => default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(9, 36), // (11,40): warning CS8619: Nullability of reference types in value of type 'S<object>' doesn't match target type 'S<object?>'. // Delegate d4 = S<object?> () => default(S<object>); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object>)").WithArguments("S<object>", "S<object?>").WithLocation(11, 40), // (12,39): warning CS8619: Nullability of reference types in value of type 'S<object?>' doesn't match target type 'S<object>'. // Delegate d5 = S<object> () => default(S<object?>); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object?>)").WithArguments("S<object?>", "S<object>").WithLocation(12, 39)); } [Fact] public void LambdaReturnType_08() { var source = @"#nullable enable using System; struct S<T> { } class Program { static void Main() { Func<string?> f1 = string? () => throw null!; Func<string?> f2 = string () => throw null!; Func<string> f3 = string? () => throw null!; Func<string> f4 = string () => throw null!; Func<S<object?>> f5 = S<object?> () => throw null!; Func<S<object?>> f6 = S<object> () => throw null!; Func<S<object>> f7 = S<object?> () => throw null!; Func<S<object>> f8 = S<object> () => throw null!; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes). // Func<string?> f2 = string () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => throw null!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28), // (10,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Func<string> f3 = string? () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => throw null!").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 27), // (13,31): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object?>>' (possibly because of nullability attributes). // Func<S<object?>> f6 = S<object> () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object> () => throw null!").WithArguments("lambda expression", "System.Func<S<object?>>").WithLocation(13, 31), // (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object>>' (possibly because of nullability attributes). // Func<S<object>> f7 = S<object?> () => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object?> () => throw null!").WithArguments("lambda expression", "System.Func<S<object>>").WithLocation(14, 30)); } [Fact] public void LambdaReturnType_09() { var source = @"#nullable enable struct S<T> { } delegate ref T D1<T>(); delegate ref readonly T D2<T>(); class Program { static void Main() { D1<S<object?>> f1 = (ref S<object?> () => throw null!); D1<S<object?>> f2 = (ref S<object> () => throw null!); D1<S<object>> f3 = (ref S<object?> () => throw null!); D1<S<object>> f4 = (ref S<object> () => throw null!); D2<S<object?>> f5 = (ref readonly S<object?> () => throw null!); D2<S<object?>> f6 = (ref readonly S<object> () => throw null!); D2<S<object>> f7 = (ref readonly S<object?> () => throw null!); D2<S<object>> f8 = (ref readonly S<object> () => throw null!); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object?>>' (possibly because of nullability attributes). // D1<S<object?>> f2 = (ref S<object> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object> () => throw null!").WithArguments("lambda expression", "D1<S<object?>>").WithLocation(10, 30), // (11,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object>>' (possibly because of nullability attributes). // D1<S<object>> f3 = (ref S<object?> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object?> () => throw null!").WithArguments("lambda expression", "D1<S<object>>").WithLocation(11, 29), // (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object?>>' (possibly because of nullability attributes). // D2<S<object?>> f6 = (ref readonly S<object> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object> () => throw null!").WithArguments("lambda expression", "D2<S<object?>>").WithLocation(14, 30), // (15,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object>>' (possibly because of nullability attributes). // D2<S<object>> f7 = (ref readonly S<object?> () => throw null!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object?> () => throw null!").WithArguments("lambda expression", "D2<S<object>>").WithLocation(15, 29)); } [Fact] public void LambdaReturnType_10() { var source = @"delegate T D1<T>(ref T t); delegate ref T D2<T>(ref T t); delegate ref readonly T D3<T>(ref T t); class Program { static void F<T>() { D1<T> d1; D2<T> d2; D3<T> d3; d1 = T (ref T t) => t; d2 = T (ref T t) => t; d3 = T (ref T t) => t; d1 = (ref T (ref T t) => ref t); d2 = (ref T (ref T t) => ref t); d3 = (ref T (ref T t) => ref t); d1 = (ref readonly T (ref T t) => ref t); d2 = (ref readonly T (ref T t) => ref t); d3 = (ref readonly T (ref T t) => ref t); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,14): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type // d2 = T (ref T t) => t; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D2<T>").WithLocation(12, 14), // (13,14): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type // d3 = T (ref T t) => t; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D3<T>").WithLocation(13, 14), // (14,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type // d1 = (ref T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(14, 15), // (16,15): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type // d3 = (ref T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D3<T>").WithLocation(16, 15), // (17,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type // d1 = (ref readonly T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(17, 15), // (18,15): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type // d2 = (ref readonly T (ref T t) => ref t); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D2<T>").WithLocation(18, 15)); } [Fact] public void LambdaReturnType_11() { var source = @"using System; class Program { static void Main() { Delegate d; d = (ref void () => { }); d = (ref readonly void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,14): error CS8917: The delegate type could not be inferred. // d = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 14), // (7,18): error CS1547: Keyword 'void' cannot be used in this context // d = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 18), // (8,14): error CS8917: The delegate type could not be inferred. // d = (ref readonly void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref readonly void () => { }").WithLocation(8, 14), // (8,27): error CS1547: Keyword 'void' cannot be used in this context // d = (ref readonly void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(8, 27)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void LambdaReturnType_12() { var source = @"using System; class Program { static void Main() { Delegate d; d = TypedReference () => throw null; d = RuntimeArgumentHandle () => throw null; d = ArgIterator () => throw null; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'TypedReference' // d = TypedReference () => throw null; Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference").WithLocation(7, 13), // (7,13): error CS8917: The delegate type could not be inferred. // d = TypedReference () => throw null; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "TypedReference () => throw null").WithLocation(7, 13), // (8,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'RuntimeArgumentHandle' // d = RuntimeArgumentHandle () => throw null; Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = RuntimeArgumentHandle () => throw null; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "RuntimeArgumentHandle () => throw null").WithLocation(8, 13), // (9,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'ArgIterator' // d = ArgIterator () => throw null; Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator").WithLocation(9, 13), // (9,13): error CS8917: The delegate type could not be inferred. // d = ArgIterator () => throw null; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ArgIterator () => throw null").WithLocation(9, 13)); } [Fact] public void LambdaReturnType_13() { var source = @"static class S { } delegate S D(); class Program { static void Main() { D d = S () => default; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,15): error CS0722: 'S': static types cannot be used as return types // D d = S () => default; Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S").WithArguments("S").WithLocation(7, 15)); } [Fact] public void LambdaReturnType_14() { var source = @"using System; class Program { static void Main() { Delegate d = async int () => 0; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,35): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // Delegate d = async int () => 0; Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=>").WithLocation(6, 35), // (6,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // Delegate d = async int () => 0; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 35)); } [Fact] public void LambdaReturnType_15() { var source = @"using System; using System.Threading.Tasks; delegate ref Task D(string s); class Program { static void Main() { Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,23): error CS8917: The delegate type could not be inferred. // Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "async ref Task (s) => { _ = s.Length; await Task.Yield(); }").WithLocation(8, 23), // (8,29): error CS1073: Unexpected token 'ref' // Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29), // (9,22): error CS1073: Unexpected token 'ref' // D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22)); } [Fact] public void LambdaReturnType_16() { var source = @"using System; using System.Threading.Tasks; delegate ref Task D(string s); class Program { static void Main() { Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,29): error CS1073: Unexpected token 'ref' // Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29), // (9,22): error CS1073: Unexpected token 'ref' // D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22)); } [Fact] public void LambdaReturnType_17() { var source = @"#nullable enable using System; class Program { static void F(string? x, string y) { Func<string?> f1 = string () => { if (x is null) return x; return y; }; Func<string> f2 = string? () => { if (x is not null) return x; return y; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes). // Func<string?> f1 = string () => { if (x is null) return x; return y; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => { if (x is null) return x; return y; }").WithArguments("lambda expression", "System.Func<string?>").WithLocation(7, 28), // (7,65): warning CS8603: Possible null reference return. // Func<string?> f1 = string () => { if (x is null) return x; return y; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(7, 65), // (8,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Func<string> f2 = string? () => { if (x is not null) return x; return y; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => { if (x is not null) return x; return y; }").WithArguments("lambda expression", "System.Func<string>").WithLocation(8, 27)); } [Fact] public void LambdaReturnType_CustomModifiers_01() { var sourceA = @".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { } .method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) Invoke () runtime managed { } .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } .method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { } }"; var refA = CompileIL(sourceA); var sourceB = @"class Program { static void F(D d) { System.Console.WriteLine(d()); } static void Main() { F(() => 1); F(int () => 2); } }"; CompileAndVerify(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 2"); } [Fact] public void LambdaReturnType_CustomModifiers_02() { var sourceA = @".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) Invoke () runtime managed { } .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } .method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { } }"; var refA = CompileIL(sourceA); var sourceB = @"class Program { static void F(D d) { System.Console.WriteLine(d()); } static void Main() { F(() => 1); F(int () => 2); } }"; var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,34): error CS0570: 'D.Invoke()' is not supported by the language // System.Console.WriteLine(d()); Diagnostic(ErrorCode.ERR_BindToBogus, "d()").WithArguments("D.Invoke()").WithLocation(5, 34), // (9,11): error CS0570: 'D.Invoke()' is not supported by the language // F(() => 1); Diagnostic(ErrorCode.ERR_BindToBogus, "() => 1").WithArguments("D.Invoke()").WithLocation(9, 11), // (10,11): error CS0570: 'D.Invoke()' is not supported by the language // F(int () => 2); Diagnostic(ErrorCode.ERR_BindToBogus, "int () => 2").WithArguments("D.Invoke()").WithLocation(10, 11)); } [Fact] public void LambdaReturnType_UseSiteErrors() { var sourceA = @".class public sealed A extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void F<T>(Func<T> f) { } static void Main() { F(A () => default); } }"; var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,11): error CS0648: 'A' is a type not supported by the language // F(A () => default); Diagnostic(ErrorCode.ERR_BogusType, "A").WithArguments("A").WithLocation(7, 11)); } [Fact] public void AsyncLambdaParameters_01() { var source = @"using System; using System.Threading.Tasks; delegate Task D(ref string s); class Program { static void Main() { Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,41): error CS1988: Async methods cannot have ref, in or out parameters // Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(8, 41), // (9,34): error CS1988: Async methods cannot have ref, in or out parameters // D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(9, 34)); } [ConditionalFact(typeof(DesktopOnly))] public void AsyncLambdaParameters_02() { var source = @"using System; using System.Threading.Tasks; delegate void D1(TypedReference r); delegate void D2(RuntimeArgumentHandle h); delegate void D3(ArgIterator i); class Program { static void Main() { D1 d1 = async (TypedReference r) => { await Task.Yield(); }; D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); }; D3 d3 = async (ArgIterator i) => { await Task.Yield(); }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (10,39): error CS4012: Parameters or locals of type 'TypedReference' cannot be declared in async methods or async lambda expressions. // D1 d1 = async (TypedReference r) => { await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "r").WithArguments("System.TypedReference").WithLocation(10, 39), // (11,46): error CS4012: Parameters or locals of type 'RuntimeArgumentHandle' cannot be declared in async methods or async lambda expressions. // D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "h").WithArguments("System.RuntimeArgumentHandle").WithLocation(11, 46), // (12,36): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // D3 d3 = async (ArgIterator i) => { await Task.Yield(); }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "i").WithArguments("System.ArgIterator").WithLocation(12, 36)); } [Fact] public void BestType_01() { var source = @"using System; class A { } class B1 : A { } class B2 : A { } interface I { } class C1 : I { } class C2 : I { } class Program { static void F<T>(Func<bool, T> f) { } static void Main() { F((bool b) => { if (b) return new B1(); return new B2(); }); F((bool b) => { if (b) return new C1(); return new C2(); }); } }"; var expectedDiagnostics = new[] { // (13,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F((bool b) => { if (b) return new B1(); return new B2(); }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(13, 9), // (14,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F((bool b) => { if (b) return new C1(); return new C2(); }); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(14, 9) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(expectedDiagnostics); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(expectedDiagnostics); } // As above but with explicit return type. [Fact] public void BestType_02() { var source = @"using System; class A { } class B1 : A { } class B2 : A { } interface I { } class C1 : I { } class C2 : I { } class Program { static void F<T>(Func<bool, T> f) { Console.WriteLine(typeof(T)); } static void Main() { F(A (bool b) => { if (b) return new B1(); return new B2(); }); F(I (bool b) => { if (b) return new C1(); return new C2(); }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,11): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(A (bool b) => { if (b) return new B1(); return new B2(); }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "A").WithArguments("lambda return type", "10.0").WithLocation(13, 11), // (14,11): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(I (bool b) => { if (b) return new C1(); return new C2(); }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "I").WithArguments("lambda return type", "10.0").WithLocation(14, 11)); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"A I"); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void BestType_03() { var source = @"using System; class A { } class B1 : A { } class B2 : A { } class Program { static void F<T>(Func<T> x, Func<T> y) { } static void Main() { F(B2 () => null, B2 () => null); F(A () => null, B2 () => null); F(B1 () => null, B2 () => null); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,11): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(B2 () => null, B2 () => null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "B2").WithArguments("lambda return type", "10.0").WithLocation(10, 11), // (10,26): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(B2 () => null, B2 () => null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "B2").WithArguments("lambda return type", "10.0").WithLocation(10, 26), // (11,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T>, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(A () => null, B2 () => null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T>, System.Func<T>)").WithLocation(11, 9), // (11,11): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(A () => null, B2 () => null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "A").WithArguments("lambda return type", "10.0").WithLocation(11, 11), // (11,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(A () => null, B2 () => null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "B2").WithArguments("lambda return type", "10.0").WithLocation(11, 25), // (12,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T>, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(B1 () => null, B2 () => null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T>, System.Func<T>)").WithLocation(12, 9), // (12,11): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(B1 () => null, B2 () => null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "B1").WithArguments("lambda return type", "10.0").WithLocation(12, 11), // (12,26): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(B1 () => null, B2 () => null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "B2").WithArguments("lambda return type", "10.0").WithLocation(12, 26)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T>, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(A () => null, B2 () => null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T>, System.Func<T>)").WithLocation(11, 9), // (12,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T>, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(B1 () => null, B2 () => null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T>, System.Func<T>)").WithLocation(12, 9)); } [Fact] public void TypeInference_01() { var source = @"using System; class Program { static void F<T>(Func<object, T> f) { Console.WriteLine(typeof(T)); } static void Main() { F(long (o) => 1); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"System.Int64"); } [WorkItem(54257, "https://github.com/dotnet/roslyn/issues/54257")] [Fact] public void TypeInference_02() { var source = @"using System; class Program { static void F<T>(Func<T, T> f) { Console.WriteLine(typeof(T)); } static void Main() { F(int (i) => i); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } // CS4031 is not reported for async lambda in [SecurityCritical] type. [Fact] [WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")] public void SecurityCritical_AsyncLambda() { var source = @"using System; using System.Security; using System.Threading.Tasks; [SecurityCritical] class Program { static void Main() { Func<Task> f = async () => await Task.Yield(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // CS4031 is not reported for async lambda in [SecurityCritical] type. [Fact] [WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")] public void SecurityCritical_AsyncLambda_AttributeArgument() { var source = @"using System; using System.Security; using System.Threading.Tasks; class A : Attribute { internal A(int i) { } } [SecurityCritical] [A(F(async () => await Task.Yield()))] class Program { internal static int F(Func<Task> f) => 0; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(F(async () => await Task.Yield()))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F(async () => await Task.Yield())").WithLocation(9, 4)); } private static LambdaSymbol GetLambdaSymbol(SemanticModel model, LambdaExpressionSyntax syntax) { return model.GetSymbolInfo(syntax).Symbol.GetSymbol<LambdaSymbol>(); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_01() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A] (x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_02() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A][A] (x) => x; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A][A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A][A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_03() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = ([A] x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,37): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = ([A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "x").WithLocation(5, 37) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_04() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = ([A][A] x) => x; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,40): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = ([A][A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "x").WithLocation(5, 40) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_05() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int, int>> e = ([A] x, [A] y) => x + y; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,42): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int, int>> e = ([A] x, [A] y) => x + y; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "x").WithLocation(5, 42) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_06() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [return: A] (x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [return: A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[return: A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_07() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [return: A][return: A] (x) => x; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [return: A][return: A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[return: A][return: A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_08() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A][return: A] (x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A][return: A] (x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A][return: A] (x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_09() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [A] ([A] x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [A] ([A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[A] ([A] x) => x").WithLocation(5, 32) ); } [Fact] [WorkItem(53910, "https://github.com/dotnet/roslyn/issues/53910")] public void WithAttributesToExpressionTree_10() { var source = @" using System; using System.Linq.Expressions; Expression<Func<int, int>> e = [return: A] ([A] x) => x; class A : Attribute { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,32): error CS8972: A lambda expression with attributes cannot be converted to an expression tree // Expression<Func<int, int>> e = [return: A] ([A] x) => x; Diagnostic(ErrorCode.ERR_LambdaWithAttributesToExpressionTree, "[return: A] ([A] x) => x").WithLocation(5, 32) ); } } }
1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueStateMachineTests.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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class EditAndContinueStateMachineTests : EditAndContinueTestBase { [Fact] [WorkItem(1068894, "DevDiv"), WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")] public void AddIteratorMethod() { var source0 = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { } "); var source1 = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { static IEnumerable<int> G() { yield return 1; } } "); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(Parse(source1, "a.cs")); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var reader0 = md0.MetadataReader; // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<G>d__0#1"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(3, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(1, TableIndex.InterfaceImpl), Handle(2, TableIndex.InterfaceImpl), Handle(3, TableIndex.InterfaceImpl), Handle(4, TableIndex.InterfaceImpl), Handle(5, TableIndex.InterfaceImpl), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(2, TableIndex.Property), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics), Handle(1, TableIndex.MethodImpl), Handle(2, TableIndex.MethodImpl), Handle(3, TableIndex.MethodImpl), Handle(4, TableIndex.MethodImpl), Handle(5, TableIndex.MethodImpl), Handle(6, TableIndex.MethodImpl), Handle(7, TableIndex.MethodImpl), Handle(1, TableIndex.NestedClass)); diff1.VerifyPdb(Enumerable.Range(0x06000001, 0x20), @" <symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""66-9A-93-25-E7-42-DC-A9-DD-D1-61-3F-D9-45-A8-E1-39-8C-37-79"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <forwardIterator name=""&lt;G&gt;d__0#1"" /> </customDebugInfo> </method> <method token=""0x6000005""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x20"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x39""> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); } [Theory] [MemberData(nameof(ExternalPdbFormats))] public void AddAsyncMethod(DebugInformationFormat format) { var source0 = @" using System.Threading.Tasks; class C { }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await Task.FromResult(10); return 20; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format)); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<F>d__0#1"); CheckNames(readers, reader1.GetMethodDefNames(), "F", ".ctor", "MoveNext", "SetStateMachine"); CheckNames(readers, reader1.GetFieldDefNames(), "<>1__state", "<>t__builder", "<>u__1"); // Add state machine type and its members: // - Method '.ctor' // - Method 'MoveNext' // - Method 'SetStateMachine' // - Field '<>1__state' // - Field '<>t__builder' // - Field '<>u__1' // Add method F() CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); diff1.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(4) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x8c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x94"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa2""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod token=""0x6000002"" /> <await yield=""0x2e"" resume=""0x49"" token=""0x6000004"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void MethodToIteratorMethod() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return new int[] { 1, 2, 3 }; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckEncLogDefinitions(md1.Reader, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); } } } [Fact] public void MethodToAsyncMethod() { var source0 = @" using System.Threading.Tasks; class C { static Task<int> F() { return Task.FromResult(1); } }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { return await Task.FromResult(1); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckEncLogDefinitions(md1.Reader, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); } } } [Fact] public void IteratorMethodToMethod() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return new int[] { 1, 2, 3 }; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckAttributes(md1.Reader, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete IteratorStateMachineAttribute } } } [Fact] public void AsyncMethodToMethod() { var source0 = @" using System.Threading.Tasks; class C { static async Task<int> F() { return await Task.FromResult(1); } }"; var source1 = @" using System.Threading.Tasks; class C { static Task<int> F() { return Task.FromResult(1); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckAttributes(md1.Reader, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef)), // row id 0 == delete new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Delete AsyncStateMachineAttribute Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete DebuggerStepThroughAttribute } } } [Fact] public void AsyncMethodOverloads() { var source0 = @" using System.Threading.Tasks; class C { static async Task<int> F(long a) { return await Task.FromResult(1); } static async Task<int> F(int a) { return await Task.FromResult(1); } static async Task<int> F(short a) { return await Task.FromResult(1); } }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F(short a) { return await Task.FromResult(2); } static async Task<int> F(long a) { return await Task.FromResult(3); } static async Task<int> F(int a) { return await Task.FromResult(4); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var methodShort0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)"); var methodShort1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)"); var methodInt0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)"); var methodInt1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)"); var methodLong0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)"); var methodLong1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodShort0, methodShort1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, methodInt0, methodInt1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, methodLong0, methodLong1, preserveLocalVariables: true) )); using (var md1 = diff1.GetMetadata()) { // notice no TypeDefs, FieldDefs CheckEncLogDefinitions(md1.Reader, Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } } } [Fact] public void UpdateIterator_NoVariables() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 1; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { md0.MetadataReader, reader1 }; // only methods with sequence points should be listed in UpdatedMethods: CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0"); // Verify that no new TypeDefs, FieldDefs or MethodDefs were added, // 3 methods were updated: // - the kick-off method (might be changed if the method previously wasn't an iterator) // - Finally method // - MoveNext method CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 57 (0x39) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_0030 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.2 IL_0022: stfld ""int C.<F>d__0.<>2__current"" IL_0027: ldarg.0 IL_0028: ldc.i4.1 IL_0029: stfld ""int C.<F>d__0.<>1__state"" IL_002e: ldc.i4.1 IL_002f: ret IL_0030: ldarg.0 IL_0031: ldc.i4.m1 IL_0032: stfld ""int C.<F>d__0.<>1__state"" IL_0037: ldc.i4.0 IL_0038: ret }"); v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 57 (0x39) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_0030 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: stfld ""int C.<F>d__0.<>2__current"" IL_0027: ldarg.0 IL_0028: ldc.i4.1 IL_0029: stfld ""int C.<F>d__0.<>1__state"" IL_002e: ldc.i4.1 IL_002f: ret IL_0030: ldarg.0 IL_0031: ldc.i4.m1 IL_0032: stfld ""int C.<F>d__0.<>1__state"" IL_0037: ldc.i4.0 IL_0038: ret }"); } [Fact] public void UpdateAsync_NoVariables() { var source0 = WithWindowsLineBreaks(@" using System.Threading.Tasks; class C { static async Task<int> F() { await Task.FromResult(1); return 2; } }"); var source1 = WithWindowsLineBreaks(@" using System.Threading.Tasks; class C { static async Task<int> F() { await Task.FromResult(10); return 20; } }"); var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { md0.MetadataReader, reader1 }; // only methods with sequence points should be listed in UpdatedMethods: CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0"); // Verify that no new TypeDefs, FieldDefs or MethodDefs were added, // 2 methods were updated: // - the kick-off method (might be changed if the method previously wasn't async) // - MoveNext method CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 162 (0xa2) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0049 IL_000e: nop IL_000f: ldc.i4.s 10 IL_0011: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)"" IL_0016: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_001b: stloc.2 IL_001c: ldloca.s V_2 IL_001e: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0023: brtrue.s IL_0065 IL_0025: ldarg.0 IL_0026: ldc.i4.0 IL_0027: dup IL_0028: stloc.0 IL_0029: stfld ""int C.<F>d__0.<>1__state"" IL_002e: ldarg.0 IL_002f: ldloc.2 IL_0030: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0035: ldarg.0 IL_0036: stloc.3 IL_0037: ldarg.0 IL_0038: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_003d: ldloca.s V_2 IL_003f: ldloca.s V_3 IL_0041: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_0046: nop IL_0047: leave.s IL_00a1 IL_0049: ldarg.0 IL_004a: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_004f: stloc.2 IL_0050: ldarg.0 IL_0051: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0056: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_005c: ldarg.0 IL_005d: ldc.i4.m1 IL_005e: dup IL_005f: stloc.0 IL_0060: stfld ""int C.<F>d__0.<>1__state"" IL_0065: ldloca.s V_2 IL_0067: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_006c: pop IL_006d: ldc.i4.s 20 IL_006f: stloc.1 IL_0070: leave.s IL_008c } catch System.Exception { IL_0072: stloc.s V_4 IL_0074: ldarg.0 IL_0075: ldc.i4.s -2 IL_0077: stfld ""int C.<F>d__0.<>1__state"" IL_007c: ldarg.0 IL_007d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0082: ldloc.s V_4 IL_0084: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_0089: nop IL_008a: leave.s IL_00a1 } IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int C.<F>d__0.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_009a: ldloc.1 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00a0: nop IL_00a1: ret }"); v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 160 (0xa0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0048 -IL_000e: nop -IL_000f: ldc.i4.1 IL_0010: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)"" IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_001a: stloc.2 ~IL_001b: ldloca.s V_2 IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0022: brtrue.s IL_0064 IL_0024: ldarg.0 IL_0025: ldc.i4.0 IL_0026: dup IL_0027: stloc.0 IL_0028: stfld ""int C.<F>d__0.<>1__state"" <IL_002d: ldarg.0 IL_002e: ldloc.2 IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0034: ldarg.0 IL_0035: stloc.3 IL_0036: ldarg.0 IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_003c: ldloca.s V_2 IL_003e: ldloca.s V_3 IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_0045: nop IL_0046: leave.s IL_009f >IL_0048: ldarg.0 IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_004e: stloc.2 IL_004f: ldarg.0 IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_005b: ldarg.0 IL_005c: ldc.i4.m1 IL_005d: dup IL_005e: stloc.0 IL_005f: stfld ""int C.<F>d__0.<>1__state"" IL_0064: ldloca.s V_2 IL_0066: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_006b: pop -IL_006c: ldc.i4.2 IL_006d: stloc.1 IL_006e: leave.s IL_008a } catch System.Exception { ~IL_0070: stloc.s V_4 IL_0072: ldarg.0 IL_0073: ldc.i4.s -2 IL_0075: stfld ""int C.<F>d__0.<>1__state"" IL_007a: ldarg.0 IL_007b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0080: ldloc.s V_4 IL_0082: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_0087: nop IL_0088: leave.s IL_009f } -IL_008a: ldarg.0 IL_008b: ldc.i4.s -2 IL_008d: stfld ""int C.<F>d__0.<>1__state"" ~IL_0092: ldarg.0 IL_0093: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0098: ldloc.1 IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_009e: nop IL_009f: ret }", sequencePoints: "C+<F>d__0.MoveNext"); v0.VerifyPdb("C+<F>d__0.MoveNext", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;F&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""20"" offset=""0"" /> <slot kind=""33"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""34"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x6c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> <entry offset=""0x70"" hidden=""true"" document=""1"" /> <entry offset=""0x8a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x92"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa0""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""F"" /> <await yield=""0x2d"" resume=""0x48"" declaringType=""C+&lt;F&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void UpdateIterator_UserDefinedVariables_NoChange() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return 1; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return 2; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // Verify that no new TypeDefs, FieldDefs or MethodDefs were added, // 3 methods were updated: // - the kick-off method (might be changed if the method previously wasn't an iterator) // - Finally method // - MoveNext method CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 69 (0x45) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""int C.<F>d__0.p"" IL_0027: stfld ""int C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.2 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldc.i4.0 IL_0044: ret }"); } } } [Fact] public void UpdateIterator_UserDefinedVariables_AddVariable() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return x; } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int y = 1234; int x = p; yield return y; Console.WriteLine(x); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(7, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 97 (0x61) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_004c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4 0x4d2 IL_0026: stfld ""int C.<F>d__0.<y>5__2"" IL_002b: ldarg.0 IL_002c: ldarg.0 IL_002d: ldfld ""int C.<F>d__0.p"" IL_0032: stfld ""int C.<F>d__0.<x>5__1"" IL_0037: ldarg.0 IL_0038: ldarg.0 IL_0039: ldfld ""int C.<F>d__0.<y>5__2"" IL_003e: stfld ""int C.<F>d__0.<>2__current"" IL_0043: ldarg.0 IL_0044: ldc.i4.1 IL_0045: stfld ""int C.<F>d__0.<>1__state"" IL_004a: ldc.i4.1 IL_004b: ret IL_004c: ldarg.0 IL_004d: ldc.i4.m1 IL_004e: stfld ""int C.<F>d__0.<>1__state"" IL_0053: ldarg.0 IL_0054: ldfld ""int C.<F>d__0.<x>5__1"" IL_0059: call ""void System.Console.WriteLine(int)"" IL_005e: nop IL_005f: ldc.i4.0 IL_0060: ret }"); } } } [Fact] public void UpdateIterator_UserDefinedVariables_AddAndRemoveVariable() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return x; } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int y = 1234; yield return y; Console.WriteLine(p); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(7, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 85 (0x55) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_0040 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4 0x4d2 IL_0026: stfld ""int C.<F>d__0.<y>5__2"" IL_002b: ldarg.0 IL_002c: ldarg.0 IL_002d: ldfld ""int C.<F>d__0.<y>5__2"" IL_0032: stfld ""int C.<F>d__0.<>2__current"" IL_0037: ldarg.0 IL_0038: ldc.i4.1 IL_0039: stfld ""int C.<F>d__0.<>1__state"" IL_003e: ldc.i4.1 IL_003f: ret IL_0040: ldarg.0 IL_0041: ldc.i4.m1 IL_0042: stfld ""int C.<F>d__0.<>1__state"" IL_0047: ldarg.0 IL_0048: ldfld ""int C.<F>d__0.p"" IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ldc.i4.0 IL_0054: ret }"); } } } [Fact] public void UpdateIterator_UserDefinedVariables_ChangeVariableType() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { var x = 1; yield return 1; Console.WriteLine(x); } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { var x = 1.0; yield return 2; Console.WriteLine(x); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(5, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 84 (0x54) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003f IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.r8 1 IL_002a: stfld ""double C.<F>d__0.<x>5__2"" IL_002f: ldarg.0 IL_0030: ldc.i4.2 IL_0031: stfld ""int C.<F>d__0.<>2__current"" IL_0036: ldarg.0 IL_0037: ldc.i4.1 IL_0038: stfld ""int C.<F>d__0.<>1__state"" IL_003d: ldc.i4.1 IL_003e: ret IL_003f: ldarg.0 IL_0040: ldc.i4.m1 IL_0041: stfld ""int C.<F>d__0.<>1__state"" IL_0046: ldarg.0 IL_0047: ldfld ""double C.<F>d__0.<x>5__2"" IL_004c: call ""void System.Console.WriteLine(double)"" IL_0051: nop IL_0052: ldc.i4.0 IL_0053: ret }"); } } } [Fact] public void UpdateIterator_SynthesizedVariables_ChangeVariableType() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { foreach (object item in new[] { 1 }) { yield return 1; } } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { foreach (object item in new[] { 1.0 }) { yield return 1; } } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>2__current: int", "<>l__initialThreadId: int", "<>s__1: int[]", "<>s__2: int", "<item>5__3: object" }, module.GetFieldNamesAndTypes("C.<F>d__0")); }); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForEachStatement), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(7, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 161 (0xa1) .maxstack 5 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_006b IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: nop IL_0021: ldarg.0 IL_0022: ldc.i4.1 IL_0023: newarr ""double"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.r8 1 IL_0033: stelem.r8 IL_0034: stfld ""double[] C.<F>d__0.<>s__4"" IL_0039: ldarg.0 IL_003a: ldc.i4.0 IL_003b: stfld ""int C.<F>d__0.<>s__2"" IL_0040: br.s IL_0088 IL_0042: ldarg.0 IL_0043: ldarg.0 IL_0044: ldfld ""double[] C.<F>d__0.<>s__4"" IL_0049: ldarg.0 IL_004a: ldfld ""int C.<F>d__0.<>s__2"" IL_004f: ldelem.r8 IL_0050: box ""double"" IL_0055: stfld ""object C.<F>d__0.<item>5__3"" IL_005a: nop IL_005b: ldarg.0 IL_005c: ldc.i4.1 IL_005d: stfld ""int C.<F>d__0.<>2__current"" IL_0062: ldarg.0 IL_0063: ldc.i4.1 IL_0064: stfld ""int C.<F>d__0.<>1__state"" IL_0069: ldc.i4.1 IL_006a: ret IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: stfld ""int C.<F>d__0.<>1__state"" IL_0072: nop IL_0073: ldarg.0 IL_0074: ldnull IL_0075: stfld ""object C.<F>d__0.<item>5__3"" IL_007a: ldarg.0 IL_007b: ldarg.0 IL_007c: ldfld ""int C.<F>d__0.<>s__2"" IL_0081: ldc.i4.1 IL_0082: add IL_0083: stfld ""int C.<F>d__0.<>s__2"" IL_0088: ldarg.0 IL_0089: ldfld ""int C.<F>d__0.<>s__2"" IL_008e: ldarg.0 IL_008f: ldfld ""double[] C.<F>d__0.<>s__4"" IL_0094: ldlen IL_0095: conv.i4 IL_0096: blt.s IL_0042 IL_0098: ldarg.0 IL_0099: ldnull IL_009a: stfld ""double[] C.<F>d__0.<>s__4"" IL_009f: ldc.i4.0 IL_00a0: ret }"); } } } [Fact] public void HoistedVariables_MultipleGenerations() { var source0 = @" using System.Threading.Tasks; class C { static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2 { bool a1 = true; int a2 = 3; await Task.Delay(0); return 1; } static async Task<int> G() // testing G1 -> G3 { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } static async Task<int> H() // testing G0 -> G3 { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F() // updated { C a1 = new C(); int a2 = 3; await Task.Delay(0); return 1; } static async Task<int> G() // updated { C c = new C(); bool a1 = true; await Task.Delay(0); return 2; } static async Task<int> H() { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } }"; var source2 = @" using System.Threading.Tasks; class C { static async Task<int> F() // updated { bool a1 = true; C a2 = new C(); await Task.Delay(0); return 1; } static async Task<int> G() { C c = new C(); bool a1 = true; await Task.Delay(0); return 2; } static async Task<int> H() { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } }"; var source3 = @" using System.Threading.Tasks; class C { static async Task<int> F() { bool a1 = true; C a2 = new C(); await Task.Delay(0); return 1; } static async Task<int> G() // updated { C c = new C(); C a1 = new C(); await Task.Delay(0); return 1; } static async Task<int> H() // updated { C c = new C(); C a1 = new C(); await Task.Delay(0); return 1; } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var h0 = compilation0.GetMember<MethodSymbol>("C.H"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); var h2 = compilation2.GetMember<MethodSymbol>("C.H"); var h3 = compilation3.GetMember<MethodSymbol>("C.H"); var v0 = CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<a1>5__1: bool", "<a2>5__2: int", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter" }, module.GetFieldNamesAndTypes("C.<F>d__0")); }); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__0, <G>d__1}", "C.<F>d__0: {<>1__state, <>t__builder, <a1>5__3, <a2>5__2, <>u__1, MoveNext, SetStateMachine}", "C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0, <G>d__1}", "C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}", "C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetEquivalentNodesMap(h3, h2), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<G>d__1, <H>d__2, <F>d__0}", "C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}", "C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine, <a1>5__2}", "C.<H>d__2: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine}"); // Verify delta metadata contains expected rows. var md1 = diff1.GetMetadata(); var md2 = diff2.GetMetadata(); var md3 = diff3.GetMetadata(); // 1 field def added & 4 methods updated (MoveNext and kickoff for F and G) CheckEncLogDefinitions(md1.Reader, Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(16, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 192 (0xc0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter V_2, C.<F>d__0 V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_005a IL_000e: nop IL_000f: ldarg.0 IL_0010: newobj ""C..ctor()"" IL_0015: stfld ""C C.<F>d__0.<a1>5__3"" IL_001a: ldarg.0 IL_001b: ldc.i4.3 IL_001c: stfld ""int C.<F>d__0.<a2>5__2"" IL_0021: ldc.i4.0 IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)"" IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_002c: stloc.2 IL_002d: ldloca.s V_2 IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0034: brtrue.s IL_0076 IL_0036: ldarg.0 IL_0037: ldc.i4.0 IL_0038: dup IL_0039: stloc.0 IL_003a: stfld ""int C.<F>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldloc.2 IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0046: ldarg.0 IL_0047: stloc.3 IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldloca.s V_3 IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)"" IL_0057: nop IL_0058: leave.s IL_00bf IL_005a: ldarg.0 IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0060: stloc.2 IL_0061: ldarg.0 IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_006d: ldarg.0 IL_006e: ldc.i4.m1 IL_006f: dup IL_0070: stloc.0 IL_0071: stfld ""int C.<F>d__0.<>1__state"" IL_0076: ldloca.s V_2 IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_007d: nop IL_007e: ldc.i4.1 IL_007f: stloc.1 IL_0080: leave.s IL_00a3 } catch System.Exception { IL_0082: stloc.s V_4 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int C.<F>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldnull IL_008e: stfld ""C C.<F>d__0.<a1>5__3"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0099: ldloc.s V_4 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00a0: nop IL_00a1: leave.s IL_00bf } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int C.<F>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldnull IL_00ad: stfld ""C C.<F>d__0.<a1>5__3"" IL_00b2: ldarg.0 IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00b8: ldloc.1 IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00be: nop IL_00bf: ret }"); // 2 field defs added (both variables a1 and a2 of F changed their types) & 2 methods updated CheckEncLogDefinitions(md2.Reader, Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(17, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(18, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff2.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 192 (0xc0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter V_2, C.<F>d__0 V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_005a IL_000e: nop IL_000f: ldarg.0 IL_0010: ldc.i4.1 IL_0011: stfld ""bool C.<F>d__0.<a1>5__4"" IL_0016: ldarg.0 IL_0017: newobj ""C..ctor()"" IL_001c: stfld ""C C.<F>d__0.<a2>5__5"" IL_0021: ldc.i4.0 IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)"" IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_002c: stloc.2 IL_002d: ldloca.s V_2 IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0034: brtrue.s IL_0076 IL_0036: ldarg.0 IL_0037: ldc.i4.0 IL_0038: dup IL_0039: stloc.0 IL_003a: stfld ""int C.<F>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldloc.2 IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0046: ldarg.0 IL_0047: stloc.3 IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldloca.s V_3 IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)"" IL_0057: nop IL_0058: leave.s IL_00bf IL_005a: ldarg.0 IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0060: stloc.2 IL_0061: ldarg.0 IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_006d: ldarg.0 IL_006e: ldc.i4.m1 IL_006f: dup IL_0070: stloc.0 IL_0071: stfld ""int C.<F>d__0.<>1__state"" IL_0076: ldloca.s V_2 IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_007d: nop IL_007e: ldc.i4.1 IL_007f: stloc.1 IL_0080: leave.s IL_00a3 } catch System.Exception { IL_0082: stloc.s V_4 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int C.<F>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldnull IL_008e: stfld ""C C.<F>d__0.<a2>5__5"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0099: ldloc.s V_4 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00a0: nop IL_00a1: leave.s IL_00bf } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int C.<F>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldnull IL_00ad: stfld ""C C.<F>d__0.<a2>5__5"" IL_00b2: ldarg.0 IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00b8: ldloc.1 IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00be: nop IL_00bf: ret }"); // 2 field defs added - variables of G and H changed their types; 4 methods updated: G, H kickoff and MoveNext CheckEncLogDefinitions(md3.Reader, Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(19, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(20, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void HoistedVariables_Dynamic1() { var template = @" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { dynamic <N:0>x = 1</N:0>; yield return 1; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 147 (0x93) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: box ""int"" IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.1 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0048: brfalse.s IL_004c IL_004a: br.s IL_0071 IL_004c: ldc.i4.s 16 IL_004e: ldtoken ""int"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0080: ldarg.0 IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1"" IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_008b: call ""void System.Console.WriteLine(int)"" IL_0090: nop IL_0091: ldc.i4.0 IL_0092: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var baselineIL = @" { // Code size 149 (0x95) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: box ""int"" IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.1 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0048: brfalse.s IL_004c IL_004a: br.s IL_0071 IL_004c: ldc.i4.s 16 IL_004e: ldtoken ""int"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0080: ldarg.0 IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1"" IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_008b: ldc.i4.<<VALUE>> IL_008c: add IL_008d: call ""void System.Console.WriteLine(int)"" IL_0092: nop IL_0093: ldc.i4.0 IL_0094: ret }"; diff1.VerifySynthesizedMembers( "C: {<>o__0#1, <F>d__0}", "C.<>o__0#1: {<>p__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <F>d__0, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#2")); } [Fact] public void HoistedVariables_Dynamic2() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { private static IEnumerable<string> F() { dynamic <N:0>d = ""x""</N:0>; yield return d; Console.WriteLine(0); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { private static IEnumerable<string> F() { dynamic <N:0>d = ""x""</N:0>; yield return d.ToString(); Console.WriteLine(1); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class C { private static IEnumerable<string> F() { dynamic <N:0>d = ""x""</N:0>; yield return d; Console.WriteLine(2); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1, <F>d__0}", "C.<>o__0#1: {<>p__0, <>p__1}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <F>d__0, <>o__0#1}", "C.<>o__0#1: {<>p__0, <>p__1}", "C.<>o__0#2: {<>p__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}"); } [Fact] public void Awaiters1() { var source0 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; static async Task<int> F() { await A1(); await A2(); return 1; } static async Task<int> G() { await A2(); await A1(); return 1; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>" }, module.GetFieldNamesAndTypes("C.<F>d__3")); Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<int>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<bool>" }, module.GetFieldNamesAndTypes("C.<G>d__4")); }); } [Theory] [MemberData(nameof(ExternalPdbFormats))] public void Awaiters_MultipleGenerations(DebugInformationFormat format) { var source0 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2 { await A1(); await A2(); return 1; } static async Task<int> G() // testing G1 -> G3 { await A1(); return 1; } static async Task<int> H() // testing G0 -> G3 { await A1(); return 1; } }"; var source1 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() // updated { await A3(); await A2(); return 1; } static async Task<int> G() // updated { await A1(); return 2; } static async Task<int> H() { await A1(); return 1; } }"; var source2 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() // updated { await A1(); await A3(); return 1; } static async Task<int> G() { await A1(); return 2; } static async Task<int> H() { await A1(); return 1; } }"; var source3 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() { await A1(); await A3(); return 1; } static async Task<int> G() // updated { await A3(); return 1; } static async Task<int> H() // updated { await A3(); return 1; } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var h0 = compilation0.GetMember<MethodSymbol>("C.H"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); var h2 = compilation2.GetMember<MethodSymbol>("C.H"); var h3 = compilation3.GetMember<MethodSymbol>("C.H"); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format), symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>" }, module.GetFieldNamesAndTypes("C.<F>d__3")); }); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapByKind(f0, SyntaxKind.Block), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapByKind(g0, SyntaxKind.Block), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__3, <G>d__4}", "C.<F>d__3: {<>1__state, <>t__builder, <>u__3, <>u__2, MoveNext, SetStateMachine}", "C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__3, <G>d__4}", "C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}", "C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetSyntaxMapByKind(g2, SyntaxKind.Block), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetSyntaxMapByKind(h2, SyntaxKind.Block), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<G>d__4, <H>d__5, <F>d__3}", "C.<G>d__4: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine, <>u__1}", "C.<H>d__5: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine}", "C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}"); // Verify delta metadata contains expected rows. var md1 = diff1.GetMetadata(); var md2 = diff2.GetMetadata(); var md3 = diff3.GetMetadata(); diff1.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(9) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000009""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x79"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""20"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0xdc"" hidden=""true"" document=""1"" /> <entry offset=""0xf6"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0xfe"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10c""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod token=""0x6000004"" /> <await yield=""0x37"" resume=""0x55"" token=""0x6000009"" /> <await yield=""0x97"" resume=""0xb3"" token=""0x6000009"" /> </asyncInfo> </method> </methods> </symbols>"); // 1 field def added & 4 methods updated (MoveNext and kickoff for F and G) CheckEncLogDefinitions(md1.Reader, Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(11, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Note that the new awaiter is allocated slot <>u__3 since <>u__1 and <>u__2 are taken. diff1.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 268 (0x10c) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<C> V_2, C.<F>d__3 V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__3.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_0055 IL_0014: br IL_00b3 IL_0019: nop IL_001a: call ""System.Threading.Tasks.Task<C> C.A3()"" IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()"" IL_0024: stloc.2 IL_0025: ldloca.s V_2 IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get"" IL_002c: brtrue.s IL_0071 IL_002e: ldarg.0 IL_002f: ldc.i4.0 IL_0030: dup IL_0031: stloc.0 IL_0032: stfld ""int C.<F>d__3.<>1__state"" IL_0037: ldarg.0 IL_0038: ldloc.2 IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_003e: ldarg.0 IL_003f: stloc.3 IL_0040: ldarg.0 IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0046: ldloca.s V_2 IL_0048: ldloca.s V_3 IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)"" IL_004f: nop IL_0050: leave IL_010b IL_0055: ldarg.0 IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_005b: stloc.2 IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>"" IL_0068: ldarg.0 IL_0069: ldc.i4.m1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld ""int C.<F>d__3.<>1__state"" IL_0071: ldloca.s V_2 IL_0073: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()"" IL_0078: pop IL_0079: call ""System.Threading.Tasks.Task<int> C.A2()"" IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0083: stloc.s V_4 IL_0085: ldloca.s V_4 IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_008c: brtrue.s IL_00d0 IL_008e: ldarg.0 IL_008f: ldc.i4.1 IL_0090: dup IL_0091: stloc.0 IL_0092: stfld ""int C.<F>d__3.<>1__state"" IL_0097: ldarg.0 IL_0098: ldloc.s V_4 IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2"" IL_009f: ldarg.0 IL_00a0: stloc.3 IL_00a1: ldarg.0 IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00a7: ldloca.s V_4 IL_00a9: ldloca.s V_3 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__3)"" IL_00b0: nop IL_00b1: leave.s IL_010b IL_00b3: ldarg.0 IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2"" IL_00b9: stloc.s V_4 IL_00bb: ldarg.0 IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2"" IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00c7: ldarg.0 IL_00c8: ldc.i4.m1 IL_00c9: dup IL_00ca: stloc.0 IL_00cb: stfld ""int C.<F>d__3.<>1__state"" IL_00d0: ldloca.s V_4 IL_00d2: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00d7: pop IL_00d8: ldc.i4.1 IL_00d9: stloc.1 IL_00da: leave.s IL_00f6 } catch System.Exception { IL_00dc: stloc.s V_5 IL_00de: ldarg.0 IL_00df: ldc.i4.s -2 IL_00e1: stfld ""int C.<F>d__3.<>1__state"" IL_00e6: ldarg.0 IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00ec: ldloc.s V_5 IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00f3: nop IL_00f4: leave.s IL_010b } IL_00f6: ldarg.0 IL_00f7: ldc.i4.s -2 IL_00f9: stfld ""int C.<F>d__3.<>1__state"" IL_00fe: ldarg.0 IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0104: ldloc.1 IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_010a: nop IL_010b: ret }"); // 1 field def added & 2 methods updated CheckEncLogDefinitions(md2.Reader, Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(12, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff2.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(9) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000009""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x79"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""20"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0xdc"" hidden=""true"" document=""1"" /> <entry offset=""0xf6"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0xfe"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10c""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod token=""0x6000004"" /> <await yield=""0x37"" resume=""0x55"" token=""0x6000009"" /> <await yield=""0x97"" resume=""0xb3"" token=""0x6000009"" /> </asyncInfo> </method> </methods> </symbols>"); // Note that the new awaiters are allocated slots <>u__4, <>u__5. diff2.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 268 (0x10c) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<bool> V_2, C.<F>d__3 V_3, System.Runtime.CompilerServices.TaskAwaiter<C> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__3.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_0055 IL_0014: br IL_00b3 IL_0019: nop IL_001a: call ""System.Threading.Tasks.Task<bool> C.A1()"" IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_0024: stloc.2 IL_0025: ldloca.s V_2 IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_002c: brtrue.s IL_0071 IL_002e: ldarg.0 IL_002f: ldc.i4.0 IL_0030: dup IL_0031: stloc.0 IL_0032: stfld ""int C.<F>d__3.<>1__state"" IL_0037: ldarg.0 IL_0038: ldloc.2 IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4"" IL_003e: ldarg.0 IL_003f: stloc.3 IL_0040: ldarg.0 IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0046: ldloca.s V_2 IL_0048: ldloca.s V_3 IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<F>d__3)"" IL_004f: nop IL_0050: leave IL_010b IL_0055: ldarg.0 IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4"" IL_005b: stloc.2 IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4"" IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_0068: ldarg.0 IL_0069: ldc.i4.m1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld ""int C.<F>d__3.<>1__state"" IL_0071: ldloca.s V_2 IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_0078: pop IL_0079: call ""System.Threading.Tasks.Task<C> C.A3()"" IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()"" IL_0083: stloc.s V_4 IL_0085: ldloca.s V_4 IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get"" IL_008c: brtrue.s IL_00d0 IL_008e: ldarg.0 IL_008f: ldc.i4.1 IL_0090: dup IL_0091: stloc.0 IL_0092: stfld ""int C.<F>d__3.<>1__state"" IL_0097: ldarg.0 IL_0098: ldloc.s V_4 IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_009f: ldarg.0 IL_00a0: stloc.3 IL_00a1: ldarg.0 IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00a7: ldloca.s V_4 IL_00a9: ldloca.s V_3 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)"" IL_00b0: nop IL_00b1: leave.s IL_010b IL_00b3: ldarg.0 IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_00b9: stloc.s V_4 IL_00bb: ldarg.0 IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>"" IL_00c7: ldarg.0 IL_00c8: ldc.i4.m1 IL_00c9: dup IL_00ca: stloc.0 IL_00cb: stfld ""int C.<F>d__3.<>1__state"" IL_00d0: ldloca.s V_4 IL_00d2: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()"" IL_00d7: pop IL_00d8: ldc.i4.1 IL_00d9: stloc.1 IL_00da: leave.s IL_00f6 } catch System.Exception { IL_00dc: stloc.s V_5 IL_00de: ldarg.0 IL_00df: ldc.i4.s -2 IL_00e1: stfld ""int C.<F>d__3.<>1__state"" IL_00e6: ldarg.0 IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00ec: ldloc.s V_5 IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00f3: nop IL_00f4: leave.s IL_010b } IL_00f6: ldarg.0 IL_00f7: ldc.i4.s -2 IL_00f9: stfld ""int C.<F>d__3.<>1__state"" IL_00fe: ldarg.0 IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0104: ldloc.1 IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_010a: nop IL_010b: ret }"); // 2 field defs added - G and H awaiters & 4 methods updated: G, H kickoff and MoveNext CheckEncLogDefinitions(md3.Reader, Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(13, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(14, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff3.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(15) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x600000f""> <customDebugInfo> <forward token=""0x600000c"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""24"" startColumn=""5"" endLine=""24"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""20"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""18"" document=""1"" /> <entry offset=""0x6f"" hidden=""true"" document=""1"" /> <entry offset=""0x89"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" /> <entry offset=""0x91"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <kickoffMethod token=""0x6000006"" /> <await yield=""0x2c"" resume=""0x47"" token=""0x600000f"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void SynthesizedMembersMerging() { var source0 = @" using System.Collections.Generic; public class C { }"; var source1 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 2; } }"; var source2 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 3; } }"; var source3 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 3; } public static void G() { System.Console.WriteLine(1); } }"; var source4 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 3; } public static void G() { System.Console.WriteLine(1); } public static IEnumerable<int> H() { yield return 1; } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var h4 = compilation4.GetMember<MethodSymbol>("C.H"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); diff1.VerifySynthesizedMembers( "C: {<F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g3))); diff3.VerifySynthesizedMembers( "C: {<F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, h4))); diff4.VerifySynthesizedMembers( "C: {<H>d__2#4, <F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "C.<H>d__2#4: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); } [Fact] public void UniqueSynthesizedNames() { var source0 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; } }"; var source1 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F(int a) { yield return 2; } public static IEnumerable<int> F() { yield return 1; } }"; var source2 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F(int a) { yield return 2; } public static IEnumerable<int> F(byte a) { yield return 3; } public static IEnumerable<int> F() { yield return 1; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<F>d__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<F>d__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<F>d__1#2"); } [Fact] public void UpdateAsyncLambda() { var source0 = MarkedSource( @"using System; using System.Threading.Tasks; class C { static void F() { Func<Task> <N:0>g1 = <N:1>async () => { await A1(); await A2(); }</N:1></N:0>; } static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; }"); var source1 = MarkedSource( @"using System; using System.Threading.Tasks; class C { static int G() => 1; static void F() { Func<Task> <N:0>g1 = <N:1>async () => { await A2(); await A1(); }</N:1></N:0>; } static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; }"); var source2 = MarkedSource( @"using System; using System.Threading.Tasks; class C { static int G() => 1; static void F() { Func<Task> <N:0>g1 = <N:1>async () => { await A1(); await A2(); }</N:1></N:0>; } static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; }"); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "<>4__this: C.<>c", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>" }, module.GetFieldNamesAndTypes("C.<>c.<<F>b__0_0>d")); }); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation: diff1.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d", "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "<>4__this: C.<>c", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); // note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation: diff2.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d", "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "<>4__this: C.<>c", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"); } [Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")] public void HoistedAnonymousTypes1() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = 1 }</N:0>; yield return 1; Console.WriteLine(x.A + 1); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = 1 }</N:0>; yield return 1; Console.WriteLine(x.A + 2); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = 1 }</N:0>; yield return 1; Console.WriteLine(x.A + 3); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL = @" { // Code size 88 (0x58) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0027: stfld ""<anonymous type: int A> C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.1 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldarg.0 IL_0044: ldfld ""<anonymous type: int A> C.<F>d__0.<x>5__1"" IL_0049: callvirt ""int <>f__AnonymousType0<int>.A.get"" IL_004e: ldc.i4.<<VALUE>> IL_004f: add IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: nop IL_0056: ldc.i4.0 IL_0057: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0"); diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<F>d__0"); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3")); } [Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")] public void HoistedAnonymousTypes_Nested() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>; yield return 1; Console.WriteLine(x[0].A.B + 1); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>; yield return 1; Console.WriteLine(x[0].A.B + 2); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>; yield return 1; Console.WriteLine(x[0].A.B + 3); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL = @" { // Code size 109 (0x6d) .maxstack 5 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_004a IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: newarr ""<>f__AnonymousType0<<anonymous type: int B>>"" IL_0027: dup IL_0028: ldc.i4.0 IL_0029: ldc.i4.1 IL_002a: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_002f: newobj ""<>f__AnonymousType0<<anonymous type: int B>>..ctor(<anonymous type: int B>)"" IL_0034: stelem.ref IL_0035: stfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1"" IL_003a: ldarg.0 IL_003b: ldc.i4.1 IL_003c: stfld ""int C.<F>d__0.<>2__current"" IL_0041: ldarg.0 IL_0042: ldc.i4.1 IL_0043: stfld ""int C.<F>d__0.<>1__state"" IL_0048: ldc.i4.1 IL_0049: ret IL_004a: ldarg.0 IL_004b: ldc.i4.m1 IL_004c: stfld ""int C.<F>d__0.<>1__state"" IL_0051: ldarg.0 IL_0052: ldfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1"" IL_0057: ldc.i4.0 IL_0058: ldelem.ref IL_0059: callvirt ""<anonymous type: int B> <>f__AnonymousType0<<anonymous type: int B>>.A.get"" IL_005e: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_0063: ldc.i4.<<VALUE>> IL_0064: add IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: ldc.i4.0 IL_006c: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3")); } [Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")] public void HoistedGenericTypes() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class Z<T1> { public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); } } class C { public IEnumerable<int> F() { var <N:0>x = new Z<double>.S<int>()</N:0>; yield return 1; Console.WriteLine(x.a + x.b + 1); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class Z<T1> { public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); } } class C { public IEnumerable<int> F() { var <N:0>x = new Z<double>.S<int>()</N:0>; yield return 1; Console.WriteLine(x.a + x.b + 2); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class Z<T1> { public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); } } class C { public IEnumerable<int> F() { var <N:0>x = new Z<double>.S<int>()</N:0>; yield return 1; Console.WriteLine(x.a + x.b + 3); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL = @" { // Code size 108 (0x6c) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003b IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: newobj ""Z<double>.S<int>..ctor()"" IL_0026: stfld ""Z<double>.S<int> C.<F>d__0.<x>5__1"" IL_002b: ldarg.0 IL_002c: ldc.i4.1 IL_002d: stfld ""int C.<F>d__0.<>2__current"" IL_0032: ldarg.0 IL_0033: ldc.i4.1 IL_0034: stfld ""int C.<F>d__0.<>1__state"" IL_0039: ldc.i4.1 IL_003a: ret IL_003b: ldarg.0 IL_003c: ldc.i4.m1 IL_003d: stfld ""int C.<F>d__0.<>1__state"" IL_0042: ldarg.0 IL_0043: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1"" IL_0048: ldfld ""double Z<double>.S<int>.a"" IL_004d: ldarg.0 IL_004e: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1"" IL_0053: ldfld ""int Z<double>.S<int>.b"" IL_0058: conv.r8 IL_0059: add IL_005a: ldc.r8 <<VALUE>> IL_0063: add IL_0064: call ""void System.Console.WriteLine(double)"" IL_0069: nop IL_006a: ldc.i4.0 IL_006b: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3")); } [Fact] public void HoistedAnonymousTypes_Dynamic() { var template = @" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; yield return 1; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 87 (0x57) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003d IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldnull IL_0022: ldc.i4.1 IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_002d: ldarg.0 IL_002e: ldc.i4.1 IL_002f: stfld ""int C.<F>d__0.<>2__current"" IL_0034: ldarg.0 IL_0035: ldc.i4.1 IL_0036: stfld ""int C.<F>d__0.<>1__state"" IL_003b: ldc.i4.1 IL_003c: ret IL_003d: ldarg.0 IL_003e: ldc.i4.m1 IL_003f: stfld ""int C.<F>d__0.<>1__state"" IL_0044: ldarg.0 IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_004f: call ""void System.Console.WriteLine(int)"" IL_0054: nop IL_0055: ldc.i4.0 IL_0056: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var baselineIL = @" { // Code size 89 (0x59) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003d IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldnull IL_0022: ldc.i4.1 IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_002d: ldarg.0 IL_002e: ldc.i4.1 IL_002f: stfld ""int C.<F>d__0.<>2__current"" IL_0034: ldarg.0 IL_0035: ldc.i4.1 IL_0036: stfld ""int C.<F>d__0.<>1__state"" IL_003b: ldc.i4.1 IL_003c: ret IL_003d: ldarg.0 IL_003e: ldc.i4.m1 IL_003f: stfld ""int C.<F>d__0.<>1__state"" IL_0044: ldarg.0 IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_004f: ldc.i4.<<VALUE>> IL_0050: add IL_0051: call ""void System.Console.WriteLine(int)"" IL_0056: nop IL_0057: ldc.i4.0 IL_0058: ret }"; diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); } [Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")] public void HoistedAnonymousTypes_Delete() { var source0 = MarkedSource(@" using System.Linq; using System.Threading.Tasks; class C { static async Task<int> F() { var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>; return <N:2>await Task.FromResult(1)</N:2>; } } "); var source1 = MarkedSource(@" using System.Linq; using System.Threading.Tasks; class C { static async Task<int> F() { var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>; var y = x.First(); return <N:2>await Task.FromResult(1)</N:2>; } } "); var source2 = source0; var source3 = source1; var source4 = source0; var source5 = source1; var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var compilation3 = compilation0.WithSource(source3.Tree); var compilation4 = compilation0.WithSource(source4.Tree); var compilation5 = compilation0.WithSource(source5.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var f4 = compilation4.GetMember<MethodSymbol>("C.F"); var f5 = compilation5.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // y is added var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__3, <>s__2, <>u__1, MoveNext, SetStateMachine}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is removed var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); // Synthesized members collection still includes y field since members are only added to it and never deleted. // The corresponding CLR field is also present. diff2.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is added and a new slot index is allocated for it var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__4, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is removed var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f3, f4, GetSyntaxMapFromMarkers(source3, source4), preserveLocalVariables: true))); diff4.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is added var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f4, f5, GetSyntaxMapFromMarkers(source4, source5), preserveLocalVariables: true))); diff5.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__5, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); } [Fact] public void HoistedAnonymousTypes_Dynamic2() { var source0 = MarkedSource(@" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { args = Iterator().ToArray(); } private static IEnumerable<string> Iterator() { string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>; var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>; for (int <N:18>i = 0</N:18>; i < 10; i++) { var <N:6>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4> <N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>; var <N:8>linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, <N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>; while (linked != null) { <N:9>yield return linked.Head</N:9>; linked = linked.Tail; } var <N:14>newArgs = from a in result <N:10>let value = a.Value</N:10> <N:11>let length = a.Length</N:11> <N:12>where value.Length == length</N:12> <N:13>select value + value</N:13></N:14>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var source1 = MarkedSource(@" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { args = Iterator().ToArray(); } private static IEnumerable<string> Iterator() { string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>; var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>; for (int <N:18>i = 0</N:18>; i < 10; i++) { var <N:6>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4> <N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>; var <N:8>linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, <N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>; var <N:17>temp = list</N:17>; while (temp != null) { <N:9>yield return temp.Head</N:9>; temp = temp.Tail; } var <N:14>newArgs = from a in result <N:10>let value = a.Value</N:10> <N:11>let length = a.Length</N:11> <N:12>where value.Length == length</N:12> <N:13>select value + value</N:13></N:14>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var source2 = MarkedSource(@" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { args = Iterator().ToArray(); } private static IEnumerable<string> Iterator() { string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>; var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>; for (int <N:18>i = 0</N:18>; i < 10; i++) { var <N:6>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4> <N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>; var <N:8>linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, <N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>; var <N:17>temp = list</N:17>; while (temp != null) { <N:9>yield return temp.Head.ToString()</N:9>; temp = temp.Tail; } var <N:14>newArgs = from a in result <N:10>let value = a.Value</N:10> <N:11>let length = a.Length</N:11> <N:12>where value.Length == length</N:12> <N:13>select value + value</N:13></N:14>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("Program.Iterator"); var f1 = compilation1.GetMember<MethodSymbol>("Program.Iterator"); var f2 = compilation2.GetMember<MethodSymbol>("Program.Iterator"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 798 (0x31e) .maxstack 5 .locals init (int V_0, bool V_1, int V_2, bool V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_001b IL_0014: br IL_019b IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldarg.0 IL_001c: ldc.i4.m1 IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_0022: nop IL_0023: ldarg.0 IL_0024: ldc.i4.4 IL_0025: newarr ""string"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldstr ""a"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldstr ""bB"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldstr ""Cc"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldstr ""DD"" IL_0049: stelem.ref IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_004f: ldarg.0 IL_0050: ldnull IL_0051: ldnull IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_005c: ldarg.0 IL_005d: ldc.i4.0 IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0063: br IL_0305 IL_0068: nop IL_0069: ldarg.0 IL_006a: ldarg.0 IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_0075: dup IL_0076: brtrue.s IL_008f IL_0078: pop IL_0079: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)"" IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_0089: dup IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_0099: dup IL_009a: brtrue.s IL_00b3 IL_009c: pop IL_009d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_00ad: dup IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00bd: dup IL_00be: brtrue.s IL_00d7 IL_00c0: pop IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_00d1: dup IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00e1: dup IL_00e2: brtrue.s IL_00fb IL_00e4: pop IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)"" IL_00f5: dup IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)"" IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_0105: dup IL_0106: brtrue.s IL_011f IL_0108: pop IL_0109: ldsfld ""Program.<>c Program.<>c.<>9"" IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)"" IL_0119: dup IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)"" IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0129: dup IL_012a: brtrue.s IL_0143 IL_012c: pop IL_012d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_013d: dup IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_014d: ldarg.0 IL_014e: ldarg.0 IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_0154: ldnull IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_015a: dup IL_015b: brtrue.s IL_0174 IL_015d: pop IL_015e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)"" IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)"" IL_016e: dup IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)"" IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_017e: br.s IL_01f5 IL_0180: nop IL_0181: ldarg.0 IL_0182: ldarg.0 IL_0183: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_0188: callvirt ""string <>f__AnonymousType0<string, dynamic>.Head.get"" IL_018d: stfld ""string Program.<Iterator>d__1.<>2__current"" IL_0192: ldarg.0 IL_0193: ldc.i4.1 IL_0194: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_0199: ldc.i4.1 IL_019a: ret IL_019b: ldarg.0 IL_019c: ldc.i4.m1 IL_019d: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_01a2: ldarg.0 IL_01a3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01a8: brfalse.s IL_01ac IL_01aa: br.s IL_01d0 IL_01ac: ldc.i4.0 IL_01ad: ldtoken ""<>f__AnonymousType0<string, dynamic>"" IL_01b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b7: ldtoken ""Program"" IL_01bc: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01c1: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_01c6: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01cb: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01d0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01d5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Target"" IL_01da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01df: ldarg.0 IL_01e0: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_01e5: callvirt ""dynamic <>f__AnonymousType0<string, dynamic>.Tail.get"" IL_01ea: callvirt ""<anonymous type: string Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01ef: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_01f4: nop IL_01f5: ldarg.0 IL_01f6: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_01fb: ldnull IL_01fc: cgt.un IL_01fe: stloc.1 IL_01ff: ldloc.1 IL_0200: brtrue IL_0180 IL_0205: ldarg.0 IL_0206: ldarg.0 IL_0207: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_020c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_0211: dup IL_0212: brtrue.s IL_022b IL_0214: pop IL_0215: ldsfld ""Program.<>c Program.<>c.<>9"" IL_021a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)"" IL_0220: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)"" IL_0225: dup IL_0226: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_022b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)"" IL_0230: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_0235: dup IL_0236: brtrue.s IL_024f IL_0238: pop IL_0239: ldsfld ""Program.<>c Program.<>c.<>9"" IL_023e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)"" IL_0244: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)"" IL_0249: dup IL_024a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_024f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)"" IL_0254: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_0259: dup IL_025a: brtrue.s IL_0273 IL_025c: pop IL_025d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0262: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_0268: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)"" IL_026d: dup IL_026e: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_0273: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)"" IL_0278: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_027d: dup IL_027e: brtrue.s IL_0297 IL_0280: pop IL_0281: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0286: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_028c: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)"" IL_0291: dup IL_0292: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_0297: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)"" IL_029c: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02a1: ldarg.0 IL_02a2: ldarg.0 IL_02a3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_02a8: ldarg.0 IL_02a9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02ae: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)"" IL_02b3: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)"" IL_02b8: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_02bd: ldarg.0 IL_02be: ldarg.0 IL_02bf: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_02c4: box ""int"" IL_02c9: ldarg.0 IL_02ca: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_02cf: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_02d4: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_02d9: call ""void System.Diagnostics.Debugger.Break()"" IL_02de: nop IL_02df: nop IL_02e0: ldarg.0 IL_02e1: ldnull IL_02e2: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_02e7: ldarg.0 IL_02e8: ldnull IL_02e9: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_02ee: ldarg.0 IL_02ef: ldnull IL_02f0: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02f5: ldarg.0 IL_02f6: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_02fb: stloc.2 IL_02fc: ldarg.0 IL_02fd: ldloc.2 IL_02fe: ldc.i4.1 IL_02ff: add IL_0300: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0305: ldarg.0 IL_0306: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_030b: ldc.i4.s 10 IL_030d: clt IL_030f: stloc.3 IL_0310: ldloc.3 IL_0311: brtrue IL_0068 IL_0316: call ""void System.Diagnostics.Debugger.Break()"" IL_031b: nop IL_031c: ldc.i4.0 IL_031d: ret }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program.<>o__1#1: {<>p__0, <>p__1}", "Program: {<>o__1#1, <>c, <Iterator>d__1}", "Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}", "Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 885 (0x375) .maxstack 5 .locals init (int V_0, bool V_1, int V_2, bool V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_001b IL_0014: br IL_01eb IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldarg.0 IL_001c: ldc.i4.m1 IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_0022: nop IL_0023: ldarg.0 IL_0024: ldc.i4.4 IL_0025: newarr ""string"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldstr ""a"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldstr ""bB"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldstr ""Cc"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldstr ""DD"" IL_0049: stelem.ref IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_004f: ldarg.0 IL_0050: ldnull IL_0051: ldnull IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_005c: ldarg.0 IL_005d: ldc.i4.0 IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0063: br IL_035c IL_0068: nop IL_0069: ldarg.0 IL_006a: ldarg.0 IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_0075: dup IL_0076: brtrue.s IL_008f IL_0078: pop IL_0079: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)"" IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_0089: dup IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_0099: dup IL_009a: brtrue.s IL_00b3 IL_009c: pop IL_009d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_00ad: dup IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00bd: dup IL_00be: brtrue.s IL_00d7 IL_00c0: pop IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_00d1: dup IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00e1: dup IL_00e2: brtrue.s IL_00fb IL_00e4: pop IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)"" IL_00f5: dup IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)"" IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_0105: dup IL_0106: brtrue.s IL_011f IL_0108: pop IL_0109: ldsfld ""Program.<>c Program.<>c.<>9"" IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)"" IL_0119: dup IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)"" IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0129: dup IL_012a: brtrue.s IL_0143 IL_012c: pop IL_012d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_013d: dup IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_014d: ldarg.0 IL_014e: ldarg.0 IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_0154: ldnull IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_015a: dup IL_015b: brtrue.s IL_0174 IL_015d: pop IL_015e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)"" IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)"" IL_016e: dup IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)"" IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_017e: ldarg.0 IL_017f: ldarg.0 IL_0180: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_0185: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_018a: br IL_0245 IL_018f: nop IL_0190: ldarg.0 IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_0196: brfalse.s IL_019a IL_0198: br.s IL_01be IL_019a: ldc.i4.0 IL_019b: ldtoken ""string"" IL_01a0: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01a5: ldtoken ""Program"" IL_01aa: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01af: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_01b4: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01b9: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_01be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_01c3: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Target"" IL_01c8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_01cd: ldarg.0 IL_01ce: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_01d3: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Head.get"" IL_01d8: callvirt ""string System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01dd: stfld ""string Program.<Iterator>d__1.<>2__current"" IL_01e2: ldarg.0 IL_01e3: ldc.i4.1 IL_01e4: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_01e9: ldc.i4.1 IL_01ea: ret IL_01eb: ldarg.0 IL_01ec: ldc.i4.m1 IL_01ed: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_01f2: ldarg.0 IL_01f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_01f8: brfalse.s IL_01fc IL_01fa: br.s IL_0220 IL_01fc: ldc.i4.0 IL_01fd: ldtoken ""<>f__AnonymousType0<dynamic, dynamic>"" IL_0202: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0207: ldtoken ""Program"" IL_020c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0211: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0216: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_021b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_0220: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_0225: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Target"" IL_022a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_022f: ldarg.0 IL_0230: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_0235: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Tail.get"" IL_023a: callvirt ""<anonymous type: dynamic Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_023f: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_0244: nop IL_0245: ldarg.0 IL_0246: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_024b: ldnull IL_024c: cgt.un IL_024e: stloc.1 IL_024f: ldloc.1 IL_0250: brtrue IL_018f IL_0255: ldarg.0 IL_0256: ldarg.0 IL_0257: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_025c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_0261: dup IL_0262: brtrue.s IL_027b IL_0264: pop IL_0265: ldsfld ""Program.<>c Program.<>c.<>9"" IL_026a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)"" IL_0270: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)"" IL_0275: dup IL_0276: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_027b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)"" IL_0280: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_0285: dup IL_0286: brtrue.s IL_029f IL_0288: pop IL_0289: ldsfld ""Program.<>c Program.<>c.<>9"" IL_028e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)"" IL_0294: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)"" IL_0299: dup IL_029a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_029f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)"" IL_02a4: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_02a9: dup IL_02aa: brtrue.s IL_02c3 IL_02ac: pop IL_02ad: ldsfld ""Program.<>c Program.<>c.<>9"" IL_02b2: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_02b8: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)"" IL_02bd: dup IL_02be: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_02c3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)"" IL_02c8: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_02cd: dup IL_02ce: brtrue.s IL_02e7 IL_02d0: pop IL_02d1: ldsfld ""Program.<>c Program.<>c.<>9"" IL_02d6: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_02dc: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)"" IL_02e1: dup IL_02e2: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_02e7: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)"" IL_02ec: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02f1: ldarg.0 IL_02f2: ldarg.0 IL_02f3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_02f8: ldarg.0 IL_02f9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02fe: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)"" IL_0303: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)"" IL_0308: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_030d: ldarg.0 IL_030e: ldarg.0 IL_030f: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0314: box ""int"" IL_0319: ldarg.0 IL_031a: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_031f: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_0324: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_0329: call ""void System.Diagnostics.Debugger.Break()"" IL_032e: nop IL_032f: nop IL_0330: ldarg.0 IL_0331: ldnull IL_0332: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_0337: ldarg.0 IL_0338: ldnull IL_0339: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_033e: ldarg.0 IL_033f: ldnull IL_0340: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_0345: ldarg.0 IL_0346: ldnull IL_0347: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_034c: ldarg.0 IL_034d: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0352: stloc.2 IL_0353: ldarg.0 IL_0354: ldloc.2 IL_0355: ldc.i4.1 IL_0356: add IL_0357: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_035c: ldarg.0 IL_035d: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0362: ldc.i4.s 10 IL_0364: clt IL_0366: stloc.3 IL_0367: ldloc.3 IL_0368: brtrue IL_0068 IL_036d: call ""void System.Diagnostics.Debugger.Break()"" IL_0372: nop IL_0373: ldc.i4.0 IL_0374: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>o__1#1: {<>p__0, <>p__1}", "Program.<>o__1#2: {<>p__0, <>p__1, <>p__2}", "Program: {<>o__1#2, <>c, <Iterator>d__1, <>o__1#1}", "Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}", "Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); } [Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")] public void MissingIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (7,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(7, 29)); } [Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")] public void BadIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { } } class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // the ctor is missing a parameter Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (12,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing. // public IEnumerable<int> F() Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(12, 29)); } [Fact] public void AddedIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var ism1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.IteratorStateMachineAttribute"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, ism1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // We conclude the original method wasn't a state machine. // The IDE however reports a Rude Edit in that case. diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void SourceIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")] public void MissingAsyncStateMachineAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 0</N:0>; <N:1>await new Task();</N:1> return a; } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>await new Task();</N:1> return a; } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain AsyncStateMachineAttribute, IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28)); } [Fact] public void AddedAsyncStateMachineAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 0</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; namespace System.Runtime.CompilerServices { public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } } } class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var asm1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.AsyncStateMachineAttribute"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, asm1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void SourceAsyncStateMachineAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; namespace System.Runtime.CompilerServices { public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } } } class C { public async Task<int> F() { int <N:0>a = 0</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; namespace System.Runtime.CompilerServices { public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } } } class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact, WorkItem(10190, "https://github.com/dotnet/roslyn/issues/10190")] public void NonAsyncToAsync() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public Task<int> F() { int <N:0>a = 0</N:0>; <N:1>return Task.FromResult(a);</N:1> } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>return await Task.FromResult(a);</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void NonAsyncToAsync_MissingAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public Task<int> F() { int <N:0>a = 0</N:0>; a++; <N:1>return new Task<int>();</N:1> } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 1</N:0>; a++; <N:1>return await new Task<int>();</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28)); } [Fact] public void NonIteratorToIterator_MissingAttribute() { var source0 = MarkedSource(@" using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>return new int[] { a };</N:1> } } "); var source1 = MarkedSource(@" using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return a;</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(6, 29)); } [Fact] public void NonIteratorToIterator_SourceAttribute() { var source0 = MarkedSource(@" using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>return new int[] { a };</N:1> } } "); var source1 = MarkedSource(@" using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return a;</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void NonAsyncToAsyncLambda() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public object F() { return new System.Func<Task<int>>(<N:2>() => <N:3>{ int <N:0>a = 0</N:0>; <N:1>return Task.FromResult(a);</N:1> }</N:3></N:2>); } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public object F() { return new System.Func<Task<int>>(<N:2>async () => <N:3>{ int <N:0>a = 0</N:0>; <N:1>return await Task.FromResult(a);</N:1> }</N:3></N:2>); } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <F>b__0_0, <<F>b__0_0>d}", "C.<>c.<<F>b__0_0>d: {<>1__state, <>t__builder, <>4__this, <a>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine}"); } [Fact] public void AsyncMethodWithNullableParameterAddingNullCheck() { var source0 = MarkedSource(@" using System; using System.Threading.Tasks; #nullable enable class C { static T id<T>(T t) => t; static Task<T> G<T>(Func<T> f) => Task.FromResult(f()); static T H<T>(Func<T> f) => f(); public async void F(string? x) <N:4>{</N:4> var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>; var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>; } } ", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source1 = MarkedSource(@" using System; using System.Threading.Tasks; #nullable enable class C { static T id<T>(T t) => t; static Task<T> G<T>(Func<T> f) => Task.FromResult(f()); static T H<T>(Func<T> f) => f(); public async void F(string? x) <N:4>{</N:4> if (x is null) throw new Exception(); var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>; var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>; } } ", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, y, <F>b__1, <F>b__0}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "Microsoft: {CodeAnalysis}", "System.Runtime: {CompilerServices, CompilerServices}", "C: {<>c__DisplayClass3_0, <F>d__3}", "<global namespace>: {Microsoft, System, System}", "System: {Runtime, Runtime}", "C.<F>d__3: {<>1__state, <>t__builder, x, <>4__this, <>8__4, <z>5__2, <>s__5, <>u__1, MoveNext, SetStateMachine}"); diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__1()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""string C.<>c__DisplayClass3_0.x"" IL_0006: call ""string C.id<string>(string)"" IL_000b: newobj ""<>f__AnonymousType0<string>..ctor(string)"" IL_0010: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__0()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass3_0.y"" IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get"" IL_000b: ret } "); } } }
// Licensed to the .NET Foundation under one or more 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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class EditAndContinueStateMachineTests : EditAndContinueTestBase { [Fact] [WorkItem(1068894, "DevDiv"), WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")] public void AddIteratorMethod() { var source0 = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { } "); var source1 = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { static IEnumerable<int> G() { yield return 1; } } "); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(Parse(source1, "a.cs")); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var reader0 = md0.MetadataReader; // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<G>d__0#1"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(3, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(1, TableIndex.InterfaceImpl), Handle(2, TableIndex.InterfaceImpl), Handle(3, TableIndex.InterfaceImpl), Handle(4, TableIndex.InterfaceImpl), Handle(5, TableIndex.InterfaceImpl), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(2, TableIndex.Property), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics), Handle(1, TableIndex.MethodImpl), Handle(2, TableIndex.MethodImpl), Handle(3, TableIndex.MethodImpl), Handle(4, TableIndex.MethodImpl), Handle(5, TableIndex.MethodImpl), Handle(6, TableIndex.MethodImpl), Handle(7, TableIndex.MethodImpl), Handle(1, TableIndex.NestedClass)); diff1.VerifyPdb(Enumerable.Range(0x06000001, 0x20), @" <symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""66-9A-93-25-E7-42-DC-A9-DD-D1-61-3F-D9-45-A8-E1-39-8C-37-79"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <forwardIterator name=""&lt;G&gt;d__0#1"" /> </customDebugInfo> </method> <method token=""0x6000005""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x20"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x39""> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); } [Theory] [MemberData(nameof(ExternalPdbFormats))] public void AddAsyncMethod(DebugInformationFormat format) { var source0 = @" using System.Threading.Tasks; class C { }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await Task.FromResult(10); return 20; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format)); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<F>d__0#1"); CheckNames(readers, reader1.GetMethodDefNames(), "F", ".ctor", "MoveNext", "SetStateMachine"); CheckNames(readers, reader1.GetFieldDefNames(), "<>1__state", "<>t__builder", "<>u__1"); // Add state machine type and its members: // - Method '.ctor' // - Method 'MoveNext' // - Method 'SetStateMachine' // - Field '<>1__state' // - Field '<>t__builder' // - Field '<>u__1' // Add method F() CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); diff1.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(4) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x8c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x94"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa2""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod token=""0x6000002"" /> <await yield=""0x2e"" resume=""0x49"" token=""0x6000004"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void MethodToIteratorMethod() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return new int[] { 1, 2, 3 }; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckEncLogDefinitions(md1.Reader, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); } } } [Fact] public void MethodToAsyncMethod() { var source0 = @" using System.Threading.Tasks; class C { static Task<int> F() { return Task.FromResult(1); } }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { return await Task.FromResult(1); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckEncLogDefinitions(md1.Reader, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)); } } } [Fact] public void IteratorMethodToMethod() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return new int[] { 1, 2, 3 }; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckAttributes(md1.Reader, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete IteratorStateMachineAttribute } } } [Fact] public void AsyncMethodToMethod() { var source0 = @" using System.Threading.Tasks; class C { static async Task<int> F() { return await Task.FromResult(1); } }"; var source1 = @" using System.Threading.Tasks; class C { static Task<int> F() { return Task.FromResult(1); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using (var md1 = diff1.GetMetadata()) { CheckAttributes(md1.Reader, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef)), // row id 0 == delete new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Delete AsyncStateMachineAttribute Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete DebuggerStepThroughAttribute } } } [Fact] public void AsyncMethodOverloads() { var source0 = @" using System.Threading.Tasks; class C { static async Task<int> F(long a) { return await Task.FromResult(1); } static async Task<int> F(int a) { return await Task.FromResult(1); } static async Task<int> F(short a) { return await Task.FromResult(1); } }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F(short a) { return await Task.FromResult(2); } static async Task<int> F(long a) { return await Task.FromResult(3); } static async Task<int> F(int a) { return await Task.FromResult(4); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var methodShort0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)"); var methodShort1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)"); var methodInt0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)"); var methodInt1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)"); var methodLong0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)"); var methodLong1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodShort0, methodShort1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, methodInt0, methodInt1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, methodLong0, methodLong1, preserveLocalVariables: true) )); using (var md1 = diff1.GetMetadata()) { // notice no TypeDefs, FieldDefs CheckEncLogDefinitions(md1.Reader, Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } } } [Fact] public void UpdateIterator_NoVariables() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 1; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { md0.MetadataReader, reader1 }; // only methods with sequence points should be listed in UpdatedMethods: CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0"); // Verify that no new TypeDefs, FieldDefs or MethodDefs were added, // 3 methods were updated: // - the kick-off method (might be changed if the method previously wasn't an iterator) // - Finally method // - MoveNext method CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 57 (0x39) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_0030 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.2 IL_0022: stfld ""int C.<F>d__0.<>2__current"" IL_0027: ldarg.0 IL_0028: ldc.i4.1 IL_0029: stfld ""int C.<F>d__0.<>1__state"" IL_002e: ldc.i4.1 IL_002f: ret IL_0030: ldarg.0 IL_0031: ldc.i4.m1 IL_0032: stfld ""int C.<F>d__0.<>1__state"" IL_0037: ldc.i4.0 IL_0038: ret }"); v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 57 (0x39) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_0030 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: stfld ""int C.<F>d__0.<>2__current"" IL_0027: ldarg.0 IL_0028: ldc.i4.1 IL_0029: stfld ""int C.<F>d__0.<>1__state"" IL_002e: ldc.i4.1 IL_002f: ret IL_0030: ldarg.0 IL_0031: ldc.i4.m1 IL_0032: stfld ""int C.<F>d__0.<>1__state"" IL_0037: ldc.i4.0 IL_0038: ret }"); } [Fact] public void UpdateAsync_NoVariables() { var source0 = WithWindowsLineBreaks(@" using System.Threading.Tasks; class C { static async Task<int> F() { await Task.FromResult(1); return 2; } }"); var source1 = WithWindowsLineBreaks(@" using System.Threading.Tasks; class C { static async Task<int> F() { await Task.FromResult(10); return 20; } }"); var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { md0.MetadataReader, reader1 }; // only methods with sequence points should be listed in UpdatedMethods: CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0"); // Verify that no new TypeDefs, FieldDefs or MethodDefs were added, // 2 methods were updated: // - the kick-off method (might be changed if the method previously wasn't async) // - MoveNext method CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 162 (0xa2) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0049 IL_000e: nop IL_000f: ldc.i4.s 10 IL_0011: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)"" IL_0016: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_001b: stloc.2 IL_001c: ldloca.s V_2 IL_001e: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0023: brtrue.s IL_0065 IL_0025: ldarg.0 IL_0026: ldc.i4.0 IL_0027: dup IL_0028: stloc.0 IL_0029: stfld ""int C.<F>d__0.<>1__state"" IL_002e: ldarg.0 IL_002f: ldloc.2 IL_0030: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0035: ldarg.0 IL_0036: stloc.3 IL_0037: ldarg.0 IL_0038: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_003d: ldloca.s V_2 IL_003f: ldloca.s V_3 IL_0041: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_0046: nop IL_0047: leave.s IL_00a1 IL_0049: ldarg.0 IL_004a: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_004f: stloc.2 IL_0050: ldarg.0 IL_0051: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0056: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_005c: ldarg.0 IL_005d: ldc.i4.m1 IL_005e: dup IL_005f: stloc.0 IL_0060: stfld ""int C.<F>d__0.<>1__state"" IL_0065: ldloca.s V_2 IL_0067: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_006c: pop IL_006d: ldc.i4.s 20 IL_006f: stloc.1 IL_0070: leave.s IL_008c } catch System.Exception { IL_0072: stloc.s V_4 IL_0074: ldarg.0 IL_0075: ldc.i4.s -2 IL_0077: stfld ""int C.<F>d__0.<>1__state"" IL_007c: ldarg.0 IL_007d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0082: ldloc.s V_4 IL_0084: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_0089: nop IL_008a: leave.s IL_00a1 } IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int C.<F>d__0.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_009a: ldloc.1 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00a0: nop IL_00a1: ret }"); v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 160 (0xa0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0048 -IL_000e: nop -IL_000f: ldc.i4.1 IL_0010: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)"" IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_001a: stloc.2 ~IL_001b: ldloca.s V_2 IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0022: brtrue.s IL_0064 IL_0024: ldarg.0 IL_0025: ldc.i4.0 IL_0026: dup IL_0027: stloc.0 IL_0028: stfld ""int C.<F>d__0.<>1__state"" <IL_002d: ldarg.0 IL_002e: ldloc.2 IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0034: ldarg.0 IL_0035: stloc.3 IL_0036: ldarg.0 IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_003c: ldloca.s V_2 IL_003e: ldloca.s V_3 IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_0045: nop IL_0046: leave.s IL_009f >IL_0048: ldarg.0 IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_004e: stloc.2 IL_004f: ldarg.0 IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_005b: ldarg.0 IL_005c: ldc.i4.m1 IL_005d: dup IL_005e: stloc.0 IL_005f: stfld ""int C.<F>d__0.<>1__state"" IL_0064: ldloca.s V_2 IL_0066: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_006b: pop -IL_006c: ldc.i4.2 IL_006d: stloc.1 IL_006e: leave.s IL_008a } catch System.Exception { ~IL_0070: stloc.s V_4 IL_0072: ldarg.0 IL_0073: ldc.i4.s -2 IL_0075: stfld ""int C.<F>d__0.<>1__state"" IL_007a: ldarg.0 IL_007b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0080: ldloc.s V_4 IL_0082: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_0087: nop IL_0088: leave.s IL_009f } -IL_008a: ldarg.0 IL_008b: ldc.i4.s -2 IL_008d: stfld ""int C.<F>d__0.<>1__state"" ~IL_0092: ldarg.0 IL_0093: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0098: ldloc.1 IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_009e: nop IL_009f: ret }", sequencePoints: "C+<F>d__0.MoveNext"); v0.VerifyPdb("C+<F>d__0.MoveNext", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;F&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""20"" offset=""0"" /> <slot kind=""33"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""34"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x6c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> <entry offset=""0x70"" hidden=""true"" document=""1"" /> <entry offset=""0x8a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x92"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa0""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""F"" /> <await yield=""0x2d"" resume=""0x48"" declaringType=""C+&lt;F&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void UpdateIterator_UserDefinedVariables_NoChange() { var source0 = @" using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return 1; } }"; var source1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return 2; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // Verify that no new TypeDefs, FieldDefs or MethodDefs were added, // 3 methods were updated: // - the kick-off method (might be changed if the method previously wasn't an iterator) // - Finally method // - MoveNext method CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 69 (0x45) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""int C.<F>d__0.p"" IL_0027: stfld ""int C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.2 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldc.i4.0 IL_0044: ret }"); } } } [Fact] public void UpdateIterator_UserDefinedVariables_AddVariable() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return x; } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int y = 1234; int x = p; yield return y; Console.WriteLine(x); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(7, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 97 (0x61) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_004c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4 0x4d2 IL_0026: stfld ""int C.<F>d__0.<y>5__2"" IL_002b: ldarg.0 IL_002c: ldarg.0 IL_002d: ldfld ""int C.<F>d__0.p"" IL_0032: stfld ""int C.<F>d__0.<x>5__1"" IL_0037: ldarg.0 IL_0038: ldarg.0 IL_0039: ldfld ""int C.<F>d__0.<y>5__2"" IL_003e: stfld ""int C.<F>d__0.<>2__current"" IL_0043: ldarg.0 IL_0044: ldc.i4.1 IL_0045: stfld ""int C.<F>d__0.<>1__state"" IL_004a: ldc.i4.1 IL_004b: ret IL_004c: ldarg.0 IL_004d: ldc.i4.m1 IL_004e: stfld ""int C.<F>d__0.<>1__state"" IL_0053: ldarg.0 IL_0054: ldfld ""int C.<F>d__0.<x>5__1"" IL_0059: call ""void System.Console.WriteLine(int)"" IL_005e: nop IL_005f: ldc.i4.0 IL_0060: ret }"); } } } [Fact] public void UpdateIterator_UserDefinedVariables_AddAndRemoveVariable() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int x = p; yield return x; } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F(int p) { int y = 1234; yield return y; Console.WriteLine(p); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(7, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 85 (0x55) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_0040 IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4 0x4d2 IL_0026: stfld ""int C.<F>d__0.<y>5__2"" IL_002b: ldarg.0 IL_002c: ldarg.0 IL_002d: ldfld ""int C.<F>d__0.<y>5__2"" IL_0032: stfld ""int C.<F>d__0.<>2__current"" IL_0037: ldarg.0 IL_0038: ldc.i4.1 IL_0039: stfld ""int C.<F>d__0.<>1__state"" IL_003e: ldc.i4.1 IL_003f: ret IL_0040: ldarg.0 IL_0041: ldc.i4.m1 IL_0042: stfld ""int C.<F>d__0.<>1__state"" IL_0047: ldarg.0 IL_0048: ldfld ""int C.<F>d__0.p"" IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ldc.i4.0 IL_0054: ret }"); } } } [Fact] public void UpdateIterator_UserDefinedVariables_ChangeVariableType() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { var x = 1; yield return 1; Console.WriteLine(x); } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { var x = 1.0; yield return 2; Console.WriteLine(x); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(5, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 84 (0x54) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003f IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.r8 1 IL_002a: stfld ""double C.<F>d__0.<x>5__2"" IL_002f: ldarg.0 IL_0030: ldc.i4.2 IL_0031: stfld ""int C.<F>d__0.<>2__current"" IL_0036: ldarg.0 IL_0037: ldc.i4.1 IL_0038: stfld ""int C.<F>d__0.<>1__state"" IL_003d: ldc.i4.1 IL_003e: ret IL_003f: ldarg.0 IL_0040: ldc.i4.m1 IL_0041: stfld ""int C.<F>d__0.<>1__state"" IL_0046: ldarg.0 IL_0047: ldfld ""double C.<F>d__0.<x>5__2"" IL_004c: call ""void System.Console.WriteLine(double)"" IL_0051: nop IL_0052: ldc.i4.0 IL_0053: ret }"); } } } [Fact] public void UpdateIterator_SynthesizedVariables_ChangeVariableType() { var source0 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { foreach (object item in new[] { 1 }) { yield return 1; } } }"; var source1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { foreach (object item in new[] { 1.0 }) { yield return 1; } } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>2__current: int", "<>l__initialThreadId: int", "<>s__1: int[]", "<>s__2: int", "<item>5__3: object" }, module.GetFieldNamesAndTypes("C.<F>d__0")); }); var symReader = v0.CreateSymReader(); using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)) { var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForEachStatement), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using (var md1 = diff1.GetMetadata()) { // 1 field def added & 3 methods updated CheckEncLogDefinitions(md1.Reader, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(7, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 161 (0xa1) .maxstack 5 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_006b IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: nop IL_0021: ldarg.0 IL_0022: ldc.i4.1 IL_0023: newarr ""double"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.r8 1 IL_0033: stelem.r8 IL_0034: stfld ""double[] C.<F>d__0.<>s__4"" IL_0039: ldarg.0 IL_003a: ldc.i4.0 IL_003b: stfld ""int C.<F>d__0.<>s__2"" IL_0040: br.s IL_0088 IL_0042: ldarg.0 IL_0043: ldarg.0 IL_0044: ldfld ""double[] C.<F>d__0.<>s__4"" IL_0049: ldarg.0 IL_004a: ldfld ""int C.<F>d__0.<>s__2"" IL_004f: ldelem.r8 IL_0050: box ""double"" IL_0055: stfld ""object C.<F>d__0.<item>5__3"" IL_005a: nop IL_005b: ldarg.0 IL_005c: ldc.i4.1 IL_005d: stfld ""int C.<F>d__0.<>2__current"" IL_0062: ldarg.0 IL_0063: ldc.i4.1 IL_0064: stfld ""int C.<F>d__0.<>1__state"" IL_0069: ldc.i4.1 IL_006a: ret IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: stfld ""int C.<F>d__0.<>1__state"" IL_0072: nop IL_0073: ldarg.0 IL_0074: ldnull IL_0075: stfld ""object C.<F>d__0.<item>5__3"" IL_007a: ldarg.0 IL_007b: ldarg.0 IL_007c: ldfld ""int C.<F>d__0.<>s__2"" IL_0081: ldc.i4.1 IL_0082: add IL_0083: stfld ""int C.<F>d__0.<>s__2"" IL_0088: ldarg.0 IL_0089: ldfld ""int C.<F>d__0.<>s__2"" IL_008e: ldarg.0 IL_008f: ldfld ""double[] C.<F>d__0.<>s__4"" IL_0094: ldlen IL_0095: conv.i4 IL_0096: blt.s IL_0042 IL_0098: ldarg.0 IL_0099: ldnull IL_009a: stfld ""double[] C.<F>d__0.<>s__4"" IL_009f: ldc.i4.0 IL_00a0: ret }"); } } } [Fact] public void HoistedVariables_MultipleGenerations() { var source0 = @" using System.Threading.Tasks; class C { static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2 { bool a1 = true; int a2 = 3; await Task.Delay(0); return 1; } static async Task<int> G() // testing G1 -> G3 { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } static async Task<int> H() // testing G0 -> G3 { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } }"; var source1 = @" using System.Threading.Tasks; class C { static async Task<int> F() // updated { C a1 = new C(); int a2 = 3; await Task.Delay(0); return 1; } static async Task<int> G() // updated { C c = new C(); bool a1 = true; await Task.Delay(0); return 2; } static async Task<int> H() { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } }"; var source2 = @" using System.Threading.Tasks; class C { static async Task<int> F() // updated { bool a1 = true; C a2 = new C(); await Task.Delay(0); return 1; } static async Task<int> G() { C c = new C(); bool a1 = true; await Task.Delay(0); return 2; } static async Task<int> H() { C c = new C(); bool a1 = true; await Task.Delay(0); return 1; } }"; var source3 = @" using System.Threading.Tasks; class C { static async Task<int> F() { bool a1 = true; C a2 = new C(); await Task.Delay(0); return 1; } static async Task<int> G() // updated { C c = new C(); C a1 = new C(); await Task.Delay(0); return 1; } static async Task<int> H() // updated { C c = new C(); C a1 = new C(); await Task.Delay(0); return 1; } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var h0 = compilation0.GetMember<MethodSymbol>("C.H"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); var h2 = compilation2.GetMember<MethodSymbol>("C.H"); var h3 = compilation3.GetMember<MethodSymbol>("C.H"); var v0 = CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<a1>5__1: bool", "<a2>5__2: int", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter" }, module.GetFieldNamesAndTypes("C.<F>d__0")); }); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__0, <G>d__1}", "C.<F>d__0: {<>1__state, <>t__builder, <a1>5__3, <a2>5__2, <>u__1, MoveNext, SetStateMachine}", "C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0, <G>d__1}", "C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}", "C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetEquivalentNodesMap(h3, h2), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<G>d__1, <H>d__2, <F>d__0}", "C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}", "C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine, <a1>5__2}", "C.<H>d__2: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine}"); // Verify delta metadata contains expected rows. var md1 = diff1.GetMetadata(); var md2 = diff2.GetMetadata(); var md3 = diff3.GetMetadata(); // 1 field def added & 4 methods updated (MoveNext and kickoff for F and G) CheckEncLogDefinitions(md1.Reader, Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(16, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 192 (0xc0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter V_2, C.<F>d__0 V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_005a IL_000e: nop IL_000f: ldarg.0 IL_0010: newobj ""C..ctor()"" IL_0015: stfld ""C C.<F>d__0.<a1>5__3"" IL_001a: ldarg.0 IL_001b: ldc.i4.3 IL_001c: stfld ""int C.<F>d__0.<a2>5__2"" IL_0021: ldc.i4.0 IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)"" IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_002c: stloc.2 IL_002d: ldloca.s V_2 IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0034: brtrue.s IL_0076 IL_0036: ldarg.0 IL_0037: ldc.i4.0 IL_0038: dup IL_0039: stloc.0 IL_003a: stfld ""int C.<F>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldloc.2 IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0046: ldarg.0 IL_0047: stloc.3 IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldloca.s V_3 IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)"" IL_0057: nop IL_0058: leave.s IL_00bf IL_005a: ldarg.0 IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0060: stloc.2 IL_0061: ldarg.0 IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_006d: ldarg.0 IL_006e: ldc.i4.m1 IL_006f: dup IL_0070: stloc.0 IL_0071: stfld ""int C.<F>d__0.<>1__state"" IL_0076: ldloca.s V_2 IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_007d: nop IL_007e: ldc.i4.1 IL_007f: stloc.1 IL_0080: leave.s IL_00a3 } catch System.Exception { IL_0082: stloc.s V_4 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int C.<F>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldnull IL_008e: stfld ""C C.<F>d__0.<a1>5__3"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0099: ldloc.s V_4 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00a0: nop IL_00a1: leave.s IL_00bf } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int C.<F>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldnull IL_00ad: stfld ""C C.<F>d__0.<a1>5__3"" IL_00b2: ldarg.0 IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00b8: ldloc.1 IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00be: nop IL_00bf: ret }"); // 2 field defs added (both variables a1 and a2 of F changed their types) & 2 methods updated CheckEncLogDefinitions(md2.Reader, Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(17, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(18, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff2.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 192 (0xc0) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter V_2, C.<F>d__0 V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_005a IL_000e: nop IL_000f: ldarg.0 IL_0010: ldc.i4.1 IL_0011: stfld ""bool C.<F>d__0.<a1>5__4"" IL_0016: ldarg.0 IL_0017: newobj ""C..ctor()"" IL_001c: stfld ""C C.<F>d__0.<a2>5__5"" IL_0021: ldc.i4.0 IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)"" IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_002c: stloc.2 IL_002d: ldloca.s V_2 IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0034: brtrue.s IL_0076 IL_0036: ldarg.0 IL_0037: ldc.i4.0 IL_0038: dup IL_0039: stloc.0 IL_003a: stfld ""int C.<F>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldloc.2 IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0046: ldarg.0 IL_0047: stloc.3 IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_004e: ldloca.s V_2 IL_0050: ldloca.s V_3 IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)"" IL_0057: nop IL_0058: leave.s IL_00bf IL_005a: ldarg.0 IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0060: stloc.2 IL_0061: ldarg.0 IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_006d: ldarg.0 IL_006e: ldc.i4.m1 IL_006f: dup IL_0070: stloc.0 IL_0071: stfld ""int C.<F>d__0.<>1__state"" IL_0076: ldloca.s V_2 IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_007d: nop IL_007e: ldc.i4.1 IL_007f: stloc.1 IL_0080: leave.s IL_00a3 } catch System.Exception { IL_0082: stloc.s V_4 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int C.<F>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldnull IL_008e: stfld ""C C.<F>d__0.<a2>5__5"" IL_0093: ldarg.0 IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0099: ldloc.s V_4 IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00a0: nop IL_00a1: leave.s IL_00bf } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int C.<F>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldnull IL_00ad: stfld ""C C.<F>d__0.<a2>5__5"" IL_00b2: ldarg.0 IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00b8: ldloc.1 IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00be: nop IL_00bf: ret }"); // 2 field defs added - variables of G and H changed their types; 4 methods updated: G, H kickoff and MoveNext CheckEncLogDefinitions(md3.Reader, Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(19, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(20, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void HoistedVariables_Dynamic1() { var template = @" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { dynamic <N:0>x = 1</N:0>; yield return 1; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 147 (0x93) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: box ""int"" IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.1 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0048: brfalse.s IL_004c IL_004a: br.s IL_0071 IL_004c: ldc.i4.s 16 IL_004e: ldtoken ""int"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0080: ldarg.0 IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1"" IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_008b: call ""void System.Console.WriteLine(int)"" IL_0090: nop IL_0091: ldc.i4.0 IL_0092: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var baselineIL = @" { // Code size 149 (0x95) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: box ""int"" IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.1 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0048: brfalse.s IL_004c IL_004a: br.s IL_0071 IL_004c: ldc.i4.s 16 IL_004e: ldtoken ""int"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0"" IL_0080: ldarg.0 IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1"" IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_008b: ldc.i4.<<VALUE>> IL_008c: add IL_008d: call ""void System.Console.WriteLine(int)"" IL_0092: nop IL_0093: ldc.i4.0 IL_0094: ret }"; diff1.VerifySynthesizedMembers( "C: {<>o__0#1, <F>d__0}", "C.<>o__0#1: {<>p__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <F>d__0, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#2")); } [Fact] public void HoistedVariables_Dynamic2() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { private static IEnumerable<string> F() { dynamic <N:0>d = ""x""</N:0>; yield return d; Console.WriteLine(0); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { private static IEnumerable<string> F() { dynamic <N:0>d = ""x""</N:0>; yield return d.ToString(); Console.WriteLine(1); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class C { private static IEnumerable<string> F() { dynamic <N:0>d = ""x""</N:0>; yield return d; Console.WriteLine(2); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1, <F>d__0}", "C.<>o__0#1: {<>p__0, <>p__1}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <F>d__0, <>o__0#1}", "C.<>o__0#1: {<>p__0, <>p__1}", "C.<>o__0#2: {<>p__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}"); } [Fact] public void Awaiters1() { var source0 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; static async Task<int> F() { await A1(); await A2(); return 1; } static async Task<int> G() { await A2(); await A1(); return 1; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>" }, module.GetFieldNamesAndTypes("C.<F>d__3")); Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<int>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<bool>" }, module.GetFieldNamesAndTypes("C.<G>d__4")); }); } [Theory] [MemberData(nameof(ExternalPdbFormats))] public void Awaiters_MultipleGenerations(DebugInformationFormat format) { var source0 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2 { await A1(); await A2(); return 1; } static async Task<int> G() // testing G1 -> G3 { await A1(); return 1; } static async Task<int> H() // testing G0 -> G3 { await A1(); return 1; } }"; var source1 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() // updated { await A3(); await A2(); return 1; } static async Task<int> G() // updated { await A1(); return 2; } static async Task<int> H() { await A1(); return 1; } }"; var source2 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() // updated { await A1(); await A3(); return 1; } static async Task<int> G() { await A1(); return 2; } static async Task<int> H() { await A1(); return 1; } }"; var source3 = @" using System.Threading.Tasks; class C { static Task<bool> A1() => null; static Task<int> A2() => null; static Task<C> A3() => null; static async Task<int> F() { await A1(); await A3(); return 1; } static async Task<int> G() // updated { await A3(); return 1; } static async Task<int> H() // updated { await A3(); return 1; } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var h0 = compilation0.GetMember<MethodSymbol>("C.H"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); var h2 = compilation2.GetMember<MethodSymbol>("C.H"); var h3 = compilation3.GetMember<MethodSymbol>("C.H"); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format), symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>" }, module.GetFieldNamesAndTypes("C.<F>d__3")); }); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapByKind(f0, SyntaxKind.Block), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapByKind(g0, SyntaxKind.Block), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__3, <G>d__4}", "C.<F>d__3: {<>1__state, <>t__builder, <>u__3, <>u__2, MoveNext, SetStateMachine}", "C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__3, <G>d__4}", "C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}", "C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetSyntaxMapByKind(g2, SyntaxKind.Block), preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetSyntaxMapByKind(h2, SyntaxKind.Block), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<G>d__4, <H>d__5, <F>d__3}", "C.<G>d__4: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine, <>u__1}", "C.<H>d__5: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine}", "C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}"); // Verify delta metadata contains expected rows. var md1 = diff1.GetMetadata(); var md2 = diff2.GetMetadata(); var md3 = diff3.GetMetadata(); diff1.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(9) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000009""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x79"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""20"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0xdc"" hidden=""true"" document=""1"" /> <entry offset=""0xf6"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0xfe"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10c""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod token=""0x6000004"" /> <await yield=""0x37"" resume=""0x55"" token=""0x6000009"" /> <await yield=""0x97"" resume=""0xb3"" token=""0x6000009"" /> </asyncInfo> </method> </methods> </symbols>"); // 1 field def added & 4 methods updated (MoveNext and kickoff for F and G) CheckEncLogDefinitions(md1.Reader, Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(11, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Note that the new awaiter is allocated slot <>u__3 since <>u__1 and <>u__2 are taken. diff1.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 268 (0x10c) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<C> V_2, C.<F>d__3 V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__3.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_0055 IL_0014: br IL_00b3 IL_0019: nop IL_001a: call ""System.Threading.Tasks.Task<C> C.A3()"" IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()"" IL_0024: stloc.2 IL_0025: ldloca.s V_2 IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get"" IL_002c: brtrue.s IL_0071 IL_002e: ldarg.0 IL_002f: ldc.i4.0 IL_0030: dup IL_0031: stloc.0 IL_0032: stfld ""int C.<F>d__3.<>1__state"" IL_0037: ldarg.0 IL_0038: ldloc.2 IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_003e: ldarg.0 IL_003f: stloc.3 IL_0040: ldarg.0 IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0046: ldloca.s V_2 IL_0048: ldloca.s V_3 IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)"" IL_004f: nop IL_0050: leave IL_010b IL_0055: ldarg.0 IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_005b: stloc.2 IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>"" IL_0068: ldarg.0 IL_0069: ldc.i4.m1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld ""int C.<F>d__3.<>1__state"" IL_0071: ldloca.s V_2 IL_0073: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()"" IL_0078: pop IL_0079: call ""System.Threading.Tasks.Task<int> C.A2()"" IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0083: stloc.s V_4 IL_0085: ldloca.s V_4 IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_008c: brtrue.s IL_00d0 IL_008e: ldarg.0 IL_008f: ldc.i4.1 IL_0090: dup IL_0091: stloc.0 IL_0092: stfld ""int C.<F>d__3.<>1__state"" IL_0097: ldarg.0 IL_0098: ldloc.s V_4 IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2"" IL_009f: ldarg.0 IL_00a0: stloc.3 IL_00a1: ldarg.0 IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00a7: ldloca.s V_4 IL_00a9: ldloca.s V_3 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__3)"" IL_00b0: nop IL_00b1: leave.s IL_010b IL_00b3: ldarg.0 IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2"" IL_00b9: stloc.s V_4 IL_00bb: ldarg.0 IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2"" IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00c7: ldarg.0 IL_00c8: ldc.i4.m1 IL_00c9: dup IL_00ca: stloc.0 IL_00cb: stfld ""int C.<F>d__3.<>1__state"" IL_00d0: ldloca.s V_4 IL_00d2: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00d7: pop IL_00d8: ldc.i4.1 IL_00d9: stloc.1 IL_00da: leave.s IL_00f6 } catch System.Exception { IL_00dc: stloc.s V_5 IL_00de: ldarg.0 IL_00df: ldc.i4.s -2 IL_00e1: stfld ""int C.<F>d__3.<>1__state"" IL_00e6: ldarg.0 IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00ec: ldloc.s V_5 IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00f3: nop IL_00f4: leave.s IL_010b } IL_00f6: ldarg.0 IL_00f7: ldc.i4.s -2 IL_00f9: stfld ""int C.<F>d__3.<>1__state"" IL_00fe: ldarg.0 IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0104: ldloc.1 IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_010a: nop IL_010b: ret }"); // 1 field def added & 2 methods updated CheckEncLogDefinitions(md2.Reader, Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(12, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff2.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(9) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000009""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x79"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""20"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0xdc"" hidden=""true"" document=""1"" /> <entry offset=""0xf6"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0xfe"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10c""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod token=""0x6000004"" /> <await yield=""0x37"" resume=""0x55"" token=""0x6000009"" /> <await yield=""0x97"" resume=""0xb3"" token=""0x6000009"" /> </asyncInfo> </method> </methods> </symbols>"); // Note that the new awaiters are allocated slots <>u__4, <>u__5. diff2.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 268 (0x10c) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<bool> V_2, C.<F>d__3 V_3, System.Runtime.CompilerServices.TaskAwaiter<C> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__3.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_0055 IL_0014: br IL_00b3 IL_0019: nop IL_001a: call ""System.Threading.Tasks.Task<bool> C.A1()"" IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_0024: stloc.2 IL_0025: ldloca.s V_2 IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_002c: brtrue.s IL_0071 IL_002e: ldarg.0 IL_002f: ldc.i4.0 IL_0030: dup IL_0031: stloc.0 IL_0032: stfld ""int C.<F>d__3.<>1__state"" IL_0037: ldarg.0 IL_0038: ldloc.2 IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4"" IL_003e: ldarg.0 IL_003f: stloc.3 IL_0040: ldarg.0 IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0046: ldloca.s V_2 IL_0048: ldloca.s V_3 IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<F>d__3)"" IL_004f: nop IL_0050: leave IL_010b IL_0055: ldarg.0 IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4"" IL_005b: stloc.2 IL_005c: ldarg.0 IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4"" IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_0068: ldarg.0 IL_0069: ldc.i4.m1 IL_006a: dup IL_006b: stloc.0 IL_006c: stfld ""int C.<F>d__3.<>1__state"" IL_0071: ldloca.s V_2 IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_0078: pop IL_0079: call ""System.Threading.Tasks.Task<C> C.A3()"" IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()"" IL_0083: stloc.s V_4 IL_0085: ldloca.s V_4 IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get"" IL_008c: brtrue.s IL_00d0 IL_008e: ldarg.0 IL_008f: ldc.i4.1 IL_0090: dup IL_0091: stloc.0 IL_0092: stfld ""int C.<F>d__3.<>1__state"" IL_0097: ldarg.0 IL_0098: ldloc.s V_4 IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_009f: ldarg.0 IL_00a0: stloc.3 IL_00a1: ldarg.0 IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00a7: ldloca.s V_4 IL_00a9: ldloca.s V_3 IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)"" IL_00b0: nop IL_00b1: leave.s IL_010b IL_00b3: ldarg.0 IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_00b9: stloc.s V_4 IL_00bb: ldarg.0 IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3"" IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>"" IL_00c7: ldarg.0 IL_00c8: ldc.i4.m1 IL_00c9: dup IL_00ca: stloc.0 IL_00cb: stfld ""int C.<F>d__3.<>1__state"" IL_00d0: ldloca.s V_4 IL_00d2: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()"" IL_00d7: pop IL_00d8: ldc.i4.1 IL_00d9: stloc.1 IL_00da: leave.s IL_00f6 } catch System.Exception { IL_00dc: stloc.s V_5 IL_00de: ldarg.0 IL_00df: ldc.i4.s -2 IL_00e1: stfld ""int C.<F>d__3.<>1__state"" IL_00e6: ldarg.0 IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_00ec: ldloc.s V_5 IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00f3: nop IL_00f4: leave.s IL_010b } IL_00f6: ldarg.0 IL_00f7: ldc.i4.s -2 IL_00f9: stfld ""int C.<F>d__3.<>1__state"" IL_00fe: ldarg.0 IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder"" IL_0104: ldloc.1 IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_010a: nop IL_010b: ret }"); // 2 field defs added - G and H awaiters & 4 methods updated: G, H kickoff and MoveNext CheckEncLogDefinitions(md3.Reader, Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(13, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(14, TableIndex.Field, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); diff3.VerifyPdb(new[] { MetadataTokens.MethodDefinitionHandle(15) }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x600000f""> <customDebugInfo> <forward token=""0x600000c"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""24"" startColumn=""5"" endLine=""24"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""20"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""18"" document=""1"" /> <entry offset=""0x6f"" hidden=""true"" document=""1"" /> <entry offset=""0x89"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" /> <entry offset=""0x91"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <kickoffMethod token=""0x6000006"" /> <await yield=""0x2c"" resume=""0x47"" token=""0x600000f"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void SynthesizedMembersMerging() { var source0 = @" using System.Collections.Generic; public class C { }"; var source1 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 2; } }"; var source2 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 3; } }"; var source3 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 3; } public static void G() { System.Console.WriteLine(1); } }"; var source4 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; yield return 3; } public static void G() { System.Console.WriteLine(1); } public static IEnumerable<int> H() { yield return 1; } }"; // Rude edit but the compiler should handle it. var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var h4 = compilation4.GetMember<MethodSymbol>("C.H"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); diff1.VerifySynthesizedMembers( "C: {<F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g3))); diff3.VerifySynthesizedMembers( "C: {<F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, h4))); diff4.VerifySynthesizedMembers( "C: {<H>d__2#4, <F>d__0#1}", "C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "C.<H>d__2#4: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); } [Fact] public void UniqueSynthesizedNames() { var source0 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F() { yield return 1; } }"; var source1 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F(int a) { yield return 2; } public static IEnumerable<int> F() { yield return 1; } }"; var source2 = @" using System.Collections.Generic; public class C { public static IEnumerable<int> F(int a) { yield return 2; } public static IEnumerable<int> F(byte a) { yield return 3; } public static IEnumerable<int> F() { yield return 1; } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<F>d__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<F>d__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<F>d__1#2"); } [Fact] public void UpdateAsyncLambda() { var source0 = MarkedSource( @"using System; using System.Threading.Tasks; class C { static void F() { Func<Task> <N:0>g1 = <N:1>async () => { await A1(); await A2(); }</N:1></N:0>; } static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; }"); var source1 = MarkedSource( @"using System; using System.Threading.Tasks; class C { static int G() => 1; static void F() { Func<Task> <N:0>g1 = <N:1>async () => { await A2(); await A1(); }</N:1></N:0>; } static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; }"); var source2 = MarkedSource( @"using System; using System.Threading.Tasks; class C { static int G() => 1; static void F() { Func<Task> <N:0>g1 = <N:1>async () => { await A1(); await A2(); }</N:1></N:0>; } static Task<bool> A1() => null; static Task<int> A2() => null; static Task<double> A3() => null; }"); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0, symbolValidator: module => { Assert.Equal(new[] { "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "<>4__this: C.<>c", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>" }, module.GetFieldNamesAndTypes("C.<>c.<<F>b__0_0>d")); }); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation: diff1.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d", "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "<>4__this: C.<>c", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); // note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation: diff2.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d", "<>1__state: int", "<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "<>4__this: C.<>c", "<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>", "<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"); } [Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")] public void HoistedAnonymousTypes1() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = 1 }</N:0>; yield return 1; Console.WriteLine(x.A + 1); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = 1 }</N:0>; yield return 1; Console.WriteLine(x.A + 2); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = 1 }</N:0>; yield return 1; Console.WriteLine(x.A + 3); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL = @" { // Code size 88 (0x58) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003c IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0027: stfld ""<anonymous type: int A> C.<F>d__0.<x>5__1"" IL_002c: ldarg.0 IL_002d: ldc.i4.1 IL_002e: stfld ""int C.<F>d__0.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__0.<>1__state"" IL_003a: ldc.i4.1 IL_003b: ret IL_003c: ldarg.0 IL_003d: ldc.i4.m1 IL_003e: stfld ""int C.<F>d__0.<>1__state"" IL_0043: ldarg.0 IL_0044: ldfld ""<anonymous type: int A> C.<F>d__0.<x>5__1"" IL_0049: callvirt ""int <>f__AnonymousType0<int>.A.get"" IL_004e: ldc.i4.<<VALUE>> IL_004f: add IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: nop IL_0056: ldc.i4.0 IL_0057: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0"); diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.UpdatedMethods, "MoveNext"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<F>d__0"); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3")); } [Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")] public void HoistedAnonymousTypes_Nested() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>; yield return 1; Console.WriteLine(x[0].A.B + 1); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>; yield return 1; Console.WriteLine(x[0].A.B + 2); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>; yield return 1; Console.WriteLine(x[0].A.B + 3); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL = @" { // Code size 109 (0x6d) .maxstack 5 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_004a IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldc.i4.1 IL_0022: newarr ""<>f__AnonymousType0<<anonymous type: int B>>"" IL_0027: dup IL_0028: ldc.i4.0 IL_0029: ldc.i4.1 IL_002a: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_002f: newobj ""<>f__AnonymousType0<<anonymous type: int B>>..ctor(<anonymous type: int B>)"" IL_0034: stelem.ref IL_0035: stfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1"" IL_003a: ldarg.0 IL_003b: ldc.i4.1 IL_003c: stfld ""int C.<F>d__0.<>2__current"" IL_0041: ldarg.0 IL_0042: ldc.i4.1 IL_0043: stfld ""int C.<F>d__0.<>1__state"" IL_0048: ldc.i4.1 IL_0049: ret IL_004a: ldarg.0 IL_004b: ldc.i4.m1 IL_004c: stfld ""int C.<F>d__0.<>1__state"" IL_0051: ldarg.0 IL_0052: ldfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1"" IL_0057: ldc.i4.0 IL_0058: ldelem.ref IL_0059: callvirt ""<anonymous type: int B> <>f__AnonymousType0<<anonymous type: int B>>.A.get"" IL_005e: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_0063: ldc.i4.<<VALUE>> IL_0064: add IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: ldc.i4.0 IL_006c: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3")); } [Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")] public void HoistedGenericTypes() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class Z<T1> { public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); } } class C { public IEnumerable<int> F() { var <N:0>x = new Z<double>.S<int>()</N:0>; yield return 1; Console.WriteLine(x.a + x.b + 1); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class Z<T1> { public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); } } class C { public IEnumerable<int> F() { var <N:0>x = new Z<double>.S<int>()</N:0>; yield return 1; Console.WriteLine(x.a + x.b + 2); } } "); var source2 = MarkedSource(@" using System; using System.Collections.Generic; class Z<T1> { public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); } } class C { public IEnumerable<int> F() { var <N:0>x = new Z<double>.S<int>()</N:0>; yield return 1; Console.WriteLine(x.a + x.b + 3); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL = @" { // Code size 108 (0x6c) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003b IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: newobj ""Z<double>.S<int>..ctor()"" IL_0026: stfld ""Z<double>.S<int> C.<F>d__0.<x>5__1"" IL_002b: ldarg.0 IL_002c: ldc.i4.1 IL_002d: stfld ""int C.<F>d__0.<>2__current"" IL_0032: ldarg.0 IL_0033: ldc.i4.1 IL_0034: stfld ""int C.<F>d__0.<>1__state"" IL_0039: ldc.i4.1 IL_003a: ret IL_003b: ldarg.0 IL_003c: ldc.i4.m1 IL_003d: stfld ""int C.<F>d__0.<>1__state"" IL_0042: ldarg.0 IL_0043: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1"" IL_0048: ldfld ""double Z<double>.S<int>.a"" IL_004d: ldarg.0 IL_004e: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1"" IL_0053: ldfld ""int Z<double>.S<int>.b"" IL_0058: conv.r8 IL_0059: add IL_005a: ldc.r8 <<VALUE>> IL_0063: add IL_0064: call ""void System.Console.WriteLine(double)"" IL_0069: nop IL_006a: ldc.i4.0 IL_006b: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3")); } [Fact] public void HoistedAnonymousTypes_Dynamic() { var template = @" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; yield return 1; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 87 (0x57) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003d IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldnull IL_0022: ldc.i4.1 IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_002d: ldarg.0 IL_002e: ldc.i4.1 IL_002f: stfld ""int C.<F>d__0.<>2__current"" IL_0034: ldarg.0 IL_0035: ldc.i4.1 IL_0036: stfld ""int C.<F>d__0.<>1__state"" IL_003b: ldc.i4.1 IL_003c: ret IL_003d: ldarg.0 IL_003e: ldc.i4.m1 IL_003f: stfld ""int C.<F>d__0.<>1__state"" IL_0044: ldarg.0 IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_004f: call ""void System.Console.WriteLine(int)"" IL_0054: nop IL_0055: ldc.i4.0 IL_0056: ret }"; v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var baselineIL = @" { // Code size 89 (0x59) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_003d IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldnull IL_0022: ldc.i4.1 IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_002d: ldarg.0 IL_002e: ldc.i4.1 IL_002f: stfld ""int C.<F>d__0.<>2__current"" IL_0034: ldarg.0 IL_0035: ldc.i4.1 IL_0036: stfld ""int C.<F>d__0.<>1__state"" IL_003b: ldc.i4.1 IL_003c: ret IL_003d: ldarg.0 IL_003e: ldc.i4.m1 IL_003f: stfld ""int C.<F>d__0.<>1__state"" IL_0044: ldarg.0 IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1"" IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_004f: ldc.i4.<<VALUE>> IL_0050: add IL_0051: call ""void System.Console.WriteLine(int)"" IL_0056: nop IL_0057: ldc.i4.0 IL_0058: ret }"; diff1.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<F>d__0}", "C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2")); } [Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")] public void HoistedAnonymousTypes_Delete() { var source0 = MarkedSource(@" using System.Linq; using System.Threading.Tasks; class C { static async Task<int> F() { var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>; return <N:2>await Task.FromResult(1)</N:2>; } } "); var source1 = MarkedSource(@" using System.Linq; using System.Threading.Tasks; class C { static async Task<int> F() { var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>; var y = x.First(); return <N:2>await Task.FromResult(1)</N:2>; } } "); var source2 = source0; var source3 = source1; var source4 = source0; var source5 = source1; var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var compilation3 = compilation0.WithSource(source3.Tree); var compilation4 = compilation0.WithSource(source4.Tree); var compilation5 = compilation0.WithSource(source5.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var f3 = compilation3.GetMember<MethodSymbol>("C.F"); var f4 = compilation4.GetMember<MethodSymbol>("C.F"); var f5 = compilation5.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // y is added var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__3, <>s__2, <>u__1, MoveNext, SetStateMachine}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is removed var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); // Synthesized members collection still includes y field since members are only added to it and never deleted. // The corresponding CLR field is also present. diff2.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is added and a new slot index is allocated for it var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__4, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is removed var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f3, f4, GetSyntaxMapFromMarkers(source3, source4), preserveLocalVariables: true))); diff4.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); // y is added var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f4, f5, GetSyntaxMapFromMarkers(source4, source5), preserveLocalVariables: true))); diff5.VerifySynthesizedMembers( "C: {<>c, <F>d__0}", "C.<>c: {<>9__0_0, <F>b__0_0}", "C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__5, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); } [Fact] public void HoistedAnonymousTypes_Dynamic2() { var source0 = MarkedSource(@" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { args = Iterator().ToArray(); } private static IEnumerable<string> Iterator() { string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>; var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>; for (int <N:18>i = 0</N:18>; i < 10; i++) { var <N:6>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4> <N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>; var <N:8>linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, <N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>; while (linked != null) { <N:9>yield return linked.Head</N:9>; linked = linked.Tail; } var <N:14>newArgs = from a in result <N:10>let value = a.Value</N:10> <N:11>let length = a.Length</N:11> <N:12>where value.Length == length</N:12> <N:13>select value + value</N:13></N:14>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var source1 = MarkedSource(@" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { args = Iterator().ToArray(); } private static IEnumerable<string> Iterator() { string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>; var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>; for (int <N:18>i = 0</N:18>; i < 10; i++) { var <N:6>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4> <N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>; var <N:8>linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, <N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>; var <N:17>temp = list</N:17>; while (temp != null) { <N:9>yield return temp.Head</N:9>; temp = temp.Tail; } var <N:14>newArgs = from a in result <N:10>let value = a.Value</N:10> <N:11>let length = a.Length</N:11> <N:12>where value.Length == length</N:12> <N:13>select value + value</N:13></N:14>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var source2 = MarkedSource(@" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { args = Iterator().ToArray(); } private static IEnumerable<string> Iterator() { string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>; var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>; for (int <N:18>i = 0</N:18>; i < 10; i++) { var <N:6>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4> <N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>; var <N:8>linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, <N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>; var <N:17>temp = list</N:17>; while (temp != null) { <N:9>yield return temp.Head.ToString()</N:9>; temp = temp.Tail; } var <N:14>newArgs = from a in result <N:10>let value = a.Value</N:10> <N:11>let length = a.Length</N:11> <N:12>where value.Length == length</N:12> <N:13>select value + value</N:13></N:14>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("Program.Iterator"); var f1 = compilation1.GetMember<MethodSymbol>("Program.Iterator"); var f2 = compilation2.GetMember<MethodSymbol>("Program.Iterator"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 798 (0x31e) .maxstack 5 .locals init (int V_0, bool V_1, int V_2, bool V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_001b IL_0014: br IL_019b IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldarg.0 IL_001c: ldc.i4.m1 IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_0022: nop IL_0023: ldarg.0 IL_0024: ldc.i4.4 IL_0025: newarr ""string"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldstr ""a"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldstr ""bB"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldstr ""Cc"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldstr ""DD"" IL_0049: stelem.ref IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_004f: ldarg.0 IL_0050: ldnull IL_0051: ldnull IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_005c: ldarg.0 IL_005d: ldc.i4.0 IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0063: br IL_0305 IL_0068: nop IL_0069: ldarg.0 IL_006a: ldarg.0 IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_0075: dup IL_0076: brtrue.s IL_008f IL_0078: pop IL_0079: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)"" IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_0089: dup IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_0099: dup IL_009a: brtrue.s IL_00b3 IL_009c: pop IL_009d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_00ad: dup IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00bd: dup IL_00be: brtrue.s IL_00d7 IL_00c0: pop IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_00d1: dup IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00e1: dup IL_00e2: brtrue.s IL_00fb IL_00e4: pop IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)"" IL_00f5: dup IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)"" IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_0105: dup IL_0106: brtrue.s IL_011f IL_0108: pop IL_0109: ldsfld ""Program.<>c Program.<>c.<>9"" IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)"" IL_0119: dup IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)"" IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0129: dup IL_012a: brtrue.s IL_0143 IL_012c: pop IL_012d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_013d: dup IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_014d: ldarg.0 IL_014e: ldarg.0 IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_0154: ldnull IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_015a: dup IL_015b: brtrue.s IL_0174 IL_015d: pop IL_015e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)"" IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)"" IL_016e: dup IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)"" IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_017e: br.s IL_01f5 IL_0180: nop IL_0181: ldarg.0 IL_0182: ldarg.0 IL_0183: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_0188: callvirt ""string <>f__AnonymousType0<string, dynamic>.Head.get"" IL_018d: stfld ""string Program.<Iterator>d__1.<>2__current"" IL_0192: ldarg.0 IL_0193: ldc.i4.1 IL_0194: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_0199: ldc.i4.1 IL_019a: ret IL_019b: ldarg.0 IL_019c: ldc.i4.m1 IL_019d: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_01a2: ldarg.0 IL_01a3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01a8: brfalse.s IL_01ac IL_01aa: br.s IL_01d0 IL_01ac: ldc.i4.0 IL_01ad: ldtoken ""<>f__AnonymousType0<string, dynamic>"" IL_01b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b7: ldtoken ""Program"" IL_01bc: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01c1: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_01c6: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01cb: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01d0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01d5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Target"" IL_01da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0"" IL_01df: ldarg.0 IL_01e0: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_01e5: callvirt ""dynamic <>f__AnonymousType0<string, dynamic>.Tail.get"" IL_01ea: callvirt ""<anonymous type: string Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01ef: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_01f4: nop IL_01f5: ldarg.0 IL_01f6: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_01fb: ldnull IL_01fc: cgt.un IL_01fe: stloc.1 IL_01ff: ldloc.1 IL_0200: brtrue IL_0180 IL_0205: ldarg.0 IL_0206: ldarg.0 IL_0207: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_020c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_0211: dup IL_0212: brtrue.s IL_022b IL_0214: pop IL_0215: ldsfld ""Program.<>c Program.<>c.<>9"" IL_021a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)"" IL_0220: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)"" IL_0225: dup IL_0226: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_022b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)"" IL_0230: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_0235: dup IL_0236: brtrue.s IL_024f IL_0238: pop IL_0239: ldsfld ""Program.<>c Program.<>c.<>9"" IL_023e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)"" IL_0244: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)"" IL_0249: dup IL_024a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_024f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)"" IL_0254: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_0259: dup IL_025a: brtrue.s IL_0273 IL_025c: pop IL_025d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0262: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_0268: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)"" IL_026d: dup IL_026e: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_0273: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)"" IL_0278: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_027d: dup IL_027e: brtrue.s IL_0297 IL_0280: pop IL_0281: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0286: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_028c: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)"" IL_0291: dup IL_0292: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_0297: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)"" IL_029c: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02a1: ldarg.0 IL_02a2: ldarg.0 IL_02a3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_02a8: ldarg.0 IL_02a9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02ae: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)"" IL_02b3: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)"" IL_02b8: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_02bd: ldarg.0 IL_02be: ldarg.0 IL_02bf: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_02c4: box ""int"" IL_02c9: ldarg.0 IL_02ca: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_02cf: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_02d4: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_02d9: call ""void System.Diagnostics.Debugger.Break()"" IL_02de: nop IL_02df: nop IL_02e0: ldarg.0 IL_02e1: ldnull IL_02e2: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_02e7: ldarg.0 IL_02e8: ldnull IL_02e9: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_02ee: ldarg.0 IL_02ef: ldnull IL_02f0: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02f5: ldarg.0 IL_02f6: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_02fb: stloc.2 IL_02fc: ldarg.0 IL_02fd: ldloc.2 IL_02fe: ldc.i4.1 IL_02ff: add IL_0300: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0305: ldarg.0 IL_0306: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_030b: ldc.i4.s 10 IL_030d: clt IL_030f: stloc.3 IL_0310: ldloc.3 IL_0311: brtrue IL_0068 IL_0316: call ""void System.Diagnostics.Debugger.Break()"" IL_031b: nop IL_031c: ldc.i4.0 IL_031d: ret }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program.<>o__1#1: {<>p__0, <>p__1}", "Program: {<>o__1#1, <>c, <Iterator>d__1}", "Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}", "Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @" { // Code size 885 (0x375) .maxstack 5 .locals init (int V_0, bool V_1, int V_2, bool V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_001b IL_0014: br IL_01eb IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldarg.0 IL_001c: ldc.i4.m1 IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_0022: nop IL_0023: ldarg.0 IL_0024: ldc.i4.4 IL_0025: newarr ""string"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldstr ""a"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldstr ""bB"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldstr ""Cc"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldstr ""DD"" IL_0049: stelem.ref IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_004f: ldarg.0 IL_0050: ldnull IL_0051: ldnull IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_005c: ldarg.0 IL_005d: ldc.i4.0 IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0063: br IL_035c IL_0068: nop IL_0069: ldarg.0 IL_006a: ldarg.0 IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_0075: dup IL_0076: brtrue.s IL_008f IL_0078: pop IL_0079: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)"" IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_0089: dup IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0"" IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_0099: dup IL_009a: brtrue.s IL_00b3 IL_009c: pop IL_009d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_00ad: dup IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1"" IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00bd: dup IL_00be: brtrue.s IL_00d7 IL_00c0: pop IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_00d1: dup IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2"" IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00e1: dup IL_00e2: brtrue.s IL_00fb IL_00e4: pop IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9"" IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)"" IL_00f5: dup IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3"" IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)"" IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_0105: dup IL_0106: brtrue.s IL_011f IL_0108: pop IL_0109: ldsfld ""Program.<>c Program.<>c.<>9"" IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)"" IL_0119: dup IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4"" IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)"" IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0129: dup IL_012a: brtrue.s IL_0143 IL_012c: pop IL_012d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_013d: dup IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5"" IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_014d: ldarg.0 IL_014e: ldarg.0 IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_0154: ldnull IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_015a: dup IL_015b: brtrue.s IL_0174 IL_015d: pop IL_015e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)"" IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)"" IL_016e: dup IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6"" IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)"" IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_017e: ldarg.0 IL_017f: ldarg.0 IL_0180: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_0185: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_018a: br IL_0245 IL_018f: nop IL_0190: ldarg.0 IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_0196: brfalse.s IL_019a IL_0198: br.s IL_01be IL_019a: ldc.i4.0 IL_019b: ldtoken ""string"" IL_01a0: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01a5: ldtoken ""Program"" IL_01aa: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01af: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_01b4: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01b9: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_01be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_01c3: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Target"" IL_01c8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0"" IL_01cd: ldarg.0 IL_01ce: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_01d3: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Head.get"" IL_01d8: callvirt ""string System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01dd: stfld ""string Program.<Iterator>d__1.<>2__current"" IL_01e2: ldarg.0 IL_01e3: ldc.i4.1 IL_01e4: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_01e9: ldc.i4.1 IL_01ea: ret IL_01eb: ldarg.0 IL_01ec: ldc.i4.m1 IL_01ed: stfld ""int Program.<Iterator>d__1.<>1__state"" IL_01f2: ldarg.0 IL_01f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_01f8: brfalse.s IL_01fc IL_01fa: br.s IL_0220 IL_01fc: ldc.i4.0 IL_01fd: ldtoken ""<>f__AnonymousType0<dynamic, dynamic>"" IL_0202: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0207: ldtoken ""Program"" IL_020c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0211: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0216: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_021b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_0220: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_0225: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Target"" IL_022a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1"" IL_022f: ldarg.0 IL_0230: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_0235: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Tail.get"" IL_023a: callvirt ""<anonymous type: dynamic Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_023f: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_0244: nop IL_0245: ldarg.0 IL_0246: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_024b: ldnull IL_024c: cgt.un IL_024e: stloc.1 IL_024f: ldloc.1 IL_0250: brtrue IL_018f IL_0255: ldarg.0 IL_0256: ldarg.0 IL_0257: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_025c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_0261: dup IL_0262: brtrue.s IL_027b IL_0264: pop IL_0265: ldsfld ""Program.<>c Program.<>c.<>9"" IL_026a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)"" IL_0270: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)"" IL_0275: dup IL_0276: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7"" IL_027b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)"" IL_0280: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_0285: dup IL_0286: brtrue.s IL_029f IL_0288: pop IL_0289: ldsfld ""Program.<>c Program.<>c.<>9"" IL_028e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)"" IL_0294: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)"" IL_0299: dup IL_029a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8"" IL_029f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)"" IL_02a4: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_02a9: dup IL_02aa: brtrue.s IL_02c3 IL_02ac: pop IL_02ad: ldsfld ""Program.<>c Program.<>c.<>9"" IL_02b2: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_02b8: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)"" IL_02bd: dup IL_02be: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9"" IL_02c3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)"" IL_02c8: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_02cd: dup IL_02ce: brtrue.s IL_02e7 IL_02d0: pop IL_02d1: ldsfld ""Program.<>c Program.<>c.<>9"" IL_02d6: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)"" IL_02dc: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)"" IL_02e1: dup IL_02e2: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10"" IL_02e7: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)"" IL_02ec: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02f1: ldarg.0 IL_02f2: ldarg.0 IL_02f3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_02f8: ldarg.0 IL_02f9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_02fe: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)"" IL_0303: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)"" IL_0308: stfld ""string[] Program.<Iterator>d__1.<args>5__1"" IL_030d: ldarg.0 IL_030e: ldarg.0 IL_030f: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0314: box ""int"" IL_0319: ldarg.0 IL_031a: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_031f: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)"" IL_0324: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2"" IL_0329: call ""void System.Diagnostics.Debugger.Break()"" IL_032e: nop IL_032f: nop IL_0330: ldarg.0 IL_0331: ldnull IL_0332: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4"" IL_0337: ldarg.0 IL_0338: ldnull IL_0339: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5"" IL_033e: ldarg.0 IL_033f: ldnull IL_0340: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7"" IL_0345: ldarg.0 IL_0346: ldnull IL_0347: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6"" IL_034c: ldarg.0 IL_034d: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0352: stloc.2 IL_0353: ldarg.0 IL_0354: ldloc.2 IL_0355: ldc.i4.1 IL_0356: add IL_0357: stfld ""int Program.<Iterator>d__1.<i>5__3"" IL_035c: ldarg.0 IL_035d: ldfld ""int Program.<Iterator>d__1.<i>5__3"" IL_0362: ldc.i4.s 10 IL_0364: clt IL_0366: stloc.3 IL_0367: ldloc.3 IL_0368: brtrue IL_0068 IL_036d: call ""void System.Diagnostics.Debugger.Break()"" IL_0372: nop IL_0373: ldc.i4.0 IL_0374: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>o__1#1: {<>p__0, <>p__1}", "Program.<>o__1#2: {<>p__0, <>p__1, <>p__2}", "Program: {<>o__1#2, <>c, <Iterator>d__1, <>o__1#1}", "Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}", "Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}", "<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); } [Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")] public void MissingIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (7,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(7, 29)); } [Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")] public void BadIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { } } class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // the ctor is missing a parameter Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (12,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing. // public IEnumerable<int> F() Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(12, 29)); } [Fact] public void AddedIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var ism1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.IteratorStateMachineAttribute"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, ism1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // We conclude the original method wasn't a state machine. // The IDE however reports a Rude Edit in that case. diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void SourceIteratorStateMachineAttribute() { var source0 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>yield return 0;</N:1> Console.WriteLine(a); } } "); var source1 = MarkedSource(@" using System; using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return 1;</N:1> Console.WriteLine(a); } } "); var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")] public void MissingAsyncStateMachineAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 0</N:0>; <N:1>await new Task();</N:1> return a; } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>await new Task();</N:1> return a; } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain AsyncStateMachineAttribute, IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28)); } [Fact] public void AddedAsyncStateMachineAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 0</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; namespace System.Runtime.CompilerServices { public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } } } class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); // older versions of mscorlib don't contain IteratorStateMachineAttribute Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var asm1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.AsyncStateMachineAttribute"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, asm1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void SourceAsyncStateMachineAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; namespace System.Runtime.CompilerServices { public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } } } class C { public async Task<int> F() { int <N:0>a = 0</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; namespace System.Runtime.CompilerServices { public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } } } class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>await new Task<int>();</N:1> return a; } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact, WorkItem(10190, "https://github.com/dotnet/roslyn/issues/10190")] public void NonAsyncToAsync() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public Task<int> F() { int <N:0>a = 0</N:0>; <N:1>return Task.FromResult(a);</N:1> } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 1</N:0>; <N:1>return await Task.FromResult(a);</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void NonAsyncToAsync_MissingAttribute() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public Task<int> F() { int <N:0>a = 0</N:0>; a++; <N:1>return new Task<int>();</N:1> } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public async Task<int> F() { int <N:0>a = 1</N:0>; a++; <N:1>return await new Task<int>();</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Fails); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28)); } [Fact] public void NonIteratorToIterator_MissingAttribute() { var source0 = MarkedSource(@" using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>return new int[] { a };</N:1> } } "); var source1 = MarkedSource(@" using System.Collections.Generic; class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return a;</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing. Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(6, 29)); } [Fact] public void NonIteratorToIterator_SourceAttribute() { var source0 = MarkedSource(@" using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 0</N:0>; <N:1>return new int[] { a };</N:1> } } "); var source1 = MarkedSource(@" using System.Collections.Generic; namespace System.Runtime.CompilerServices { public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } } } class C { public IEnumerable<int> F() { int <N:0>a = 1</N:0>; <N:1>yield return a;</N:1> } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void NonAsyncToAsyncLambda() { var source0 = MarkedSource(@" using System.Threading.Tasks; class C { public object F() { return new System.Func<Task<int>>(<N:2>() => <N:3>{ int <N:0>a = 0</N:0>; <N:1>return Task.FromResult(a);</N:1> }</N:3></N:2>); } } "); var source1 = MarkedSource(@" using System.Threading.Tasks; class C { public object F() { return new System.Func<Task<int>>(<N:2>async () => <N:3>{ int <N:0>a = 0</N:0>; <N:1>return await Task.FromResult(a);</N:1> }</N:3></N:2>); } } "); var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <F>b__0_0, <<F>b__0_0>d}", "C.<>c.<<F>b__0_0>d: {<>1__state, <>t__builder, <>4__this, <a>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine}"); } [Fact] public void AsyncMethodWithNullableParameterAddingNullCheck() { var source0 = MarkedSource(@" using System; using System.Threading.Tasks; #nullable enable class C { static T id<T>(T t) => t; static Task<T> G<T>(Func<T> f) => Task.FromResult(f()); static T H<T>(Func<T> f) => f(); public async void F(string? x) <N:4>{</N:4> var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>; var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>; } } ", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source1 = MarkedSource(@" using System; using System.Threading.Tasks; #nullable enable class C { static T id<T>(T t) => t; static Task<T> G<T>(Func<T> f) => Task.FromResult(f()); static T H<T>(Func<T> f) => f(); public async void F(string? x) <N:4>{</N:4> if (x is null) throw new Exception(); var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>; var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>; } } ", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor)); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, y, <F>b__1, <F>b__0}", "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "Microsoft: {CodeAnalysis}", "System.Runtime: {CompilerServices, CompilerServices}", "C: {<>c__DisplayClass3_0, <F>d__3}", "<global namespace>: {Microsoft, System, System}", "System: {Runtime, Runtime}", "C.<F>d__3: {<>1__state, <>t__builder, x, <>4__this, <>8__4, <z>5__2, <>s__5, <>u__1, MoveNext, SetStateMachine}"); diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__1()", @" { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""string C.<>c__DisplayClass3_0.x"" IL_0006: call ""string C.id<string>(string)"" IL_000b: newobj ""<>f__AnonymousType0<string>..ctor(string)"" IL_0010: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__0()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass3_0.y"" IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get"" IL_000b: ret } "); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Dependencies/Collections/Internal/SegmentedArraySegment`1.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.Collections.Internal { internal readonly struct SegmentedArraySegment<T> { public SegmentedArray<T> Array { get; } public int Start { get; } public int Length { get; } public SegmentedArraySegment(SegmentedArray<T> array, int start, int length) { Array = array; Start = start; Length = length; } public ref T this[int index] { get { if ((uint)index >= (uint)Length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Array[index + Start]; } } public SegmentedArraySegment<T> Slice(int start) { if ((uint)start >= (uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, Length - start); } public SegmentedArraySegment<T> Slice(int start, int length) { // Since start and length are both 32-bit, their sum can be computed across a 64-bit domain // without loss of fidelity. The cast to uint before the cast to ulong ensures that the // extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result // of this is that if either input is negative or if the input sum overflows past Int32.MaxValue, // that information is captured correctly in the comparison against the backing _length field. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, length); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Collections.Internal { internal readonly struct SegmentedArraySegment<T> { public SegmentedArray<T> Array { get; } public int Start { get; } public int Length { get; } public SegmentedArraySegment(SegmentedArray<T> array, int start, int length) { Array = array; Start = start; Length = length; } public ref T this[int index] { get { if ((uint)index >= (uint)Length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Array[index + Start]; } } public SegmentedArraySegment<T> Slice(int start) { if ((uint)start >= (uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, Length - start); } public SegmentedArraySegment<T> Slice(int start, int length) { // Since start and length are both 32-bit, their sum can be computed across a 64-bit domain // without loss of fidelity. The cast to uint before the cast to ulong ensures that the // extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result // of this is that if either input is negative or if the input sum overflows past Int32.MaxValue, // that information is captured correctly in the comparison against the backing _length field. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, length); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/LiveShare/Impl/Client/Projects/IRemoteProjectInfoProvider.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 System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(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.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/Core/Portable/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { internal abstract partial class AbstractGenerateDefaultConstructorsService<TService> { private class State { public INamedTypeSymbol? ClassType { get; private set; } public ImmutableArray<IMethodSymbol> UnimplementedConstructors { get; private set; } private State() { } public static State? Generate( TService service, SemanticDocument document, TextSpan textSpan, bool forRefactoring, CancellationToken cancellationToken) { var state = new State(); if (!state.TryInitialize(service, document, textSpan, forRefactoring, cancellationToken)) { return null; } return state; } private bool TryInitialize( TService service, SemanticDocument semanticDocument, TextSpan textSpan, bool forRefactoring, CancellationToken cancellationToken) { if (!service.TryInitializeState(semanticDocument, textSpan, cancellationToken, out var classType)) return false; ClassType = classType; var baseType = ClassType.BaseType; if (ClassType.IsStatic || baseType == null || baseType.TypeKind == TypeKind.Error) { return false; } // if this is for the refactoring, then don't offer this if the compiler is reporting an // error here. We'll let the code fix take care of that. // // Similarly if this is for the codefix only offer if we do see that there's an error. var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); var headerFacts = semanticDocument.Document.GetRequiredLanguageService<IHeaderFactsService>(); if (headerFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, fullHeader: true, out _)) { var fixesError = FixesError(classType, baseType); if (forRefactoring == fixesError) return false; } var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var classConstructors = ClassType.InstanceConstructors; var destinationProvider = semanticDocument.Project.Solution.Workspace.Services.GetLanguageServices(ClassType.Language); var isCaseSensitive = syntaxFacts.IsCaseSensitive; UnimplementedConstructors = baseType.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(ClassType) && IsMissing(c, classConstructors, isCaseSensitive)); return UnimplementedConstructors.Length > 0; } private static bool FixesError(INamedTypeSymbol classType, INamedTypeSymbol baseType) { // See if the user didn't supply a constructor, and thus the compiler automatically generated // one for them. If so, also see if there's an accessible no-arg contructor in the base. // If not, then the compiler will error and we want the code-fix to take over solving this problem. if (classType.Constructors.Any(c => c.Parameters.Length == 0 && c.IsImplicitlyDeclared)) { var baseNoArgConstructor = baseType.Constructors.FirstOrDefault(c => c.Parameters.Length == 0); if (baseNoArgConstructor == null || !baseNoArgConstructor.IsAccessibleWithin(classType)) { // this code is in error, but we're the refactoring codepath. Offer nothing // and let the code fix provider handle it instead. return true; } } return false; } private static bool IsMissing( IMethodSymbol constructor, ImmutableArray<IMethodSymbol> classConstructors, bool isCaseSensitive) { var matchingConstructor = classConstructors.FirstOrDefault( c => SignatureComparer.Instance.HaveSameSignature( constructor.Parameters, c.Parameters, compareParameterName: true, isCaseSensitive: isCaseSensitive)); if (matchingConstructor == null) { return true; } // We have a matching constructor in this type. But we'll still offer to create the // constructor if the constructor that we have is implicit. return matchingConstructor.IsImplicitlyDeclared; } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { internal abstract partial class AbstractGenerateDefaultConstructorsService<TService> { private class State { public INamedTypeSymbol? ClassType { get; private set; } public ImmutableArray<IMethodSymbol> UnimplementedConstructors { get; private set; } private State() { } public static State? Generate( TService service, SemanticDocument document, TextSpan textSpan, bool forRefactoring, CancellationToken cancellationToken) { var state = new State(); if (!state.TryInitialize(service, document, textSpan, forRefactoring, cancellationToken)) { return null; } return state; } private bool TryInitialize( TService service, SemanticDocument semanticDocument, TextSpan textSpan, bool forRefactoring, CancellationToken cancellationToken) { if (!service.TryInitializeState(semanticDocument, textSpan, cancellationToken, out var classType)) return false; ClassType = classType; var baseType = ClassType.BaseType; if (ClassType.IsStatic || baseType == null || baseType.TypeKind == TypeKind.Error) { return false; } // if this is for the refactoring, then don't offer this if the compiler is reporting an // error here. We'll let the code fix take care of that. // // Similarly if this is for the codefix only offer if we do see that there's an error. var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); var headerFacts = semanticDocument.Document.GetRequiredLanguageService<IHeaderFactsService>(); if (headerFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, fullHeader: true, out _)) { var fixesError = FixesError(classType, baseType); if (forRefactoring == fixesError) return false; } var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var classConstructors = ClassType.InstanceConstructors; var destinationProvider = semanticDocument.Project.Solution.Workspace.Services.GetLanguageServices(ClassType.Language); var isCaseSensitive = syntaxFacts.IsCaseSensitive; UnimplementedConstructors = baseType.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(ClassType) && IsMissing(c, classConstructors, isCaseSensitive)); return UnimplementedConstructors.Length > 0; } private static bool FixesError(INamedTypeSymbol classType, INamedTypeSymbol baseType) { // See if the user didn't supply a constructor, and thus the compiler automatically generated // one for them. If so, also see if there's an accessible no-arg contructor in the base. // If not, then the compiler will error and we want the code-fix to take over solving this problem. if (classType.Constructors.Any(c => c.Parameters.Length == 0 && c.IsImplicitlyDeclared)) { var baseNoArgConstructor = baseType.Constructors.FirstOrDefault(c => c.Parameters.Length == 0); if (baseNoArgConstructor == null || !baseNoArgConstructor.IsAccessibleWithin(classType)) { // this code is in error, but we're the refactoring codepath. Offer nothing // and let the code fix provider handle it instead. return true; } } return false; } private static bool IsMissing( IMethodSymbol constructor, ImmutableArray<IMethodSymbol> classConstructors, bool isCaseSensitive) { var matchingConstructor = classConstructors.FirstOrDefault( c => SignatureComparer.Instance.HaveSameSignature( constructor.Parameters, c.Parameters, compareParameterName: true, isCaseSensitive: isCaseSensitive)); if (matchingConstructor == null) { return true; } // We have a matching constructor in this type. But we'll still offer to create the // constructor if the constructor that we have is implicit. return matchingConstructor.IsImplicitlyDeclared; } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/CSharpTest2/Recommendations/ULongKeywordRecommenderTests.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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ULongKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [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(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncAsType() => await VerifyKeywordAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(ulong x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
// Licensed to the .NET Foundation under one or more 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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ULongKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [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(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncAsType() => await VerifyKeywordAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(ulong x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/Portable/Syntax/SyntaxListBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal class SyntaxListBuilder { private ArrayElement<GreenNode?>[] _nodes; public int Count { get; private set; } public SyntaxListBuilder(int size) { _nodes = new ArrayElement<GreenNode?>[size]; } public void Clear() { this.Count = 0; } public void Add(SyntaxNode item) { AddInternal(item.Green); } internal void AddInternal(GreenNode item) { if (item == null) { throw new ArgumentNullException(); } if (Count >= _nodes.Length) { this.Grow(Count == 0 ? 8 : _nodes.Length * 2); } _nodes[Count++].Value = item; } public void AddRange(SyntaxNode[] items) { this.AddRange(items, 0, items.Length); } public void AddRange(SyntaxNode[] items, int offset, int length) { if (Count + length > _nodes.Length) { this.Grow(Count + length); } for (int i = offset, j = Count; i < offset + length; ++i, ++j) { _nodes[j].Value = items[i].Green; } int start = Count; Count += length; Validate(start, Count); } [Conditional("DEBUG")] private void Validate(int start, int end) { for (int i = start; i < end; i++) { if (_nodes[i].Value == null) { throw new ArgumentException("Cannot add a null node."); } } } public void AddRange(SyntaxList<SyntaxNode> list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxList<SyntaxNode> list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list.ItemInternal(i)!.Green; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange<TNode>(SyntaxList<TNode> list) where TNode : SyntaxNode { this.AddRange(list, 0, list.Count); } public void AddRange<TNode>(SyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { this.AddRange(new SyntaxList<SyntaxNode>(list.Node), offset, count); } public void AddRange(SyntaxNodeOrTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxNodeOrTokenList list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list[i].UnderlyingNode; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange(SyntaxTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxTokenList list, int offset, int length) { Debug.Assert(list.Node is object); this.AddRange(new SyntaxList<SyntaxNode>(list.Node.CreateRed()), offset, length); } private void Grow(int size) { var tmp = new ArrayElement<GreenNode?>[size]; Array.Copy(_nodes, tmp, _nodes.Length); _nodes = tmp; } public bool Any(int kind) { for (int i = 0; i < Count; i++) { if (_nodes[i].Value!.RawKind == kind) { return true; } } return false; } internal GreenNode? ToListNode() { switch (this.Count) { case 0: return null; case 1: return _nodes[0].Value; case 2: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!); case 3: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!, _nodes[2].Value!); default: var tmp = new ArrayElement<GreenNode>[this.Count]; for (int i = 0; i < this.Count; i++) { tmp[i].Value = _nodes[i].Value!; } return InternalSyntax.SyntaxList.List(tmp); } } public static implicit operator SyntaxList<SyntaxNode>(SyntaxListBuilder builder) { if (builder == null) { return default(SyntaxList<SyntaxNode>); } return builder.ToList(); } internal void RemoveLast() { this.Count -= 1; this._nodes[Count] = default; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal class SyntaxListBuilder { private ArrayElement<GreenNode?>[] _nodes; public int Count { get; private set; } public SyntaxListBuilder(int size) { _nodes = new ArrayElement<GreenNode?>[size]; } public void Clear() { this.Count = 0; } public void Add(SyntaxNode item) { AddInternal(item.Green); } internal void AddInternal(GreenNode item) { if (item == null) { throw new ArgumentNullException(); } if (Count >= _nodes.Length) { this.Grow(Count == 0 ? 8 : _nodes.Length * 2); } _nodes[Count++].Value = item; } public void AddRange(SyntaxNode[] items) { this.AddRange(items, 0, items.Length); } public void AddRange(SyntaxNode[] items, int offset, int length) { if (Count + length > _nodes.Length) { this.Grow(Count + length); } for (int i = offset, j = Count; i < offset + length; ++i, ++j) { _nodes[j].Value = items[i].Green; } int start = Count; Count += length; Validate(start, Count); } [Conditional("DEBUG")] private void Validate(int start, int end) { for (int i = start; i < end; i++) { if (_nodes[i].Value == null) { throw new ArgumentException("Cannot add a null node."); } } } public void AddRange(SyntaxList<SyntaxNode> list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxList<SyntaxNode> list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list.ItemInternal(i)!.Green; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange<TNode>(SyntaxList<TNode> list) where TNode : SyntaxNode { this.AddRange(list, 0, list.Count); } public void AddRange<TNode>(SyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { this.AddRange(new SyntaxList<SyntaxNode>(list.Node), offset, count); } public void AddRange(SyntaxNodeOrTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxNodeOrTokenList list, int offset, int count) { if (this.Count + count > _nodes.Length) { this.Grow(Count + count); } var dst = this.Count; for (int i = offset, limit = offset + count; i < limit; i++) { _nodes[dst].Value = list[i].UnderlyingNode; dst++; } int start = Count; Count += count; Validate(start, Count); } public void AddRange(SyntaxTokenList list) { this.AddRange(list, 0, list.Count); } public void AddRange(SyntaxTokenList list, int offset, int length) { Debug.Assert(list.Node is object); this.AddRange(new SyntaxList<SyntaxNode>(list.Node.CreateRed()), offset, length); } private void Grow(int size) { var tmp = new ArrayElement<GreenNode?>[size]; Array.Copy(_nodes, tmp, _nodes.Length); _nodes = tmp; } public bool Any(int kind) { for (int i = 0; i < Count; i++) { if (_nodes[i].Value!.RawKind == kind) { return true; } } return false; } internal GreenNode? ToListNode() { switch (this.Count) { case 0: return null; case 1: return _nodes[0].Value; case 2: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!); case 3: return InternalSyntax.SyntaxList.List(_nodes[0].Value!, _nodes[1].Value!, _nodes[2].Value!); default: var tmp = new ArrayElement<GreenNode>[this.Count]; for (int i = 0; i < this.Count; i++) { tmp[i].Value = _nodes[i].Value!; } return InternalSyntax.SyntaxList.List(tmp); } } public static implicit operator SyntaxList<SyntaxNode>(SyntaxListBuilder builder) { if (builder == null) { return default(SyntaxList<SyntaxNode>); } return builder.ToList(); } internal void RemoveLast() { this.Count -= 1; this._nodes[Count] = default; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeStruct.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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeStruct))] public sealed class ExternalCodeStruct : AbstractExternalCodeType, EnvDTE80.CodeStruct2, EnvDTE.CodeStruct { internal static EnvDTE.CodeStruct Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var element = new ExternalCodeStruct(state, projectId, typeSymbol); return (EnvDTE.CodeStruct)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeStruct(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) : base(state, projectId, typeSymbol) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementStruct; } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain; } set { throw Exceptions.ThrowEFail(); } } public override EnvDTE.CodeElements ImplementedInterfaces { get { return ExternalTypeCollection.Create(this.State, this, this.ProjectId, TypeSymbol.AllInterfaces); } } public new bool IsAbstract { get { return base.IsAbstract; } set { throw Exceptions.ThrowEFail(); } } public bool IsGeneric { get { throw new NotImplementedException(); } } public EnvDTE.CodeElements Parts { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public void RemoveInterface(object element) => throw Exceptions.ThrowEFail(); } }
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeStruct))] public sealed class ExternalCodeStruct : AbstractExternalCodeType, EnvDTE80.CodeStruct2, EnvDTE.CodeStruct { internal static EnvDTE.CodeStruct Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var element = new ExternalCodeStruct(state, projectId, typeSymbol); return (EnvDTE.CodeStruct)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeStruct(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) : base(state, projectId, typeSymbol) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementStruct; } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain; } set { throw Exceptions.ThrowEFail(); } } public override EnvDTE.CodeElements ImplementedInterfaces { get { return ExternalTypeCollection.Create(this.State, this, this.ProjectId, TypeSymbol.AllInterfaces); } } public new bool IsAbstract { get { return base.IsAbstract; } set { throw Exceptions.ThrowEFail(); } } public bool IsGeneric { get { throw new NotImplementedException(); } } public EnvDTE.CodeElements Parts { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public void RemoveInterface(object element) => throw Exceptions.ThrowEFail(); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/RecentItemsManager.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 Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { [Export] internal class RecentItemsManager { private const int MaxMRUSize = 10; /// <summary> /// Guard for <see cref="RecentItems"/> /// </summary> private readonly object _mruUpdateLock = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RecentItemsManager() { } public ImmutableArray<string> RecentItems { get; private set; } = ImmutableArray<string>.Empty; public void MakeMostRecentItem(string item) { lock (_mruUpdateLock) { var items = RecentItems; items = items.Remove(item); if (items.Length == MaxMRUSize) { // Remove the least recent item. items = items.RemoveAt(0); } RecentItems = items.Add(item); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { [Export] internal class RecentItemsManager { private const int MaxMRUSize = 10; /// <summary> /// Guard for <see cref="RecentItems"/> /// </summary> private readonly object _mruUpdateLock = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RecentItemsManager() { } public ImmutableArray<string> RecentItems { get; private set; } = ImmutableArray<string>.Empty; public void MakeMostRecentItem(string item) { lock (_mruUpdateLock) { var items = RecentItems; items = items.Remove(item); if (items.Length == MaxMRUSize) { // Remove the least recent item. items = items.RemoveAt(0); } RecentItems = items.Add(item); } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Tools/ExternalAccess/FSharp/Navigation/FSharpDocumentNavigationService.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.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation { [ExportWorkspaceService(typeof(IFSharpDocumentNavigationService)), Shared] internal class FSharpDocumentNavigationService : IFSharpDocumentNavigationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpDocumentNavigationService() { } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) => CanNavigateToSpan(workspace, documentId, textSpan, CancellationToken.None); public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) => CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, CancellationToken.None); public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, cancellationToken); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace) => CanNavigateToPosition(workspace, documentId, position, virtualSpace, CancellationToken.None); public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options) => TryNavigateToSpan(workspace, documentId, textSpan, options, CancellationToken.None); public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToSpan(workspace, documentId, textSpan, options, cancellationToken); } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options) => TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, CancellationToken.None); public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, cancellationToken); } public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options) => TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, 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; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation { [ExportWorkspaceService(typeof(IFSharpDocumentNavigationService)), Shared] internal class FSharpDocumentNavigationService : IFSharpDocumentNavigationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpDocumentNavigationService() { } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) => CanNavigateToSpan(workspace, documentId, textSpan, CancellationToken.None); public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) => CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, CancellationToken.None); public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, cancellationToken); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace) => CanNavigateToPosition(workspace, documentId, position, virtualSpace, CancellationToken.None); public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options) => TryNavigateToSpan(workspace, documentId, textSpan, options, CancellationToken.None); public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToSpan(workspace, documentId, textSpan, options, cancellationToken); } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options) => TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, CancellationToken.None); public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, cancellationToken); } public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options) => TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/Core/Implementation/CommentSelection/ToggleBlockCommentCommandHandler.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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { [Export(typeof(ICommandHandler))] [VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)] [VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)] internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService) { } /// <summary> /// Gets block comments by parsing the text for comment markers. /// </summary> protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { var allText = snapshot.AsText(); var commentedSpans = ArrayBuilder<TextSpan>.GetInstance(); var openIdx = 0; while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0) { // Retrieve the first closing marker located after the open index. var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true); // If an open marker is found without a close marker, it's an unclosed comment. if (closeIdx < 0) { closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length; } var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx); commentedSpans.Add(blockCommentSpan); openIdx = closeIdx; } return Task.FromResult(commentedSpans.ToImmutableAndFree()); } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { [Export(typeof(ICommandHandler))] [VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)] [VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)] internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService) { } /// <summary> /// Gets block comments by parsing the text for comment markers. /// </summary> protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { var allText = snapshot.AsText(); var commentedSpans = ArrayBuilder<TextSpan>.GetInstance(); var openIdx = 0; while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0) { // Retrieve the first closing marker located after the open index. var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true); // If an open marker is found without a close marker, it's an unclosed comment. if (closeIdx < 0) { closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length; } var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx); commentedSpans.Add(blockCommentSpan); openIdx = closeIdx; } return Task.FromResult(commentedSpans.ToImmutableAndFree()); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/NonReentrantLock.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.Threading; #if WORKSPACE using Microsoft.CodeAnalysis.Internal.Log; #endif namespace Roslyn.Utilities { /// <summary> /// A lightweight mutual exclusion object which supports waiting with cancellation and prevents /// recursion (i.e. you may not call Wait if you already hold the lock) /// </summary> /// <remarks> /// <para> /// The <see cref="NonReentrantLock"/> provides a lightweight mutual exclusion class that doesn't /// use Windows kernel synchronization primitives. /// </para> /// <para> /// The implementation is distilled from the workings of <see cref="SemaphoreSlim"/> /// The basic idea is that we use a regular sync object (Monitor.Enter/Exit) to guard the setting /// of an 'owning thread' field. If, during the Wait, we find the lock is held by someone else /// then we register a cancellation callback and enter a "Monitor.Wait" loop. If the cancellation /// callback fires, then it "pulses" all the waiters to wake them up and check for cancellation. /// Waiters are also "pulsed" when leaving the lock. /// </para> /// <para> /// All public members of <see cref="NonReentrantLock"/> are thread-safe and may be used concurrently /// from multiple threads. /// </para> /// </remarks> internal sealed class NonReentrantLock { /// <summary> /// A synchronization object to protect access to the <see cref="_owningThreadId"/> field and to be pulsed /// when <see cref="Release"/> is called and during cancellation. /// </summary> private readonly object _syncLock; /// <summary> /// The <see cref="Environment.CurrentManagedThreadId" /> of the thread that holds the lock. Zero if no thread is holding /// the lock. /// </summary> private volatile int _owningThreadId; /// <summary> /// Constructor. /// </summary> /// <param name="useThisInstanceForSynchronization">If false (the default), then the class /// allocates an internal object to be used as a sync lock. /// If true, then the sync lock object will be the NonReentrantLock instance itself. This /// saves an allocation but a client may not safely further use this instance in a call to /// Monitor.Enter/Exit or in a "lock" statement. /// </param> public NonReentrantLock(bool useThisInstanceForSynchronization = false) => _syncLock = useThisInstanceForSynchronization ? this : new object(); /// <summary> /// Shared factory for use in lazy initialization. /// </summary> public static readonly Func<NonReentrantLock> Factory = () => new NonReentrantLock(useThisInstanceForSynchronization: true); /// <summary> /// Blocks the current thread until it can enter the <see cref="NonReentrantLock"/>, while observing a /// <see cref="CancellationToken"/>. /// </summary> /// <remarks> /// Recursive locking is not supported. i.e. A thread may not call Wait successfully twice without an /// intervening <see cref="Release"/>. /// </remarks> /// <param name="cancellationToken">The <see cref="CancellationToken"/> token to /// observe.</param> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was /// canceled.</exception> /// <exception cref="LockRecursionException">The caller already holds the lock</exception> public void Wait(CancellationToken cancellationToken = default) { if (this.IsOwnedByMe) { throw new LockRecursionException(); } CancellationTokenRegistration cancellationTokenRegistration = default; if (cancellationToken.CanBeCanceled) { cancellationToken.ThrowIfCancellationRequested(); // Fast path to try and avoid allocations in callback registration. lock (_syncLock) { if (!this.IsLocked) { this.TakeOwnership(); return; } } cancellationTokenRegistration = cancellationToken.Register(s_cancellationTokenCanceledEventHandler, _syncLock, useSynchronizationContext: false); } using (cancellationTokenRegistration) { // PERF: First spin wait for the lock to become available, but only up to the first planned yield. // This additional amount of spinwaiting was inherited from SemaphoreSlim's implementation where // it showed measurable perf gains in test scenarios. var spin = new SpinWait(); while (this.IsLocked && !spin.NextSpinWillYield) { spin.SpinOnce(); } lock (_syncLock) { while (this.IsLocked) { // If cancelled, we throw. Trying to wait could lead to deadlock. cancellationToken.ThrowIfCancellationRequested(); #if WORKSPACE using (Logger.LogBlock(FunctionId.Misc_NonReentrantLock_BlockingWait, cancellationToken)) #endif { // Another thread holds the lock. Wait until we get awoken either // by some code calling "Release" or by cancellation. Monitor.Wait(_syncLock); } } // We now hold the lock this.TakeOwnership(); } } } /// <summary> /// Exit the mutual exclusion. /// </summary> /// <remarks> /// The calling thread must currently hold the lock. /// </remarks> /// <exception cref="InvalidOperationException">The lock is not currently held by the calling thread.</exception> public void Release() { AssertHasLock(); lock (_syncLock) { this.ReleaseOwnership(); // Release one waiter Monitor.Pulse(_syncLock); } } /// <summary> /// Determine if the lock is currently held by the calling thread. /// </summary> /// <returns>True if the lock is currently held by the calling thread.</returns> public bool LockHeldByMe() => this.IsOwnedByMe; /// <summary> /// Throw an exception if the lock is not held by the calling thread. /// </summary> /// <exception cref="InvalidOperationException">The lock is not currently held by the calling thread.</exception> public void AssertHasLock() => Contract.ThrowIfFalse(LockHeldByMe()); /// <summary> /// Checks if the lock is currently held. /// </summary> private bool IsLocked { get { return _owningThreadId != 0; } } /// <summary> /// Checks if the lock is currently held by the calling thread. /// </summary> private bool IsOwnedByMe { get { return _owningThreadId == Environment.CurrentManagedThreadId; } } /// <summary> /// Take ownership of the lock (by the calling thread). The lock may not already /// be held by any other code. /// </summary> private void TakeOwnership() { Debug.Assert(!this.IsLocked); _owningThreadId = Environment.CurrentManagedThreadId; } /// <summary> /// Release ownership of the lock. The lock must already be held by the calling thread. /// </summary> private void ReleaseOwnership() { Debug.Assert(this.IsOwnedByMe); _owningThreadId = 0; } /// <summary> /// Action object passed to a cancellation token registration. /// </summary> private static readonly Action<object?> s_cancellationTokenCanceledEventHandler = CancellationTokenCanceledEventHandler; /// <summary> /// Callback executed when a cancellation token is canceled during a Wait. /// </summary> /// <param name="obj">The syncLock that protects a <see cref="NonReentrantLock"/> instance.</param> private static void CancellationTokenCanceledEventHandler(object? obj) { RoslynDebug.AssertNotNull(obj); lock (obj) { // Release all waiters to check their cancellation tokens. Monitor.PulseAll(obj); } } public SemaphoreDisposer DisposableWait(CancellationToken cancellationToken = default) { this.Wait(cancellationToken); return new SemaphoreDisposer(this); } /// <summary> /// Since we want to avoid boxing the return from <see cref="NonReentrantLock.DisposableWait"/>, this type must be public. /// </summary> public struct SemaphoreDisposer : IDisposable { private readonly NonReentrantLock _semaphore; public SemaphoreDisposer(NonReentrantLock semaphore) => _semaphore = semaphore; public void Dispose() => _semaphore.Release(); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; #if WORKSPACE using Microsoft.CodeAnalysis.Internal.Log; #endif namespace Roslyn.Utilities { /// <summary> /// A lightweight mutual exclusion object which supports waiting with cancellation and prevents /// recursion (i.e. you may not call Wait if you already hold the lock) /// </summary> /// <remarks> /// <para> /// The <see cref="NonReentrantLock"/> provides a lightweight mutual exclusion class that doesn't /// use Windows kernel synchronization primitives. /// </para> /// <para> /// The implementation is distilled from the workings of <see cref="SemaphoreSlim"/> /// The basic idea is that we use a regular sync object (Monitor.Enter/Exit) to guard the setting /// of an 'owning thread' field. If, during the Wait, we find the lock is held by someone else /// then we register a cancellation callback and enter a "Monitor.Wait" loop. If the cancellation /// callback fires, then it "pulses" all the waiters to wake them up and check for cancellation. /// Waiters are also "pulsed" when leaving the lock. /// </para> /// <para> /// All public members of <see cref="NonReentrantLock"/> are thread-safe and may be used concurrently /// from multiple threads. /// </para> /// </remarks> internal sealed class NonReentrantLock { /// <summary> /// A synchronization object to protect access to the <see cref="_owningThreadId"/> field and to be pulsed /// when <see cref="Release"/> is called and during cancellation. /// </summary> private readonly object _syncLock; /// <summary> /// The <see cref="Environment.CurrentManagedThreadId" /> of the thread that holds the lock. Zero if no thread is holding /// the lock. /// </summary> private volatile int _owningThreadId; /// <summary> /// Constructor. /// </summary> /// <param name="useThisInstanceForSynchronization">If false (the default), then the class /// allocates an internal object to be used as a sync lock. /// If true, then the sync lock object will be the NonReentrantLock instance itself. This /// saves an allocation but a client may not safely further use this instance in a call to /// Monitor.Enter/Exit or in a "lock" statement. /// </param> public NonReentrantLock(bool useThisInstanceForSynchronization = false) => _syncLock = useThisInstanceForSynchronization ? this : new object(); /// <summary> /// Shared factory for use in lazy initialization. /// </summary> public static readonly Func<NonReentrantLock> Factory = () => new NonReentrantLock(useThisInstanceForSynchronization: true); /// <summary> /// Blocks the current thread until it can enter the <see cref="NonReentrantLock"/>, while observing a /// <see cref="CancellationToken"/>. /// </summary> /// <remarks> /// Recursive locking is not supported. i.e. A thread may not call Wait successfully twice without an /// intervening <see cref="Release"/>. /// </remarks> /// <param name="cancellationToken">The <see cref="CancellationToken"/> token to /// observe.</param> /// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was /// canceled.</exception> /// <exception cref="LockRecursionException">The caller already holds the lock</exception> public void Wait(CancellationToken cancellationToken = default) { if (this.IsOwnedByMe) { throw new LockRecursionException(); } CancellationTokenRegistration cancellationTokenRegistration = default; if (cancellationToken.CanBeCanceled) { cancellationToken.ThrowIfCancellationRequested(); // Fast path to try and avoid allocations in callback registration. lock (_syncLock) { if (!this.IsLocked) { this.TakeOwnership(); return; } } cancellationTokenRegistration = cancellationToken.Register(s_cancellationTokenCanceledEventHandler, _syncLock, useSynchronizationContext: false); } using (cancellationTokenRegistration) { // PERF: First spin wait for the lock to become available, but only up to the first planned yield. // This additional amount of spinwaiting was inherited from SemaphoreSlim's implementation where // it showed measurable perf gains in test scenarios. var spin = new SpinWait(); while (this.IsLocked && !spin.NextSpinWillYield) { spin.SpinOnce(); } lock (_syncLock) { while (this.IsLocked) { // If cancelled, we throw. Trying to wait could lead to deadlock. cancellationToken.ThrowIfCancellationRequested(); #if WORKSPACE using (Logger.LogBlock(FunctionId.Misc_NonReentrantLock_BlockingWait, cancellationToken)) #endif { // Another thread holds the lock. Wait until we get awoken either // by some code calling "Release" or by cancellation. Monitor.Wait(_syncLock); } } // We now hold the lock this.TakeOwnership(); } } } /// <summary> /// Exit the mutual exclusion. /// </summary> /// <remarks> /// The calling thread must currently hold the lock. /// </remarks> /// <exception cref="InvalidOperationException">The lock is not currently held by the calling thread.</exception> public void Release() { AssertHasLock(); lock (_syncLock) { this.ReleaseOwnership(); // Release one waiter Monitor.Pulse(_syncLock); } } /// <summary> /// Determine if the lock is currently held by the calling thread. /// </summary> /// <returns>True if the lock is currently held by the calling thread.</returns> public bool LockHeldByMe() => this.IsOwnedByMe; /// <summary> /// Throw an exception if the lock is not held by the calling thread. /// </summary> /// <exception cref="InvalidOperationException">The lock is not currently held by the calling thread.</exception> public void AssertHasLock() => Contract.ThrowIfFalse(LockHeldByMe()); /// <summary> /// Checks if the lock is currently held. /// </summary> private bool IsLocked { get { return _owningThreadId != 0; } } /// <summary> /// Checks if the lock is currently held by the calling thread. /// </summary> private bool IsOwnedByMe { get { return _owningThreadId == Environment.CurrentManagedThreadId; } } /// <summary> /// Take ownership of the lock (by the calling thread). The lock may not already /// be held by any other code. /// </summary> private void TakeOwnership() { Debug.Assert(!this.IsLocked); _owningThreadId = Environment.CurrentManagedThreadId; } /// <summary> /// Release ownership of the lock. The lock must already be held by the calling thread. /// </summary> private void ReleaseOwnership() { Debug.Assert(this.IsOwnedByMe); _owningThreadId = 0; } /// <summary> /// Action object passed to a cancellation token registration. /// </summary> private static readonly Action<object?> s_cancellationTokenCanceledEventHandler = CancellationTokenCanceledEventHandler; /// <summary> /// Callback executed when a cancellation token is canceled during a Wait. /// </summary> /// <param name="obj">The syncLock that protects a <see cref="NonReentrantLock"/> instance.</param> private static void CancellationTokenCanceledEventHandler(object? obj) { RoslynDebug.AssertNotNull(obj); lock (obj) { // Release all waiters to check their cancellation tokens. Monitor.PulseAll(obj); } } public SemaphoreDisposer DisposableWait(CancellationToken cancellationToken = default) { this.Wait(cancellationToken); return new SemaphoreDisposer(this); } /// <summary> /// Since we want to avoid boxing the return from <see cref="NonReentrantLock.DisposableWait"/>, this type must be public. /// </summary> public struct SemaphoreDisposer : IDisposable { private readonly NonReentrantLock _semaphore; public SemaphoreDisposer(NonReentrantLock semaphore) => _semaphore = semaphore; public void Dispose() => _semaphore.Release(); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Lowering/IteratorRewriter/IteratorFinallyMethodSymbol.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A synthesized Finally method containing finalization code for a resumable try statement. /// Finalization code for such try may run when: /// 1) control flow goes out of try scope by dropping through /// 2) control flow goes out of try scope by conditionally or unconditionally branching outside of one ore more try/finally frames. /// 3) enumerator is disposed by the owner. /// 4) enumerator is being disposed after an exception. /// /// It is easier to manage partial or complete finalization when every finally is factored out as a separate method. /// /// NOTE: Finally is a private void nonvirtual instance method with no parameters. /// It is a valid JIT inlining target as long as JIT may consider inlining profitable. /// </summary> internal sealed class IteratorFinallyMethodSymbol : SynthesizedInstanceMethodSymbol, ISynthesizedMethodBodyImplementationSymbol { private readonly IteratorStateMachine _stateMachineType; private readonly string _name; public IteratorFinallyMethodSymbol(IteratorStateMachine stateMachineType, string name) { Debug.Assert((object)stateMachineType != null); Debug.Assert(name != null); _stateMachineType = stateMachineType; _name = name; } public override string Name { get { return _name; } } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override int Arity { get { return 0; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return false; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData GetDllImportData() { return null; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return false; } } public override bool ReturnsVoid { get { return true; } } public override bool IsAsync { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(ContainingAssembly.GetSpecialType(SpecialType.System_Void)); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override Cci.CallingConvention CallingConvention { get { return Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return true; } } public override Symbol ContainingSymbol { get { return _stateMachineType; } } public override ImmutableArray<Location> Locations { get { return ContainingType.Locations; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Private; } } public override bool IsStatic { get { return false; } } public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method { get { return _stateMachineType.KickoffMethod; } } bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency { get { return true; } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return _stateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A synthesized Finally method containing finalization code for a resumable try statement. /// Finalization code for such try may run when: /// 1) control flow goes out of try scope by dropping through /// 2) control flow goes out of try scope by conditionally or unconditionally branching outside of one ore more try/finally frames. /// 3) enumerator is disposed by the owner. /// 4) enumerator is being disposed after an exception. /// /// It is easier to manage partial or complete finalization when every finally is factored out as a separate method. /// /// NOTE: Finally is a private void nonvirtual instance method with no parameters. /// It is a valid JIT inlining target as long as JIT may consider inlining profitable. /// </summary> internal sealed class IteratorFinallyMethodSymbol : SynthesizedInstanceMethodSymbol, ISynthesizedMethodBodyImplementationSymbol { private readonly IteratorStateMachine _stateMachineType; private readonly string _name; public IteratorFinallyMethodSymbol(IteratorStateMachine stateMachineType, string name) { Debug.Assert((object)stateMachineType != null); Debug.Assert(name != null); _stateMachineType = stateMachineType; _name = name; } public override string Name { get { return _name; } } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override int Arity { get { return 0; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return false; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData GetDllImportData() { return null; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return false; } } public override bool ReturnsVoid { get { return true; } } public override bool IsAsync { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(ContainingAssembly.GetSpecialType(SpecialType.System_Void)); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override Cci.CallingConvention CallingConvention { get { return Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return true; } } public override Symbol ContainingSymbol { get { return _stateMachineType; } } public override ImmutableArray<Location> Locations { get { return ContainingType.Locations; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Private; } } public override bool IsStatic { get { return false; } } public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method { get { return _stateMachineType.KickoffMethod; } } bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency { get { return true; } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return _stateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Analyzers/CSharp/CodeFixes/UseCollectionInitializer/CSharpUseCollectionInitializerCodeFixProvider.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 Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer; using Microsoft.CodeAnalysis.UseCollectionInitializer; namespace Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCollectionInitializer), Shared] internal class CSharpUseCollectionInitializerCodeFixProvider : AbstractUseCollectionInitializerCodeFixProvider< SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, InvocationExpressionSyntax, ExpressionStatementSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseCollectionInitializerCodeFixProvider() { } protected override StatementSyntax GetNewStatement( StatementSyntax statement, ObjectCreationExpressionSyntax objectCreation, ImmutableArray<ExpressionStatementSyntax> matches) { return statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)); } private static ObjectCreationExpressionSyntax GetNewObjectCreation( ObjectCreationExpressionSyntax objectCreation, ImmutableArray<ExpressionStatementSyntax> matches) { return UseInitializerHelpers.GetNewObjectCreation( objectCreation, CreateExpressions(matches)); } private static SeparatedSyntaxList<ExpressionSyntax> CreateExpressions( ImmutableArray<ExpressionStatementSyntax> matches) { var nodesAndTokens = new List<SyntaxNodeOrToken>(); for (var i = 0; i < matches.Length; i++) { var expressionStatement = matches[i]; var newExpression = ConvertExpression(expressionStatement.Expression) .WithoutTrivia() .WithLeadingTrivia(expressionStatement.GetLeadingTrivia()); if (i < matches.Length - 1) { nodesAndTokens.Add(newExpression); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken) .WithTriviaFrom(expressionStatement.SemicolonToken); nodesAndTokens.Add(commaToken); } else { newExpression = newExpression.WithTrailingTrivia( expressionStatement.GetTrailingTrivia()); nodesAndTokens.Add(newExpression); } } return SyntaxFactory.SeparatedList<ExpressionSyntax>(nodesAndTokens); } private static ExpressionSyntax ConvertExpression(ExpressionSyntax expression) { if (expression is InvocationExpressionSyntax invocation) { return ConvertInvocation(invocation); } else if (expression is AssignmentExpressionSyntax assignment) { return ConvertAssignment(assignment); } throw new InvalidOperationException(); } private static ExpressionSyntax ConvertAssignment(AssignmentExpressionSyntax assignment) { var elementAccess = (ElementAccessExpressionSyntax)assignment.Left; return assignment.WithLeft( SyntaxFactory.ImplicitElementAccess(elementAccess.ArgumentList)); } private static ExpressionSyntax ConvertInvocation(InvocationExpressionSyntax invocation) { var arguments = invocation.ArgumentList.Arguments; if (arguments.Count == 1) { // Assignment expressions in a collection initializer will cause the compiler to // report an error. This is because { a = b } is the form for an object initializer, // and the two forms are not allowed to mix/match. Parenthesize the assignment to // avoid the ambiguity. var expression = arguments[0].Expression; return SyntaxFacts.IsAssignmentExpression(expression.Kind()) ? SyntaxFactory.ParenthesizedExpression(expression) : expression; } return SyntaxFactory.InitializerExpression( SyntaxKind.ComplexElementInitializerExpression, SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithoutTrivia(), SyntaxFactory.SeparatedList( arguments.Select(a => a.Expression), arguments.GetSeparators()), SyntaxFactory.Token(SyntaxKind.CloseBraceToken).WithoutTrivia()); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer; using Microsoft.CodeAnalysis.UseCollectionInitializer; namespace Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCollectionInitializer), Shared] internal class CSharpUseCollectionInitializerCodeFixProvider : AbstractUseCollectionInitializerCodeFixProvider< SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, InvocationExpressionSyntax, ExpressionStatementSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseCollectionInitializerCodeFixProvider() { } protected override StatementSyntax GetNewStatement( StatementSyntax statement, ObjectCreationExpressionSyntax objectCreation, ImmutableArray<ExpressionStatementSyntax> matches) { return statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)); } private static ObjectCreationExpressionSyntax GetNewObjectCreation( ObjectCreationExpressionSyntax objectCreation, ImmutableArray<ExpressionStatementSyntax> matches) { return UseInitializerHelpers.GetNewObjectCreation( objectCreation, CreateExpressions(matches)); } private static SeparatedSyntaxList<ExpressionSyntax> CreateExpressions( ImmutableArray<ExpressionStatementSyntax> matches) { var nodesAndTokens = new List<SyntaxNodeOrToken>(); for (var i = 0; i < matches.Length; i++) { var expressionStatement = matches[i]; var newExpression = ConvertExpression(expressionStatement.Expression) .WithoutTrivia() .WithLeadingTrivia(expressionStatement.GetLeadingTrivia()); if (i < matches.Length - 1) { nodesAndTokens.Add(newExpression); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken) .WithTriviaFrom(expressionStatement.SemicolonToken); nodesAndTokens.Add(commaToken); } else { newExpression = newExpression.WithTrailingTrivia( expressionStatement.GetTrailingTrivia()); nodesAndTokens.Add(newExpression); } } return SyntaxFactory.SeparatedList<ExpressionSyntax>(nodesAndTokens); } private static ExpressionSyntax ConvertExpression(ExpressionSyntax expression) { if (expression is InvocationExpressionSyntax invocation) { return ConvertInvocation(invocation); } else if (expression is AssignmentExpressionSyntax assignment) { return ConvertAssignment(assignment); } throw new InvalidOperationException(); } private static ExpressionSyntax ConvertAssignment(AssignmentExpressionSyntax assignment) { var elementAccess = (ElementAccessExpressionSyntax)assignment.Left; return assignment.WithLeft( SyntaxFactory.ImplicitElementAccess(elementAccess.ArgumentList)); } private static ExpressionSyntax ConvertInvocation(InvocationExpressionSyntax invocation) { var arguments = invocation.ArgumentList.Arguments; if (arguments.Count == 1) { // Assignment expressions in a collection initializer will cause the compiler to // report an error. This is because { a = b } is the form for an object initializer, // and the two forms are not allowed to mix/match. Parenthesize the assignment to // avoid the ambiguity. var expression = arguments[0].Expression; return SyntaxFacts.IsAssignmentExpression(expression.Kind()) ? SyntaxFactory.ParenthesizedExpression(expression) : expression; } return SyntaxFactory.InitializerExpression( SyntaxKind.ComplexElementInitializerExpression, SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithoutTrivia(), SyntaxFactory.SeparatedList( arguments.Select(a => a.Expression), arguments.GetSeparators()), SyntaxFactory.Token(SyntaxKind.CloseBraceToken).WithoutTrivia()); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/Portable/Symbols/Attributes/SecurityWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from security attributes, i.e. attributes derived from well-known SecurityAttribute, applied on a method/type/assembly. /// </summary> internal sealed class SecurityWellKnownAttributeData { // data from Security attributes: // Array of decoded security actions corresponding to source security attributes, null if there are no security attributes in source. private byte[] _lazySecurityActions; // Array of resolved file paths corresponding to source PermissionSet security attributes needing fixup, null if there are no security attributes in source. // Fixup involves reading the file contents of the resolved file and emitting it in the permission set. private string[] _lazyPathsForPermissionSetFixup; public void SetSecurityAttribute(int attributeIndex, DeclarativeSecurityAction action, int totalSourceAttributes) { Debug.Assert(attributeIndex >= 0 && attributeIndex < totalSourceAttributes); Debug.Assert(action != 0); if (_lazySecurityActions == null) { Interlocked.CompareExchange(ref _lazySecurityActions, new byte[totalSourceAttributes], null); } Debug.Assert(_lazySecurityActions.Length == totalSourceAttributes); _lazySecurityActions[attributeIndex] = (byte)action; } public void SetPathForPermissionSetAttributeFixup(int attributeIndex, string resolvedFilePath, int totalSourceAttributes) { Debug.Assert(attributeIndex >= 0 && attributeIndex < totalSourceAttributes); Debug.Assert(resolvedFilePath != null); if (_lazyPathsForPermissionSetFixup == null) { Interlocked.CompareExchange(ref _lazyPathsForPermissionSetFixup, new string[totalSourceAttributes], null); } Debug.Assert(_lazyPathsForPermissionSetFixup.Length == totalSourceAttributes); _lazyPathsForPermissionSetFixup[attributeIndex] = resolvedFilePath; } /// <summary> /// Used for retrieving applied source security attributes, i.e. attributes derived from well-known SecurityAttribute. /// </summary> public IEnumerable<Cci.SecurityAttribute> GetSecurityAttributes<T>(ImmutableArray<T> customAttributes) where T : Cci.ICustomAttribute { Debug.Assert(!customAttributes.IsDefault); Debug.Assert(_lazyPathsForPermissionSetFixup == null || _lazySecurityActions != null && _lazyPathsForPermissionSetFixup.Length == _lazySecurityActions.Length); if (_lazySecurityActions != null) { Debug.Assert(_lazySecurityActions != null); Debug.Assert(_lazySecurityActions.Length == customAttributes.Length); for (int i = 0; i < customAttributes.Length; i++) { if (_lazySecurityActions[i] != 0) { var action = (DeclarativeSecurityAction)_lazySecurityActions[i]; Cci.ICustomAttribute attribute = customAttributes[i]; if (_lazyPathsForPermissionSetFixup?[i] != null) { attribute = new PermissionSetAttributeWithFileReference(attribute, _lazyPathsForPermissionSetFixup[i]); } yield return new Cci.SecurityAttribute(action, attribute); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from security attributes, i.e. attributes derived from well-known SecurityAttribute, applied on a method/type/assembly. /// </summary> internal sealed class SecurityWellKnownAttributeData { // data from Security attributes: // Array of decoded security actions corresponding to source security attributes, null if there are no security attributes in source. private byte[] _lazySecurityActions; // Array of resolved file paths corresponding to source PermissionSet security attributes needing fixup, null if there are no security attributes in source. // Fixup involves reading the file contents of the resolved file and emitting it in the permission set. private string[] _lazyPathsForPermissionSetFixup; public void SetSecurityAttribute(int attributeIndex, DeclarativeSecurityAction action, int totalSourceAttributes) { Debug.Assert(attributeIndex >= 0 && attributeIndex < totalSourceAttributes); Debug.Assert(action != 0); if (_lazySecurityActions == null) { Interlocked.CompareExchange(ref _lazySecurityActions, new byte[totalSourceAttributes], null); } Debug.Assert(_lazySecurityActions.Length == totalSourceAttributes); _lazySecurityActions[attributeIndex] = (byte)action; } public void SetPathForPermissionSetAttributeFixup(int attributeIndex, string resolvedFilePath, int totalSourceAttributes) { Debug.Assert(attributeIndex >= 0 && attributeIndex < totalSourceAttributes); Debug.Assert(resolvedFilePath != null); if (_lazyPathsForPermissionSetFixup == null) { Interlocked.CompareExchange(ref _lazyPathsForPermissionSetFixup, new string[totalSourceAttributes], null); } Debug.Assert(_lazyPathsForPermissionSetFixup.Length == totalSourceAttributes); _lazyPathsForPermissionSetFixup[attributeIndex] = resolvedFilePath; } /// <summary> /// Used for retrieving applied source security attributes, i.e. attributes derived from well-known SecurityAttribute. /// </summary> public IEnumerable<Cci.SecurityAttribute> GetSecurityAttributes<T>(ImmutableArray<T> customAttributes) where T : Cci.ICustomAttribute { Debug.Assert(!customAttributes.IsDefault); Debug.Assert(_lazyPathsForPermissionSetFixup == null || _lazySecurityActions != null && _lazyPathsForPermissionSetFixup.Length == _lazySecurityActions.Length); if (_lazySecurityActions != null) { Debug.Assert(_lazySecurityActions != null); Debug.Assert(_lazySecurityActions.Length == customAttributes.Length); for (int i = 0; i < customAttributes.Length; i++) { if (_lazySecurityActions[i] != 0) { var action = (DeclarativeSecurityAction)_lazySecurityActions[i]; Cci.ICustomAttribute attribute = customAttributes[i]; if (_lazyPathsForPermissionSetFixup?[i] != null) { attribute = new PermissionSetAttributeWithFileReference(attribute, _lazyPathsForPermissionSetFixup[i]); } yield return new Cci.SecurityAttribute(action, attribute); } } } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Syntax/ConstructorDeclarationSyntax.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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ConstructorDeclarationSyntax { public ConstructorDeclarationSyntax Update( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body, SyntaxToken semicolonToken) => Update( attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody: null, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody: null, default(SyntaxToken)); public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body, SyntaxToken semicolonToken) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody: null, semicolonToken); public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, ArrowExpressionClauseSyntax expressionBody) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body: null, expressionBody, default(SyntaxToken)); public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body: null, expressionBody, semicolonToken); } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ConstructorDeclarationSyntax { public ConstructorDeclarationSyntax Update( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body, SyntaxToken semicolonToken) => Update( attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody: null, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody: null, default(SyntaxToken)); public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, BlockSyntax body, SyntaxToken semicolonToken) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody: null, semicolonToken); public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, ArrowExpressionClauseSyntax expressionBody) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body: null, expressionBody, default(SyntaxToken)); public static ConstructorDeclarationSyntax ConstructorDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax initializer, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken) => ConstructorDeclaration( attributeLists, modifiers, identifier, parameterList, initializer, body: null, expressionBody, semicolonToken); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingHotReloadService.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.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingHotReloadService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly ImmutableArray<string> _capabilities; public DebuggerService(ImmutableArray<string> capabilities) { _capabilities = capabilities; } public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(_capabilities); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } public readonly struct Update { public readonly Guid ModuleId; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> PdbDelta; public readonly ImmutableArray<int> UpdatedMethods; public readonly ImmutableArray<int> UpdatedTypes; public Update( Guid moduleId, ImmutableArray<byte> ilDelta, ImmutableArray<byte> metadataDelta, ImmutableArray<byte> pdbDelta, ImmutableArray<int> updatedMethods, ImmutableArray<int> updatedTypes) { ModuleId = moduleId; ILDelta = ilDelta; MetadataDelta = metadataDelta; PdbDelta = pdbDelta; UpdatedMethods = updatedMethods; UpdatedTypes = updatedTypes; } } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private static readonly ImmutableArray<Update> EmptyUpdate = ImmutableArray.Create<Update>(); private static readonly ImmutableArray<Diagnostic> EmptyDiagnostic = ImmutableArray.Create<Diagnostic>(); private readonly IEditAndContinueWorkspaceService _encService; private DebuggingSessionId _sessionId; public UnitTestingHotReloadService(HostWorkspaceServices services) => _encService = services.GetRequiredService<IEditAndContinueWorkspaceService>(); /// <summary> /// Starts the watcher. /// </summary> /// <param name="solution">Solution that represents sources that match the built binaries on disk.</param> /// <param name="capabilities">Array of capabilities retrieved from the runtime to dictate supported rude edits.</param> /// <param name="cancellationToken">Cancellation token.</param> public async Task StartSessionAsync(Solution solution, ImmutableArray<string> capabilities, CancellationToken cancellationToken) { var newSessionId = await _encService.StartDebuggingSessionAsync( solution, new DebuggerService(capabilities), captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: false, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; } /// <summary> /// Emits updates for all projects that differ between the given <paramref name="solution"/> snapshot and the one given to the previous successful call /// where <paramref name="commitUpdates"/> was `true` or the one passed to <see cref="StartSessionAsync(Solution, ImmutableArray{string}, CancellationToken)"/> /// for the first invocation. /// </summary> /// <param name="solution">Solution snapshot.</param> /// <param name="commitUpdates">commits changes if true, discards if false</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Updates (one for each changed project) and Rude Edit diagnostics. Does not include syntax or semantic diagnostics. /// </returns> public async Task<(ImmutableArray<Update> updates, ImmutableArray<Diagnostic> diagnostics)> EmitSolutionUpdateAsync(Solution solution, bool commitUpdates, CancellationToken cancellationToken) { var sessionId = _sessionId; Contract.ThrowIfFalse(sessionId != default, "Session has not started"); var results = await _encService .EmitSolutionUpdateAsync(sessionId, solution, s_solutionActiveStatementSpanProvider, cancellationToken) .ConfigureAwait(false); if (results.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { if (commitUpdates) { _encService.CommitSolutionUpdate(sessionId, out _); } else { _encService.DiscardSolutionUpdate(sessionId); } } if (results.SyntaxError is not null) { // We do not need to acquire any updates or other // diagnostics if there is a syntax error. return (EmptyUpdate, EmptyDiagnostic.Add(results.SyntaxError)); } var updates = results.ModuleUpdates.Updates.SelectAsArray( update => new Update( update.Module, update.ILDelta, update.MetadataDelta, update.PdbDelta, update.UpdatedMethods, update.UpdatedTypes)); var diagnostics = await results.GetAllDiagnosticsAsync(solution, cancellationToken).ConfigureAwait(false); return (updates, diagnostics); } public void EndSession() { Contract.ThrowIfFalse(_sessionId != default, "Session has not started"); _encService.EndDebuggingSession(_sessionId, out _); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly UnitTestingHotReloadService _instance; internal TestAccessor(UnitTestingHotReloadService instance) => _instance = instance; public DebuggingSessionId SessionId => _instance._sessionId; } } }
// Licensed to the .NET Foundation under one or more 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.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingHotReloadService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly ImmutableArray<string> _capabilities; public DebuggerService(ImmutableArray<string> capabilities) { _capabilities = capabilities; } public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(_capabilities); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } public readonly struct Update { public readonly Guid ModuleId; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> PdbDelta; public readonly ImmutableArray<int> UpdatedMethods; public readonly ImmutableArray<int> UpdatedTypes; public Update( Guid moduleId, ImmutableArray<byte> ilDelta, ImmutableArray<byte> metadataDelta, ImmutableArray<byte> pdbDelta, ImmutableArray<int> updatedMethods, ImmutableArray<int> updatedTypes) { ModuleId = moduleId; ILDelta = ilDelta; MetadataDelta = metadataDelta; PdbDelta = pdbDelta; UpdatedMethods = updatedMethods; UpdatedTypes = updatedTypes; } } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private static readonly ImmutableArray<Update> EmptyUpdate = ImmutableArray.Create<Update>(); private static readonly ImmutableArray<Diagnostic> EmptyDiagnostic = ImmutableArray.Create<Diagnostic>(); private readonly IEditAndContinueWorkspaceService _encService; private DebuggingSessionId _sessionId; public UnitTestingHotReloadService(HostWorkspaceServices services) => _encService = services.GetRequiredService<IEditAndContinueWorkspaceService>(); /// <summary> /// Starts the watcher. /// </summary> /// <param name="solution">Solution that represents sources that match the built binaries on disk.</param> /// <param name="capabilities">Array of capabilities retrieved from the runtime to dictate supported rude edits.</param> /// <param name="cancellationToken">Cancellation token.</param> public async Task StartSessionAsync(Solution solution, ImmutableArray<string> capabilities, CancellationToken cancellationToken) { var newSessionId = await _encService.StartDebuggingSessionAsync( solution, new DebuggerService(capabilities), captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: false, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; } /// <summary> /// Emits updates for all projects that differ between the given <paramref name="solution"/> snapshot and the one given to the previous successful call /// where <paramref name="commitUpdates"/> was `true` or the one passed to <see cref="StartSessionAsync(Solution, ImmutableArray{string}, CancellationToken)"/> /// for the first invocation. /// </summary> /// <param name="solution">Solution snapshot.</param> /// <param name="commitUpdates">commits changes if true, discards if false</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Updates (one for each changed project) and Rude Edit diagnostics. Does not include syntax or semantic diagnostics. /// </returns> public async Task<(ImmutableArray<Update> updates, ImmutableArray<Diagnostic> diagnostics)> EmitSolutionUpdateAsync(Solution solution, bool commitUpdates, CancellationToken cancellationToken) { var sessionId = _sessionId; Contract.ThrowIfFalse(sessionId != default, "Session has not started"); var results = await _encService .EmitSolutionUpdateAsync(sessionId, solution, s_solutionActiveStatementSpanProvider, cancellationToken) .ConfigureAwait(false); if (results.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { if (commitUpdates) { _encService.CommitSolutionUpdate(sessionId, out _); } else { _encService.DiscardSolutionUpdate(sessionId); } } if (results.SyntaxError is not null) { // We do not need to acquire any updates or other // diagnostics if there is a syntax error. return (EmptyUpdate, EmptyDiagnostic.Add(results.SyntaxError)); } var updates = results.ModuleUpdates.Updates.SelectAsArray( update => new Update( update.Module, update.ILDelta, update.MetadataDelta, update.PdbDelta, update.UpdatedMethods, update.UpdatedTypes)); var diagnostics = await results.GetAllDiagnosticsAsync(solution, cancellationToken).ConfigureAwait(false); return (updates, diagnostics); } public void EndSession() { Contract.ThrowIfFalse(_sessionId != default, "Session has not started"); _encService.EndDebuggingSession(_sessionId, out _); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly UnitTestingHotReloadService _instance; internal TestAccessor(UnitTestingHotReloadService instance) => _instance = instance; public DebuggingSessionId SessionId => _instance._sessionId; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/EncapsulateField_OutOfProc.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.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class EncapsulateField_OutOfProc : OutOfProcComponent { public string DialogName = "Preview Changes - Encapsulate Field"; public EncapsulateField_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.E, ShiftState.Ctrl)); } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class EncapsulateField_OutOfProc : OutOfProcComponent { public string DialogName = "Preview Changes - Encapsulate Field"; public EncapsulateField_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.E, ShiftState.Ctrl)); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Symbols/SubstitutedEventSymbol.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.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SubstitutedEventSymbol : WrappedEventSymbol { private readonly SubstitutedNamedTypeSymbol _containingType; private TypeWithAnnotations.Boxed? _lazyType; internal SubstitutedEventSymbol(SubstitutedNamedTypeSymbol containingType, EventSymbol originalDefinition) : base(originalDefinition) { Debug.Assert(originalDefinition.IsDefinition); _containingType = containingType; } public override TypeWithAnnotations TypeWithAnnotations { get { if (_lazyType == null) { var type = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations); Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null); } return _lazyType.Value; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override EventSymbol OriginalDefinition { get { return _underlyingEvent; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return OriginalDefinition.GetAttributes(); } public override MethodSymbol? AddMethod { get { MethodSymbol? originalAddMethod = OriginalDefinition.AddMethod; return (object?)originalAddMethod == null ? null : originalAddMethod.AsMember(_containingType); } } public override MethodSymbol? RemoveMethod { get { MethodSymbol? originalRemoveMethod = OriginalDefinition.RemoveMethod; return (object?)originalRemoveMethod == null ? null : originalRemoveMethod.AsMember(_containingType); } } internal override FieldSymbol? AssociatedField { get { FieldSymbol? originalAssociatedField = OriginalDefinition.AssociatedField; return (object?)originalAssociatedField == null ? null : originalAssociatedField.AsMember(_containingType); } } internal override bool IsExplicitInterfaceImplementation { get { return OriginalDefinition.IsExplicitInterfaceImplementation; } } //we want to compute this lazily since it may be expensive for the underlying symbol private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations; private OverriddenOrHiddenMembersResult? _lazyOverriddenOrHiddenMembers; public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange( ref _lazyExplicitInterfaceImplementations, ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution), default(ImmutableArray<EventSymbol>)); } return _lazyExplicitInterfaceImplementations; } } internal override bool MustCallMethodsDirectly { get { return OriginalDefinition.MustCallMethodsDirectly; } } internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { if (_lazyOverriddenOrHiddenMembers == null) { Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); } return _lazyOverriddenOrHiddenMembers; } } public override bool IsWindowsRuntimeEvent { get { // A substituted event computes overriding and interface implementation separately // from the original definition, in case the type has changed. However, is should // never be the case that providing type arguments changes a WinRT event to a // non-WinRT event or vice versa, so we'll delegate to the original definition. return OriginalDefinition.IsWindowsRuntimeEvent; } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SubstitutedEventSymbol : WrappedEventSymbol { private readonly SubstitutedNamedTypeSymbol _containingType; private TypeWithAnnotations.Boxed? _lazyType; internal SubstitutedEventSymbol(SubstitutedNamedTypeSymbol containingType, EventSymbol originalDefinition) : base(originalDefinition) { Debug.Assert(originalDefinition.IsDefinition); _containingType = containingType; } public override TypeWithAnnotations TypeWithAnnotations { get { if (_lazyType == null) { var type = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations); Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null); } return _lazyType.Value; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override EventSymbol OriginalDefinition { get { return _underlyingEvent; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return OriginalDefinition.GetAttributes(); } public override MethodSymbol? AddMethod { get { MethodSymbol? originalAddMethod = OriginalDefinition.AddMethod; return (object?)originalAddMethod == null ? null : originalAddMethod.AsMember(_containingType); } } public override MethodSymbol? RemoveMethod { get { MethodSymbol? originalRemoveMethod = OriginalDefinition.RemoveMethod; return (object?)originalRemoveMethod == null ? null : originalRemoveMethod.AsMember(_containingType); } } internal override FieldSymbol? AssociatedField { get { FieldSymbol? originalAssociatedField = OriginalDefinition.AssociatedField; return (object?)originalAssociatedField == null ? null : originalAssociatedField.AsMember(_containingType); } } internal override bool IsExplicitInterfaceImplementation { get { return OriginalDefinition.IsExplicitInterfaceImplementation; } } //we want to compute this lazily since it may be expensive for the underlying symbol private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations; private OverriddenOrHiddenMembersResult? _lazyOverriddenOrHiddenMembers; public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get { if (_lazyExplicitInterfaceImplementations.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange( ref _lazyExplicitInterfaceImplementations, ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution), default(ImmutableArray<EventSymbol>)); } return _lazyExplicitInterfaceImplementations; } } internal override bool MustCallMethodsDirectly { get { return OriginalDefinition.MustCallMethodsDirectly; } } internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { if (_lazyOverriddenOrHiddenMembers == null) { Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); } return _lazyOverriddenOrHiddenMembers; } } public override bool IsWindowsRuntimeEvent { get { // A substituted event computes overriding and interface implementation separately // from the original definition, in case the type has changed. However, is should // never be the case that providing type arguments changes a WinRT event to a // non-WinRT event or vice versa, so we'll delegate to the original definition. return OriginalDefinition.IsWindowsRuntimeEvent; } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.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.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForOperatorsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { public static bool operator +(C c1, C c2) { [||]Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) { [||]Bar(); } }", @"class C { public static bool operator +(C c1, C c2) => Bar(); }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) { [||]Bar(); } }", @"class C { public static bool operator +(C c1, C c2) => Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedInLambda() { await TestMissingAsync( @"class C { public static bool operator +(C c1, C c2) { return () => { [||] }; } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { public static bool operator +(C c1, C c2) => [||]Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) => [||]Bar(); }", @"class C { public static bool operator +(C c1, C c2) { return Bar(); } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) => [||]Bar(); }", @"class C { public static bool operator +(C c1, C c2) { return Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
// Licensed to the .NET Foundation under one or more 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.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForOperatorsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { public static bool operator +(C c1, C c2) { [||]Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) { [||]Bar(); } }", @"class C { public static bool operator +(C c1, C c2) => Bar(); }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) { [||]Bar(); } }", @"class C { public static bool operator +(C c1, C c2) => Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedInLambda() { await TestMissingAsync( @"class C { public static bool operator +(C c1, C c2) { return () => { [||] }; } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { public static bool operator +(C c1, C c2) => [||]Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) => [||]Bar(); }", @"class C { public static bool operator +(C c1, C c2) { return Bar(); } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public static bool operator +(C c1, C c2) => [||]Bar(); }", @"class C { public static bool operator +(C c1, C c2) { return Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/TestUtilities/RenameTracking/MockPreviewDialogService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking { [ExportWorkspaceService(typeof(IPreviewDialogService), ServiceLayer.Test), Shared, PartNotDiscoverable] internal class MockPreviewDialogService : IPreviewDialogService, IWorkspaceServiceFactory { public bool ReturnsNull; public bool Called; public string Title; public string HelpString; public string Description; public string TopLevelName; public Glyph TopLevelGlyph; public bool ShowCheckBoxes; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockPreviewDialogService() { } public Solution PreviewChanges(string title, string helpString, string description, string topLevelName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, bool showCheckBoxes = true) { Called = true; Title = title; HelpString = helpString; Description = description; TopLevelName = topLevelName; TopLevelGlyph = topLevelGlyph; ShowCheckBoxes = showCheckBoxes; return ReturnsNull ? null : newSolution; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => this; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking { [ExportWorkspaceService(typeof(IPreviewDialogService), ServiceLayer.Test), Shared, PartNotDiscoverable] internal class MockPreviewDialogService : IPreviewDialogService, IWorkspaceServiceFactory { public bool ReturnsNull; public bool Called; public string Title; public string HelpString; public string Description; public string TopLevelName; public Glyph TopLevelGlyph; public bool ShowCheckBoxes; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockPreviewDialogService() { } public Solution PreviewChanges(string title, string helpString, string description, string topLevelName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, bool showCheckBoxes = true) { Called = true; Title = title; HelpString = helpString; Description = description; TopLevelName = topLevelName; TopLevelGlyph = topLevelGlyph; ShowCheckBoxes = showCheckBoxes; return ReturnsNull ? null : newSolution; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => this; } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicQuickInfo.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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicQuickInfo : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicQuickInfo(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicQuickInfo)) { } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.QuickInfo)] public void QuickInfo1() { SetUpEditor(@" ''' <summary>Hello!</summary> Class Program Sub Main(ByVal args As String$$()) End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Class System.String\r\nRepresents text as a sequence of UTF-16 code units.To browse the .NET Framework source code for this type, see the Reference Source.", VisualStudio.Editor.GetQuickInfo()); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public void International() { SetUpEditor(@" ''' <summary> ''' This is an XML doc comment defined in code. ''' </summary> Class العربية123 Shared Sub Goo() Dim goo as العربية123$$ End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal(@"Class TestProj.العربية123 This is an XML doc comment defined in code.", VisualStudio.Editor.GetQuickInfo()); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicQuickInfo : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicQuickInfo(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicQuickInfo)) { } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.QuickInfo)] public void QuickInfo1() { SetUpEditor(@" ''' <summary>Hello!</summary> Class Program Sub Main(ByVal args As String$$()) End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal("Class System.String\r\nRepresents text as a sequence of UTF-16 code units.To browse the .NET Framework source code for this type, see the Reference Source.", VisualStudio.Editor.GetQuickInfo()); } [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public void International() { SetUpEditor(@" ''' <summary> ''' This is an XML doc comment defined in code. ''' </summary> Class العربية123 Shared Sub Goo() Dim goo as العربية123$$ End Sub End Class"); VisualStudio.Editor.InvokeQuickInfo(); Assert.Equal(@"Class TestProj.العربية123 This is an XML doc comment defined in code.", VisualStudio.Editor.GetQuickInfo()); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/Core/Implementation/ExtractInterface/AbstractExtractInterfaceCommandHandler.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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.ExtractInterface { internal abstract class AbstractExtractInterfaceCommandHandler : ICommandHandler<ExtractInterfaceCommandArgs> { private readonly IThreadingContext _threadingContext; protected AbstractExtractInterfaceCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public string DisplayName => EditorFeaturesResources.Extract_Interface; public CommandState GetCommandState(ExtractInterfaceCommandArgs args) => IsAvailable(args.SubjectBuffer, out _) ? CommandState.Available : CommandState.Unspecified; public bool ExecuteCommand(ExtractInterfaceCommandArgs args, CommandExecutionContext context) { using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Extract_Interface)) { var subjectBuffer = args.SubjectBuffer; if (!IsAvailable(subjectBuffer, out var workspace)) { return false; } var caretPoint = args.TextView.GetCaretPoint(subjectBuffer); if (!caretPoint.HasValue) { return false; } var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( context.OperationContext, _threadingContext); if (document == null) { return false; } // We are about to show a modal UI dialog so we should take over the command execution // wait context. That means the command system won't attempt to show its own wait dialog // and also will take it into consideration when measuring command handling duration. context.OperationContext.TakeOwnership(); var extractInterfaceService = document.GetLanguageService<AbstractExtractInterfaceService>(); var result = _threadingContext.JoinableTaskFactory.Run(() => extractInterfaceService.ExtractInterfaceAsync( document, caretPoint.Value.Position, (errorMessage, severity) => workspace.Services.GetService<INotificationService>().SendNotification(errorMessage, severity: severity), CancellationToken.None)); if (result == null || !result.Succeeded) { return true; } if (!document.Project.Solution.Workspace.TryApplyChanges(result.UpdatedSolution)) { // TODO: handle failure return true; } // TODO: Use a threaded-wait-dialog here so we can cancel navigation. var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); navigationService.TryNavigateToPosition(workspace, result.NavigationDocumentId, 0, CancellationToken.None); return true; } } private static bool IsAvailable(ITextBuffer subjectBuffer, out Workspace workspace) => subjectBuffer.TryGetWorkspace(out workspace) && workspace.CanApplyChange(ApplyChangesKind.AddDocument) && workspace.CanApplyChange(ApplyChangesKind.ChangeDocument) && subjectBuffer.SupportsRefactorings(); } }
// Licensed to the .NET Foundation under one or more 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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.ExtractInterface { internal abstract class AbstractExtractInterfaceCommandHandler : ICommandHandler<ExtractInterfaceCommandArgs> { private readonly IThreadingContext _threadingContext; protected AbstractExtractInterfaceCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public string DisplayName => EditorFeaturesResources.Extract_Interface; public CommandState GetCommandState(ExtractInterfaceCommandArgs args) => IsAvailable(args.SubjectBuffer, out _) ? CommandState.Available : CommandState.Unspecified; public bool ExecuteCommand(ExtractInterfaceCommandArgs args, CommandExecutionContext context) { using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Extract_Interface)) { var subjectBuffer = args.SubjectBuffer; if (!IsAvailable(subjectBuffer, out var workspace)) { return false; } var caretPoint = args.TextView.GetCaretPoint(subjectBuffer); if (!caretPoint.HasValue) { return false; } var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( context.OperationContext, _threadingContext); if (document == null) { return false; } // We are about to show a modal UI dialog so we should take over the command execution // wait context. That means the command system won't attempt to show its own wait dialog // and also will take it into consideration when measuring command handling duration. context.OperationContext.TakeOwnership(); var extractInterfaceService = document.GetLanguageService<AbstractExtractInterfaceService>(); var result = _threadingContext.JoinableTaskFactory.Run(() => extractInterfaceService.ExtractInterfaceAsync( document, caretPoint.Value.Position, (errorMessage, severity) => workspace.Services.GetService<INotificationService>().SendNotification(errorMessage, severity: severity), CancellationToken.None)); if (result == null || !result.Succeeded) { return true; } if (!document.Project.Solution.Workspace.TryApplyChanges(result.UpdatedSolution)) { // TODO: handle failure return true; } // TODO: Use a threaded-wait-dialog here so we can cancel navigation. var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); navigationService.TryNavigateToPosition(workspace, result.NavigationDocumentId, 0, CancellationToken.None); return true; } } private static bool IsAvailable(ITextBuffer subjectBuffer, out Workspace workspace) => subjectBuffer.TryGetWorkspace(out workspace) && workspace.CanApplyChange(ApplyChangesKind.AddDocument) && workspace.CanApplyChange(ApplyChangesKind.ChangeDocument) && subjectBuffer.SupportsRefactorings(); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_NativeInteger.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 System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_NativeInteger : CSharpTestBase { private static readonly SymbolDisplayFormat FormatWithSpecialTypes = SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes); [Fact] public void EmptyProject() { var source = @""; var comp = CreateCompilation(source); var expected = @""; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void ExplicitAttribute_FromSource() { var source = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(new[] { NativeIntegerAttributeDefinition, source }); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger] System.UIntPtr[] F2 "; CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute"); Assert.NotNull(attributeType); AssertNativeIntegerAttributes(module, expected); }); } [Fact] public void ExplicitAttribute_FromMetadata() { var comp = CreateCompilation(NativeIntegerAttributeDefinition); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"public class Program { public nint F1; public nuint[] F2; }"; comp = CreateCompilation(source, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger] System.UIntPtr[] F2 "; CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute"); Assert.Null(attributeType); AssertNativeIntegerAttributes(module, expected); }); } [Fact] public void ExplicitAttribute_MissingEmptyConstructor() { var source1 = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { public NativeIntegerAttribute(bool[] flags) { } } }"; var source2 = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nint F1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nuint[] F2; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20)); } [Fact] public void ExplicitAttribute_MissingConstructor() { var source1 = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { } }"; var source2 = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nint F1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nuint[] F2; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20)); } [Fact] public void ExplicitAttribute_ReferencedInSource() { var sourceAttribute = @"namespace System.Runtime.CompilerServices { internal class NativeIntegerAttribute : Attribute { internal NativeIntegerAttribute() { } internal NativeIntegerAttribute(bool[] flags) { } } }"; var source = @"#pragma warning disable 67 #pragma warning disable 169 using System; using System.Runtime.CompilerServices; [NativeInteger] class Program { [NativeInteger] IntPtr F; [NativeInteger] event EventHandler E; [NativeInteger] object P { get; } [NativeInteger(new[] { false, true })] static UIntPtr[] M1() => throw null; [return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null; static void M3([NativeInteger]object arg) { } }"; var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular8); verifyDiagnostics(comp); comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular9); verifyDiagnostics(comp); static void verifyDiagnostics(CSharpCompilation comp) { comp.VerifyDiagnostics( // (5,2): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] class Program Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 2), // (7,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] IntPtr F; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 6), // (8,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] event EventHandler E; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(8, 6), // (9,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] object P { get; } Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(9, 6), // (11,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger(new[] { false, true })").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(11, 14), // (12,21): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // static void M3([NativeInteger]object arg) { } Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(12, 21)); } } [Fact] public void MissingAttributeUsageAttribute() { var source = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute); comp.VerifyEmitDiagnostics( // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1)); } [Fact] public void Metadata_ZeroElements() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0] .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0] ret } .method public static void F1(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0] ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<System.IntPtr, System.UIntPtr>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language // B.F0(default, default); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(new A<System.IntPtr, System.UIntPtr>()); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11)); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language // B.F0(default, default); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(new A<System.IntPtr, System.UIntPtr>()); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11)); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0( x, y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(? x, ? y) [NativeInteger({ })] ? x [NativeInteger({ })] ? y void F1(? a) [NativeInteger({ })] ? a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_OneElementFalse() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F1(class A<int32, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F2(class A<native int, uint32> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<int, System.UIntPtr>()); B.F2(new A<System.IntPtr, uint>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<System.IntPtr, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(System.IntPtr x, System.UIntPtr y) [NativeInteger({ False })] System.IntPtr x [NativeInteger({ False })] System.UIntPtr y void F1(A<System.Int32, System.UIntPtr> a) [NativeInteger({ False })] A<System.Int32, System.UIntPtr> a void F2(A<System.IntPtr, System.UInt32> a) [NativeInteger({ False })] A<System.IntPtr, System.UInt32> a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_OneElementTrue() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } ret } .method public static void F1(class A<int32, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } ret } .method public static void F2(class A<native int, uint32> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<int, nuint>()); B.F2(new A<nint, uint>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,25): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // B.F1(new A<int, nuint>()); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 25), // (7,20): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // B.F2(new A<nint, uint>()); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(7, 20)); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0(nint x, nuint y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1(A<int, nuint> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<nint, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(System.IntPtr x, System.UIntPtr y) [NativeInteger({ True })] System.IntPtr x [NativeInteger({ True })] System.UIntPtr y void F1(A<System.Int32, System.UIntPtr> a) [NativeInteger({ True })] A<System.Int32, System.UIntPtr> a void F2(A<System.IntPtr, System.UInt32> a) [NativeInteger({ True })] A<System.IntPtr, System.UInt32> a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_AllFalse() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F1(class A<int32, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F2(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 00 00 00 ) // new[] { false, false } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<int, System.UIntPtr>()); B.F2(new A<System.IntPtr, System.UIntPtr>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<System.IntPtr, System.UIntPtr> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(System.IntPtr x, System.UIntPtr y) [NativeInteger({ False })] System.IntPtr x [NativeInteger({ False })] System.UIntPtr y void F1(A<System.Int32, System.UIntPtr> a) [NativeInteger({ False })] A<System.Int32, System.UIntPtr> a void F2(A<System.IntPtr, System.UIntPtr> a) [NativeInteger({ False, False })] A<System.IntPtr, System.UIntPtr> a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_TooFewAndTooManyTransformFlags() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { } .class public B { .method public static void F(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 ) // no array, too few ret } .method public static void F0(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0], too few ret } .method public static void F1(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }, too few ret } .method public static void F2(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }, valid ret } .method public static void F3(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 ) // new[] { false, true, true }, too many ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F(A<nint, nuint> a) { B.F(a); B.F0(a); B.F1(a); B.F2(a); B.F3(a); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,21): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F(A<nint, nuint> a) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(3, 21), // (3,27): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F(A<nint, nuint> a) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(3, 27), // (5,11): error CS0570: 'B.F(?)' is not supported by the language // B.F(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F0(?)' is not supported by the language // B.F0(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11), // (9,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11)); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F(?)' is not supported by the language // B.F(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F0(?)' is not supported by the language // B.F0(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11), // (9,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11)); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F( a)", type.GetMember("F").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F0( a)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<System.IntPtr, nuint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F3( a)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F(? a) [NativeInteger] ? a void F0(? a) [NativeInteger({ })] ? a void F1(? a) [NativeInteger({ True })] ? a void F2(A<System.IntPtr, System.UIntPtr> a) [NativeInteger({ False, True })] A<System.IntPtr, System.UIntPtr> a void F3(? a) [NativeInteger({ False, True, True })] ? a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_UnexpectedTarget() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class A<T> { } .class public B { .method public static void F1(int32 w) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public static void F2(object[] x) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true } ret } .method public static void F3(class A<class B> y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true } ret } .method public static void F4(native int[] z) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) // new[] { true, true } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F1(default); B.F2(default); B.F3(default); B.F4(default); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F2(?)' is not supported by the language // B.F2(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11), // (8,11): error CS0570: 'B.F4(?)' is not supported by the language // B.F4(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11) ); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F2(?)' is not supported by the language // B.F2(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11), // (8,11): error CS0570: 'B.F4(?)' is not supported by the language // B.F4(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11) ); var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F1( w)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2( x)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F3( y)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F4( z)", type.GetMember("F4").ToDisplayString(FormatWithSpecialTypes)); var expected = @" B void F1(? w) [NativeInteger] ? w void F2(? x) [NativeInteger({ False, True })] ? x void F3(? y) [NativeInteger({ False, True })] ? y void F4(? z) [NativeInteger({ True, True })] ? z "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } [Fact] public void EmitAttribute_BaseClass() { var source = @"public class A<T, U> { } public class B : A<nint, nuint[]> { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"[NativeInteger({ True, True })] B "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_Interface() { var source = @"public interface I<T> { } public class A : I<(nint, nuint[])> { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, validator: assembly => { var reader = assembly.GetMetadataReader(); var typeDef = GetTypeDefinitionByName(reader, "A"); var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single()); AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])"); }); } [Fact] public void EmitAttribute_AllTypes() { var source = @"public enum E { } public class C<T> { public delegate void D<T>(); public enum F { } public struct S<U> { } public interface I<U> { } public C<T>.S<nint> F1; public C<nuint>.I<T> F2; public C<E>.D<nint> F3; public C<nuint>.D<dynamic> F4; public C<C<nuint>.D<System.IntPtr>>.F F5; public C<C<System.UIntPtr>.F>.D<nint> F6; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"C<T> [NativeInteger] C<T>.S<System.IntPtr> F1 [NativeInteger] C<System.UIntPtr>.I<T> F2 [NativeInteger] C<E>.D<System.IntPtr> F3 [NativeInteger] C<System.UIntPtr>.D<dynamic> F4 [NativeInteger({ True, False })] C<C<System.UIntPtr>.D<System.IntPtr>>.F F5 [NativeInteger({ False, True })] C<C<System.UIntPtr>.F>.D<System.IntPtr> F6 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_ErrorType() { var source1 = @"public class A { } public class B<T> { }"; var comp = CreateCompilation(source1, assemblyName: "95d36b13-f2e1-495d-9ab6-62e8cc63ac22"); var ref1 = comp.EmitToImageReference(); var source2 = @"public class C<T, U> { } public class D { public B<nint> F1; public C<nint, A> F2; }"; comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9); var ref2 = comp.EmitToImageReference(); var source3 = @"class Program { static void Main() { var d = new D(); _ = d.F1; _ = d.F2; } }"; comp = CreateCompilation(source3, references: new[] { ref2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,15): error CS0012: The type 'B<>' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // _ = d.F1; Diagnostic(ErrorCode.ERR_NoTypeDef, "F1").WithArguments("B<>", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 15), // (7,15): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // _ = d.F2; Diagnostic(ErrorCode.ERR_NoTypeDef, "F2").WithArguments("A", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 15)); } [Fact] public void EmitAttribute_Fields() { var source = @"public class Program { public nint F1; public (System.IntPtr, nuint[]) F2; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F2 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_MethodReturnType() { var source = @"public class Program { public (System.IntPtr, nuint[]) F() => default; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F() "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_MethodParameters() { var source = @"public class Program { public void F(nint x, nuint y) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program void F(System.IntPtr x, System.UIntPtr y) [NativeInteger] System.IntPtr x [NativeInteger] System.UIntPtr y "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_PropertyType() { var source = @"public class Program { public (System.IntPtr, nuint[]) P => default; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P { get; } [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P.get "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_PropertyParameters() { var source = @"public class Program { public object this[nint x, (nuint[], System.IntPtr) y] => null; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y] { get; } [NativeInteger] System.IntPtr x [NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y].get [NativeInteger] System.IntPtr x [NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_EventType() { var source = @"using System; public class Program { public event EventHandler<nuint[]> E; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger] event System.EventHandler<System.UIntPtr[]> E void E.add [NativeInteger] System.EventHandler<System.UIntPtr[]> value void E.remove [NativeInteger] System.EventHandler<System.UIntPtr[]> value "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_OperatorReturnType() { var source = @"public class C { public static nint operator+(C a, C b) => 0; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"C [NativeInteger] System.IntPtr operator +(C a, C b) "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_OperatorParameters() { var source = @"public class C { public static C operator+(C a, nuint[] b) => a; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"C C operator +(C a, System.UIntPtr[] b) [NativeInteger] System.UIntPtr[] b "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_DelegateReturnType() { var source = @"public delegate nint D();"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"D [NativeInteger] System.IntPtr Invoke() [NativeInteger] System.IntPtr EndInvoke(System.IAsyncResult result) "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_DelegateParameters() { var source = @"public delegate void D(nint x, nuint[] y);"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"D void Invoke(System.IntPtr x, System.UIntPtr[] y) [NativeInteger] System.IntPtr x [NativeInteger] System.UIntPtr[] y System.IAsyncResult BeginInvoke(System.IntPtr x, System.UIntPtr[] y, System.AsyncCallback callback, System.Object @object) [NativeInteger] System.IntPtr x [NativeInteger] System.UIntPtr[] y "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_Constraint() { var source = @"public class A<T> { } public class B<T> where T : A<nint> { } public class C<T> where T : A<nuint[]> { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var type = comp.GetMember<NamedTypeSymbol>("B"); Assert.Equal("A<nint>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes)); type = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal("A<nuint[]>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes)); static TypeWithAnnotations getConstraintType(NamedTypeSymbol type) => type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0]; } [Fact] public void EmitAttribute_LambdaReturnType() { var source = @"using System; class Program { static object M() { Func<nint> f = () => (nint)2; return f(); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<M>b__0_0"); AssertNativeIntegerAttribute(method.GetReturnTypeAttributes()); }); } [Fact] public void EmitAttribute_LambdaParameters() { var source = @"using System; class Program { static void M() { Action<nuint[]> a = (nuint[] n) => { }; a(null); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<M>b__0_0"); AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes()); }); } [Fact] public void EmitAttribute_LocalFunctionReturnType() { var source = @"class Program { static object M() { nint L() => (nint)2; return L(); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0"); AssertNativeIntegerAttribute(method.GetReturnTypeAttributes()); AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.CompilerGeneratedAttribute"); }); } [Fact] public void EmitAttribute_LocalFunctionParameters() { var source = @"class Program { static void M() { void L(nuint[] n) { } L(null); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0"); AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes()); }); } [Fact] public void EmitAttribute_Lambda_NetModule() { var source = @"class Program { static void Main() { var a1 = (nint n) => { }; a1(1); var a2 = nuint[] () => null; a2(); } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseModule); comp.VerifyDiagnostics( // (5,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // var a1 = (nint n) => { }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 19), // (7,29): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // var a2 = nuint[] () => null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "=>").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 29)); } [Fact] public void EmitAttribute_LocalFunction_NetModule() { var source = @"class Program { static void Main() { void L1(nint n) { }; L1(1); nuint[] L2() => null; L2(); } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseModule); comp.VerifyDiagnostics( // (5,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // void L1(nint n) { }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 17), // (7,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // nuint[] L2() => null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nuint[]").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 9)); } [Fact] public void EmitAttribute_Lambda_MissingAttributeConstructor() { var sourceA = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { private NativeIntegerAttribute() { } } }"; var sourceB = @"class Program { static void Main() { var a1 = (nint n) => { }; a1(1); var a2 = nuint[] () => null; a2(); } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // var a1 = (nint n) => { }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(5, 19), // (7,29): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // var a2 = nuint[] () => null; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(7, 29)); } [Fact] public void EmitAttribute_LocalFunction_MissingAttributeConstructor() { var sourceA = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { private NativeIntegerAttribute() { } } }"; var sourceB = @"class Program { static void Main() { void L1(nint n) { }; L1(1); nuint[] L2() => null; L2(); } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // void L1(nint n) { }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(5, 17), // (7,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // nuint[] L2() => null; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nuint[]").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(7, 9)); } [Fact] public void EmitAttribute_LocalFunctionConstraints() { var source = @"interface I<T> { } class Program { static void M() { void L<T>() where T : I<nint> { } L<I<nint>>(); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, symbolValidator: module => { var assembly = module.ContainingAssembly; Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NativeIntegerAttribute")); }); } [Fact] public void EmitAttribute_Nested() { var source = @"public class A<T> { public class B<U> { } } unsafe public class Program { public nint F1; public nuint[] F2; public nint* F3; public A<nint>.B<nuint> F4; public (nint, nuint) F5; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger] System.UIntPtr[] F2 [NativeInteger] System.IntPtr* F3 [NativeInteger({ True, True })] A<System.IntPtr>.B<System.UIntPtr> F4 [NativeInteger({ True, True })] (System.IntPtr, System.UIntPtr) F5 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_LongTuples_01() { var source = @"public class A<T> { } unsafe public class B { public A<(object, (nint, nuint, nint[], nuint, nint, nuint*[], nint, System.UIntPtr))> F1; public A<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)> F2; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll); var expected = @"B [NativeInteger({ True, True, True, True, True, True, True, False })] A<(System.Object, (System.IntPtr, System.UIntPtr, System.IntPtr[], System.UIntPtr, System.IntPtr, System.UIntPtr*[], System.IntPtr, System.UIntPtr))> F1 [NativeInteger({ True, True, True, False, True, True })] A<(System.IntPtr, System.Object, System.UIntPtr[], System.Object, System.IntPtr, System.Object, (System.IntPtr, System.UIntPtr), System.Object, System.UIntPtr)> F2 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_LongTuples_02() { var source1 = @"public interface IA { } public interface IB<T> { } public class C : IA, IB<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)> { }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, validator: assembly => { var reader = assembly.GetMetadataReader(); var typeDef = GetTypeDefinitionByName(reader, "C"); var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().ElementAt(1)); var customAttributes = interfaceImpl.GetCustomAttributes(); AssertAttributes(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])"); var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])"); AssertEx.Equal(ImmutableArray.Create(true, true, true, false, true, true), reader.ReadBoolArray(customAttribute.Value)); }); var ref1 = comp.EmitToImageReference(); var source2 = @"class Program { static void Main() { IA a = new C(); _ = a; } }"; comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(45519, "https://github.com/dotnet/roslyn/issues/45519")] public void EmitAttribute_PartialMethods() { var source = @"public partial class Program { static partial void F1(System.IntPtr x); static partial void F2(System.UIntPtr x) { } static partial void F1(nint x) { } static partial void F2(nuint x); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9); var expected = @"Program void F2(System.UIntPtr x) [NativeInteger] System.UIntPtr x "; AssertNativeIntegerAttributes(comp, expected); comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(6), parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): warning CS8826: Partial method declarations 'void Program.F2(nuint x)' and 'void Program.F2(UIntPtr x)' have signature differences. // static partial void F2(System.UIntPtr x) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F2").WithArguments("void Program.F2(nuint x)", "void Program.F2(UIntPtr x)").WithLocation(4, 25), // (5,25): warning CS8826: Partial method declarations 'void Program.F1(IntPtr x)' and 'void Program.F1(nint x)' have signature differences. // static partial void F1(nint x) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F1").WithArguments("void Program.F1(IntPtr x)", "void Program.F1(nint x)").WithLocation(5, 25)); } // Shouldn't depend on [NullablePublicOnly]. [Fact] public void NoPublicMembers() { var source = @"class A<T, U> { } class B : A<System.UIntPtr, nint> { }"; var comp = CreateCompilation( source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9.WithNullablePublicOnly()); var expected = @"[NativeInteger({ False, True })] B "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void AttributeUsage() { var source = @"public class Program { public nint F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute"); AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo(); Assert.False(attributeUsage.Inherited); Assert.False(attributeUsage.AllowMultiple); Assert.True(attributeUsage.HasValidAttributeTargets); var expectedTargets = AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue; Assert.Equal(expectedTargets, attributeUsage.ValidTargets); }); } [Fact] public void AttributeFieldExists() { var source = @"public class Program { public nint F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, symbolValidator: module => { var type = module.ContainingAssembly.GetTypeByMetadataName("Program"); var member = type.GetMembers("F").Single(); var attributes = member.GetAttributes(); AssertNativeIntegerAttribute(attributes); var attribute = GetNativeIntegerAttribute(attributes); var field = attribute.AttributeClass.GetField("TransformFlags"); Assert.Equal("System.Boolean[]", field.TypeWithAnnotations.ToTestDisplayString()); }); } [Fact] public void NestedNativeIntegerWithPrecedingType() { var comp = CompileAndVerify(@" class C<T, U, V> { public C<dynamic, T, nint> F0; public C<dynamic, nint, System.IntPtr> F1; public C<dynamic, nuint, System.UIntPtr> F2; public C<T, nint, System.IntPtr> F3; public C<T, nuint, System.UIntPtr> F4; } ", options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator); static void symbolValidator(ModuleSymbol module) { var expectedAttributes = @" C<T, U, V> [NativeInteger] C<dynamic, T, System.IntPtr> F0 [NativeInteger({ True, False })] C<dynamic, System.IntPtr, System.IntPtr> F1 [NativeInteger({ True, False })] C<dynamic, System.UIntPtr, System.UIntPtr> F2 [NativeInteger({ True, False })] C<T, System.IntPtr, System.IntPtr> F3 [NativeInteger({ True, False })] C<T, System.UIntPtr, System.UIntPtr> F4 "; AssertNativeIntegerAttributes(module, expectedAttributes); var c = module.GlobalNamespace.GetTypeMember("C"); assert("C<dynamic, T, nint>", "F0"); assert("C<dynamic, nint, System.IntPtr>", "F1"); assert("C<dynamic, nuint, System.UIntPtr>", "F2"); assert("C<T, nint, System.IntPtr>", "F3"); assert("C<T, nuint, System.UIntPtr>", "F4"); void assert(string expectedType, string fieldName) { Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString()); } } } [Fact] public void FunctionPointersWithNativeIntegerTypes() { var comp = CompileAndVerify(@" unsafe class C { public delegate*<nint, object, object> F0; public delegate*<nint, nint, nint> F1; public delegate*<System.IntPtr, System.IntPtr, nint> F2; public delegate*<nint, System.IntPtr, System.IntPtr> F3; public delegate*<System.IntPtr, nint, System.IntPtr> F4; public delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint> F5; public delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6; public delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr> F7; public delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>> F8; } ", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator); static void symbolValidator(ModuleSymbol module) { var expectedAttributes = @" C [NativeInteger] delegate*<System.IntPtr, System.Object, System.Object> F0 [NativeInteger({ True, True, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F1 [NativeInteger({ True, False, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F2 [NativeInteger({ False, True, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F3 [NativeInteger({ False, False, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F4 [NativeInteger({ True, False, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F5 [NativeInteger({ False, False, False, True })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6 [NativeInteger({ False, True, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F7 [NativeInteger({ False, False, True, False })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F8 "; AssertNativeIntegerAttributes(module, expectedAttributes); var c = module.GlobalNamespace.GetTypeMember("C"); assert("delegate*<nint, System.Object, System.Object>", "F0"); assert("delegate*<nint, nint, nint>", "F1"); assert("delegate*<System.IntPtr, System.IntPtr, nint>", "F2"); assert("delegate*<nint, System.IntPtr, System.IntPtr>", "F3"); assert("delegate*<System.IntPtr, nint, System.IntPtr>", "F4"); assert("delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint>", "F5"); assert("delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>>", "F6"); assert("delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr>", "F7"); assert("delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>>", "F8"); void assert(string expectedType, string fieldName) { var field = c.GetField(fieldName); FunctionPointerUtilities.CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type); Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString()); } } } private static TypeDefinition GetTypeDefinitionByName(MetadataReader reader, string name) { return reader.GetTypeDefinition(reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name))); } private static string GetAttributeConstructorName(MetadataReader reader, CustomAttributeHandle handle) { return reader.Dump(reader.GetCustomAttribute(handle).Constructor); } private static CustomAttribute GetAttributeByConstructorName(MetadataReader reader, CustomAttributeHandleCollection handles, string name) { return reader.GetCustomAttribute(handles.FirstOrDefault(h => GetAttributeConstructorName(reader, h) == name)); } private static void AssertAttributes(MetadataReader reader, CustomAttributeHandleCollection handles, params string[] expectedNames) { var actualNames = handles.Select(h => GetAttributeConstructorName(reader, h)).ToArray(); AssertEx.Equal(expectedNames, actualNames); } private static void AssertNoNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) { AssertAttributes(attributes); } private static void AssertNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) { AssertAttributes(attributes, "System.Runtime.CompilerServices.NativeIntegerAttribute"); } private static void AssertAttributes(ImmutableArray<CSharpAttributeData> attributes, params string[] expectedNames) { var actualNames = attributes.Select(a => a.AttributeClass.ToTestDisplayString()).ToArray(); AssertEx.Equal(expectedNames, actualNames); } private static void AssertNoNativeIntegerAttributes(CSharpCompilation comp) { var image = comp.EmitToArray(); using (var reader = new PEReader(image)) { var metadataReader = reader.GetMetadataReader(); var attributes = metadataReader.GetCustomAttributeRows().Select(metadataReader.GetCustomAttributeName).ToArray(); Assert.False(attributes.Contains("NativeIntegerAttribute")); } } private void AssertNativeIntegerAttributes(CSharpCompilation comp, string expected) { CompileAndVerify(comp, symbolValidator: module => AssertNativeIntegerAttributes(module, expected)); } private static void AssertNativeIntegerAttributes(ModuleSymbol module, string expected) { var actual = NativeIntegerAttributesVisitor.GetString((PEModuleSymbol)module); AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual); } private static CSharpAttributeData GetNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) { return attributes.Single(a => a.AttributeClass.ToTestDisplayString() == "System.Runtime.CompilerServices.NativeIntegerAttribute"); } } }
// Licensed to the .NET Foundation under one or more 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 System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_NativeInteger : CSharpTestBase { private static readonly SymbolDisplayFormat FormatWithSpecialTypes = SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes); [Fact] public void EmptyProject() { var source = @""; var comp = CreateCompilation(source); var expected = @""; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void ExplicitAttribute_FromSource() { var source = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(new[] { NativeIntegerAttributeDefinition, source }); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger] System.UIntPtr[] F2 "; CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute"); Assert.NotNull(attributeType); AssertNativeIntegerAttributes(module, expected); }); } [Fact] public void ExplicitAttribute_FromMetadata() { var comp = CreateCompilation(NativeIntegerAttributeDefinition); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"public class Program { public nint F1; public nuint[] F2; }"; comp = CreateCompilation(source, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger] System.UIntPtr[] F2 "; CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute"); Assert.Null(attributeType); AssertNativeIntegerAttributes(module, expected); }); } [Fact] public void ExplicitAttribute_MissingEmptyConstructor() { var source1 = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { public NativeIntegerAttribute(bool[] flags) { } } }"; var source2 = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nint F1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nuint[] F2; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20)); } [Fact] public void ExplicitAttribute_MissingConstructor() { var source1 = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { } }"; var source2 = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nint F1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // public nuint[] F2; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20)); } [Fact] public void ExplicitAttribute_ReferencedInSource() { var sourceAttribute = @"namespace System.Runtime.CompilerServices { internal class NativeIntegerAttribute : Attribute { internal NativeIntegerAttribute() { } internal NativeIntegerAttribute(bool[] flags) { } } }"; var source = @"#pragma warning disable 67 #pragma warning disable 169 using System; using System.Runtime.CompilerServices; [NativeInteger] class Program { [NativeInteger] IntPtr F; [NativeInteger] event EventHandler E; [NativeInteger] object P { get; } [NativeInteger(new[] { false, true })] static UIntPtr[] M1() => throw null; [return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null; static void M3([NativeInteger]object arg) { } }"; var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular8); verifyDiagnostics(comp); comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular9); verifyDiagnostics(comp); static void verifyDiagnostics(CSharpCompilation comp) { comp.VerifyDiagnostics( // (5,2): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] class Program Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 2), // (7,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] IntPtr F; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 6), // (8,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] event EventHandler E; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(8, 6), // (9,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [NativeInteger] object P { get; } Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(9, 6), // (11,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // [return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger(new[] { false, true })").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(11, 14), // (12,21): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage. // static void M3([NativeInteger]object arg) { } Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(12, 21)); } } [Fact] public void MissingAttributeUsageAttribute() { var source = @"public class Program { public nint F1; public nuint[] F2; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute); comp.VerifyEmitDiagnostics( // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1)); } [Fact] public void Metadata_ZeroElements() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0] .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0] ret } .method public static void F1(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0] ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<System.IntPtr, System.UIntPtr>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language // B.F0(default, default); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(new A<System.IntPtr, System.UIntPtr>()); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11)); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language // B.F0(default, default); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(new A<System.IntPtr, System.UIntPtr>()); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11)); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0( x, y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(? x, ? y) [NativeInteger({ })] ? x [NativeInteger({ })] ? y void F1(? a) [NativeInteger({ })] ? a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_OneElementFalse() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F1(class A<int32, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F2(class A<native int, uint32> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<int, System.UIntPtr>()); B.F2(new A<System.IntPtr, uint>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<System.IntPtr, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(System.IntPtr x, System.UIntPtr y) [NativeInteger({ False })] System.IntPtr x [NativeInteger({ False })] System.UIntPtr y void F1(A<System.Int32, System.UIntPtr> a) [NativeInteger({ False })] A<System.Int32, System.UIntPtr> a void F2(A<System.IntPtr, System.UInt32> a) [NativeInteger({ False })] A<System.IntPtr, System.UInt32> a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_OneElementTrue() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } ret } .method public static void F1(class A<int32, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } ret } .method public static void F2(class A<native int, uint32> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<int, nuint>()); B.F2(new A<nint, uint>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,25): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // B.F1(new A<int, nuint>()); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 25), // (7,20): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // B.F2(new A<nint, uint>()); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(7, 20)); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0(nint x, nuint y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1(A<int, nuint> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<nint, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(System.IntPtr x, System.UIntPtr y) [NativeInteger({ True })] System.IntPtr x [NativeInteger({ True })] System.UIntPtr y void F1(A<System.Int32, System.UIntPtr> a) [NativeInteger({ True })] A<System.Int32, System.UIntPtr> a void F2(A<System.IntPtr, System.UInt32> a) [NativeInteger({ True })] A<System.IntPtr, System.UInt32> a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_AllFalse() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public B { .method public static void F0(native int x, native uint y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } .param [2] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F1(class A<int32, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false } ret } .method public static void F2(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 00 00 00 ) // new[] { false, false } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F0(default, default); B.F1(new A<int, System.UIntPtr>()); B.F2(new A<System.IntPtr, System.UIntPtr>()); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<System.IntPtr, System.UIntPtr> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F0(System.IntPtr x, System.UIntPtr y) [NativeInteger({ False })] System.IntPtr x [NativeInteger({ False })] System.UIntPtr y void F1(A<System.Int32, System.UIntPtr> a) [NativeInteger({ False })] A<System.Int32, System.UIntPtr> a void F2(A<System.IntPtr, System.UIntPtr> a) [NativeInteger({ False, False })] A<System.IntPtr, System.UIntPtr> a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_TooFewAndTooManyTransformFlags() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class public A<T, U> { } .class public B { .method public static void F(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 ) // no array, too few ret } .method public static void F0(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0], too few ret } .method public static void F1(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }, too few ret } .method public static void F2(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }, valid ret } .method public static void F3(class A<native int, native uint> a) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 ) // new[] { false, true, true }, too many ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F(A<nint, nuint> a) { B.F(a); B.F0(a); B.F1(a); B.F2(a); B.F3(a); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,21): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F(A<nint, nuint> a) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(3, 21), // (3,27): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F(A<nint, nuint> a) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(3, 27), // (5,11): error CS0570: 'B.F(?)' is not supported by the language // B.F(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F0(?)' is not supported by the language // B.F0(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11), // (9,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11)); verify(comp); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F(?)' is not supported by the language // B.F(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F0(?)' is not supported by the language // B.F0(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11), // (9,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(a); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11)); verify(comp); static void verify(CSharpCompilation comp) { var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F( a)", type.GetMember("F").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F0( a)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2(A<System.IntPtr, nuint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F3( a)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes)); var expected = @"B void F(? a) [NativeInteger] ? a void F0(? a) [NativeInteger({ })] ? a void F1(? a) [NativeInteger({ True })] ? a void F2(A<System.IntPtr, System.UIntPtr> a) [NativeInteger({ False, True })] A<System.IntPtr, System.UIntPtr> a void F3(? a) [NativeInteger({ False, True, True })] ? a "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } } [Fact] public void Metadata_UnexpectedTarget() { var source0 = @".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class A<T> { } .class public B { .method public static void F1(int32 w) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public static void F2(object[] x) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true } ret } .method public static void F3(class A<class B> y) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true } ret } .method public static void F4(native int[] z) { .param [1] .custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) // new[] { true, true } ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void F() { B.F1(default); B.F2(default); B.F3(default); B.F4(default); } }"; var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F2(?)' is not supported by the language // B.F2(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11), // (8,11): error CS0570: 'B.F4(?)' is not supported by the language // B.F4(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11) ); comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,11): error CS0570: 'B.F1(?)' is not supported by the language // B.F1(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11), // (6,11): error CS0570: 'B.F2(?)' is not supported by the language // B.F2(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11), // (7,11): error CS0570: 'B.F3(?)' is not supported by the language // B.F3(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11), // (8,11): error CS0570: 'B.F4(?)' is not supported by the language // B.F4(default); Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11) ); var type = comp.GetTypeByMetadataName("B"); Assert.Equal("void B.F1( w)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F2( x)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F3( y)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes)); Assert.Equal("void B.F4( z)", type.GetMember("F4").ToDisplayString(FormatWithSpecialTypes)); var expected = @" B void F1(? w) [NativeInteger] ? w void F2(? x) [NativeInteger({ False, True })] ? x void F3(? y) [NativeInteger({ False, True })] ? y void F4(? z) [NativeInteger({ True, True })] ? z "; AssertNativeIntegerAttributes(type.ContainingModule, expected); } [Fact] public void EmitAttribute_BaseClass() { var source = @"public class A<T, U> { } public class B : A<nint, nuint[]> { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"[NativeInteger({ True, True })] B "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_Interface() { var source = @"public interface I<T> { } public class A : I<(nint, nuint[])> { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, validator: assembly => { var reader = assembly.GetMetadataReader(); var typeDef = GetTypeDefinitionByName(reader, "A"); var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single()); AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])"); }); } [Fact] public void EmitAttribute_AllTypes() { var source = @"public enum E { } public class C<T> { public delegate void D<T>(); public enum F { } public struct S<U> { } public interface I<U> { } public C<T>.S<nint> F1; public C<nuint>.I<T> F2; public C<E>.D<nint> F3; public C<nuint>.D<dynamic> F4; public C<C<nuint>.D<System.IntPtr>>.F F5; public C<C<System.UIntPtr>.F>.D<nint> F6; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"C<T> [NativeInteger] C<T>.S<System.IntPtr> F1 [NativeInteger] C<System.UIntPtr>.I<T> F2 [NativeInteger] C<E>.D<System.IntPtr> F3 [NativeInteger] C<System.UIntPtr>.D<dynamic> F4 [NativeInteger({ True, False })] C<C<System.UIntPtr>.D<System.IntPtr>>.F F5 [NativeInteger({ False, True })] C<C<System.UIntPtr>.F>.D<System.IntPtr> F6 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_ErrorType() { var source1 = @"public class A { } public class B<T> { }"; var comp = CreateCompilation(source1, assemblyName: "95d36b13-f2e1-495d-9ab6-62e8cc63ac22"); var ref1 = comp.EmitToImageReference(); var source2 = @"public class C<T, U> { } public class D { public B<nint> F1; public C<nint, A> F2; }"; comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9); var ref2 = comp.EmitToImageReference(); var source3 = @"class Program { static void Main() { var d = new D(); _ = d.F1; _ = d.F2; } }"; comp = CreateCompilation(source3, references: new[] { ref2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,15): error CS0012: The type 'B<>' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // _ = d.F1; Diagnostic(ErrorCode.ERR_NoTypeDef, "F1").WithArguments("B<>", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 15), // (7,15): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // _ = d.F2; Diagnostic(ErrorCode.ERR_NoTypeDef, "F2").WithArguments("A", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 15)); } [Fact] public void EmitAttribute_Fields() { var source = @"public class Program { public nint F1; public (System.IntPtr, nuint[]) F2; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F2 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_MethodReturnType() { var source = @"public class Program { public (System.IntPtr, nuint[]) F() => default; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F() "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_MethodParameters() { var source = @"public class Program { public void F(nint x, nuint y) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program void F(System.IntPtr x, System.UIntPtr y) [NativeInteger] System.IntPtr x [NativeInteger] System.UIntPtr y "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_PropertyType() { var source = @"public class Program { public (System.IntPtr, nuint[]) P => default; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P { get; } [NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P.get "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_PropertyParameters() { var source = @"public class Program { public object this[nint x, (nuint[], System.IntPtr) y] => null; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y] { get; } [NativeInteger] System.IntPtr x [NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y].get [NativeInteger] System.IntPtr x [NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_EventType() { var source = @"using System; public class Program { public event EventHandler<nuint[]> E; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"Program [NativeInteger] event System.EventHandler<System.UIntPtr[]> E void E.add [NativeInteger] System.EventHandler<System.UIntPtr[]> value void E.remove [NativeInteger] System.EventHandler<System.UIntPtr[]> value "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_OperatorReturnType() { var source = @"public class C { public static nint operator+(C a, C b) => 0; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"C [NativeInteger] System.IntPtr operator +(C a, C b) "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_OperatorParameters() { var source = @"public class C { public static C operator+(C a, nuint[] b) => a; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"C C operator +(C a, System.UIntPtr[] b) [NativeInteger] System.UIntPtr[] b "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_DelegateReturnType() { var source = @"public delegate nint D();"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"D [NativeInteger] System.IntPtr Invoke() [NativeInteger] System.IntPtr EndInvoke(System.IAsyncResult result) "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_DelegateParameters() { var source = @"public delegate void D(nint x, nuint[] y);"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expected = @"D void Invoke(System.IntPtr x, System.UIntPtr[] y) [NativeInteger] System.IntPtr x [NativeInteger] System.UIntPtr[] y System.IAsyncResult BeginInvoke(System.IntPtr x, System.UIntPtr[] y, System.AsyncCallback callback, System.Object @object) [NativeInteger] System.IntPtr x [NativeInteger] System.UIntPtr[] y "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_Constraint() { var source = @"public class A<T> { } public class B<T> where T : A<nint> { } public class C<T> where T : A<nuint[]> { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var type = comp.GetMember<NamedTypeSymbol>("B"); Assert.Equal("A<nint>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes)); type = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal("A<nuint[]>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes)); static TypeWithAnnotations getConstraintType(NamedTypeSymbol type) => type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0]; } [Fact] public void EmitAttribute_LambdaReturnType() { var source = @"using System; class Program { static object M() { Func<nint> f = () => (nint)2; return f(); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<M>b__0_0"); AssertNativeIntegerAttribute(method.GetReturnTypeAttributes()); }); } [Fact] public void EmitAttribute_LambdaParameters() { var source = @"using System; class Program { static void M() { Action<nuint[]> a = (nuint[] n) => { }; a(null); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<M>b__0_0"); AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes()); }); } [Fact] public void EmitAttribute_LocalFunctionReturnType() { var source = @"class Program { static object M() { nint L() => (nint)2; return L(); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0"); AssertNativeIntegerAttribute(method.GetReturnTypeAttributes()); AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.CompilerGeneratedAttribute"); }); } [Fact] public void EmitAttribute_LocalFunctionParameters() { var source = @"class Program { static void M() { void L(nuint[] n) { } L(null); } }"; CompileAndVerify( source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0"); AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes()); }); } [Fact] public void EmitAttribute_Lambda_NetModule() { var source = @"class Program { static void Main() { var a1 = (nint n) => { }; a1(1); var a2 = nuint[] () => null; a2(); } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseModule); comp.VerifyDiagnostics( // (5,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // var a1 = (nint n) => { }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 19), // (7,29): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // var a2 = nuint[] () => null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "=>").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 29)); } [Fact] public void EmitAttribute_LocalFunction_NetModule() { var source = @"class Program { static void Main() { void L1(nint n) { }; L1(1); nuint[] L2() => null; L2(); } }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseModule); comp.VerifyDiagnostics( // (5,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // void L1(nint n) { }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 17), // (7,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported // nuint[] L2() => null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nuint[]").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 9)); } [Fact] public void EmitAttribute_Lambda_MissingAttributeConstructor() { var sourceA = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { private NativeIntegerAttribute() { } } }"; var sourceB = @"class Program { static void Main() { var a1 = (nint n) => { }; a1(1); var a2 = nuint[] () => null; a2(); } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // var a1 = (nint n) => { }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(5, 19), // (7,29): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // var a2 = nuint[] () => null; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(7, 29)); } [Fact] public void EmitAttribute_LocalFunction_MissingAttributeConstructor() { var sourceA = @"namespace System.Runtime.CompilerServices { public sealed class NativeIntegerAttribute : Attribute { private NativeIntegerAttribute() { } } }"; var sourceB = @"class Program { static void Main() { void L1(nint n) { }; L1(1); nuint[] L2() => null; L2(); } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // void L1(nint n) { }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(5, 17), // (7,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor' // nuint[] L2() => null; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nuint[]").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(7, 9)); } [Fact] public void EmitAttribute_LocalFunctionConstraints() { var source = @"interface I<T> { } class Program { static void M() { void L<T>() where T : I<nint> { } L<I<nint>>(); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, symbolValidator: module => { var assembly = module.ContainingAssembly; Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NativeIntegerAttribute")); }); } [Fact] public void EmitAttribute_Nested() { var source = @"public class A<T> { public class B<U> { } } unsafe public class Program { public nint F1; public nuint[] F2; public nint* F3; public A<nint>.B<nuint> F4; public (nint, nuint) F5; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll); var expected = @"Program [NativeInteger] System.IntPtr F1 [NativeInteger] System.UIntPtr[] F2 [NativeInteger] System.IntPtr* F3 [NativeInteger({ True, True })] A<System.IntPtr>.B<System.UIntPtr> F4 [NativeInteger({ True, True })] (System.IntPtr, System.UIntPtr) F5 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_LongTuples_01() { var source = @"public class A<T> { } unsafe public class B { public A<(object, (nint, nuint, nint[], nuint, nint, nuint*[], nint, System.UIntPtr))> F1; public A<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)> F2; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll); var expected = @"B [NativeInteger({ True, True, True, True, True, True, True, False })] A<(System.Object, (System.IntPtr, System.UIntPtr, System.IntPtr[], System.UIntPtr, System.IntPtr, System.UIntPtr*[], System.IntPtr, System.UIntPtr))> F1 [NativeInteger({ True, True, True, False, True, True })] A<(System.IntPtr, System.Object, System.UIntPtr[], System.Object, System.IntPtr, System.Object, (System.IntPtr, System.UIntPtr), System.Object, System.UIntPtr)> F2 "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void EmitAttribute_LongTuples_02() { var source1 = @"public interface IA { } public interface IB<T> { } public class C : IA, IB<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)> { }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, validator: assembly => { var reader = assembly.GetMetadataReader(); var typeDef = GetTypeDefinitionByName(reader, "C"); var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().ElementAt(1)); var customAttributes = interfaceImpl.GetCustomAttributes(); AssertAttributes(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])"); var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])"); AssertEx.Equal(ImmutableArray.Create(true, true, true, false, true, true), reader.ReadBoolArray(customAttribute.Value)); }); var ref1 = comp.EmitToImageReference(); var source2 = @"class Program { static void Main() { IA a = new C(); _ = a; } }"; comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(45519, "https://github.com/dotnet/roslyn/issues/45519")] public void EmitAttribute_PartialMethods() { var source = @"public partial class Program { static partial void F1(System.IntPtr x); static partial void F2(System.UIntPtr x) { } static partial void F1(nint x) { } static partial void F2(nuint x); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9); var expected = @"Program void F2(System.UIntPtr x) [NativeInteger] System.UIntPtr x "; AssertNativeIntegerAttributes(comp, expected); comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(6), parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,25): warning CS8826: Partial method declarations 'void Program.F2(nuint x)' and 'void Program.F2(UIntPtr x)' have signature differences. // static partial void F2(System.UIntPtr x) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F2").WithArguments("void Program.F2(nuint x)", "void Program.F2(UIntPtr x)").WithLocation(4, 25), // (5,25): warning CS8826: Partial method declarations 'void Program.F1(IntPtr x)' and 'void Program.F1(nint x)' have signature differences. // static partial void F1(nint x) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F1").WithArguments("void Program.F1(IntPtr x)", "void Program.F1(nint x)").WithLocation(5, 25)); } // Shouldn't depend on [NullablePublicOnly]. [Fact] public void NoPublicMembers() { var source = @"class A<T, U> { } class B : A<System.UIntPtr, nint> { }"; var comp = CreateCompilation( source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9.WithNullablePublicOnly()); var expected = @"[NativeInteger({ False, True })] B "; AssertNativeIntegerAttributes(comp, expected); } [Fact] public void AttributeUsage() { var source = @"public class Program { public nint F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute"); AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo(); Assert.False(attributeUsage.Inherited); Assert.False(attributeUsage.AllowMultiple); Assert.True(attributeUsage.HasValidAttributeTargets); var expectedTargets = AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue; Assert.Equal(expectedTargets, attributeUsage.ValidTargets); }); } [Fact] public void AttributeFieldExists() { var source = @"public class Program { public nint F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, symbolValidator: module => { var type = module.ContainingAssembly.GetTypeByMetadataName("Program"); var member = type.GetMembers("F").Single(); var attributes = member.GetAttributes(); AssertNativeIntegerAttribute(attributes); var attribute = GetNativeIntegerAttribute(attributes); var field = attribute.AttributeClass.GetField("TransformFlags"); Assert.Equal("System.Boolean[]", field.TypeWithAnnotations.ToTestDisplayString()); }); } [Fact] public void NestedNativeIntegerWithPrecedingType() { var comp = CompileAndVerify(@" class C<T, U, V> { public C<dynamic, T, nint> F0; public C<dynamic, nint, System.IntPtr> F1; public C<dynamic, nuint, System.UIntPtr> F2; public C<T, nint, System.IntPtr> F3; public C<T, nuint, System.UIntPtr> F4; } ", options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator); static void symbolValidator(ModuleSymbol module) { var expectedAttributes = @" C<T, U, V> [NativeInteger] C<dynamic, T, System.IntPtr> F0 [NativeInteger({ True, False })] C<dynamic, System.IntPtr, System.IntPtr> F1 [NativeInteger({ True, False })] C<dynamic, System.UIntPtr, System.UIntPtr> F2 [NativeInteger({ True, False })] C<T, System.IntPtr, System.IntPtr> F3 [NativeInteger({ True, False })] C<T, System.UIntPtr, System.UIntPtr> F4 "; AssertNativeIntegerAttributes(module, expectedAttributes); var c = module.GlobalNamespace.GetTypeMember("C"); assert("C<dynamic, T, nint>", "F0"); assert("C<dynamic, nint, System.IntPtr>", "F1"); assert("C<dynamic, nuint, System.UIntPtr>", "F2"); assert("C<T, nint, System.IntPtr>", "F3"); assert("C<T, nuint, System.UIntPtr>", "F4"); void assert(string expectedType, string fieldName) { Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString()); } } } [Fact] public void FunctionPointersWithNativeIntegerTypes() { var comp = CompileAndVerify(@" unsafe class C { public delegate*<nint, object, object> F0; public delegate*<nint, nint, nint> F1; public delegate*<System.IntPtr, System.IntPtr, nint> F2; public delegate*<nint, System.IntPtr, System.IntPtr> F3; public delegate*<System.IntPtr, nint, System.IntPtr> F4; public delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint> F5; public delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6; public delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr> F7; public delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>> F8; } ", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator); static void symbolValidator(ModuleSymbol module) { var expectedAttributes = @" C [NativeInteger] delegate*<System.IntPtr, System.Object, System.Object> F0 [NativeInteger({ True, True, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F1 [NativeInteger({ True, False, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F2 [NativeInteger({ False, True, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F3 [NativeInteger({ False, False, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F4 [NativeInteger({ True, False, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F5 [NativeInteger({ False, False, False, True })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6 [NativeInteger({ False, True, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F7 [NativeInteger({ False, False, True, False })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F8 "; AssertNativeIntegerAttributes(module, expectedAttributes); var c = module.GlobalNamespace.GetTypeMember("C"); assert("delegate*<nint, System.Object, System.Object>", "F0"); assert("delegate*<nint, nint, nint>", "F1"); assert("delegate*<System.IntPtr, System.IntPtr, nint>", "F2"); assert("delegate*<nint, System.IntPtr, System.IntPtr>", "F3"); assert("delegate*<System.IntPtr, nint, System.IntPtr>", "F4"); assert("delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint>", "F5"); assert("delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>>", "F6"); assert("delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr>", "F7"); assert("delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>>", "F8"); void assert(string expectedType, string fieldName) { var field = c.GetField(fieldName); FunctionPointerUtilities.CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type); Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString()); } } } private static TypeDefinition GetTypeDefinitionByName(MetadataReader reader, string name) { return reader.GetTypeDefinition(reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name))); } private static string GetAttributeConstructorName(MetadataReader reader, CustomAttributeHandle handle) { return reader.Dump(reader.GetCustomAttribute(handle).Constructor); } private static CustomAttribute GetAttributeByConstructorName(MetadataReader reader, CustomAttributeHandleCollection handles, string name) { return reader.GetCustomAttribute(handles.FirstOrDefault(h => GetAttributeConstructorName(reader, h) == name)); } private static void AssertAttributes(MetadataReader reader, CustomAttributeHandleCollection handles, params string[] expectedNames) { var actualNames = handles.Select(h => GetAttributeConstructorName(reader, h)).ToArray(); AssertEx.Equal(expectedNames, actualNames); } private static void AssertNoNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) { AssertAttributes(attributes); } private static void AssertNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) { AssertAttributes(attributes, "System.Runtime.CompilerServices.NativeIntegerAttribute"); } private static void AssertAttributes(ImmutableArray<CSharpAttributeData> attributes, params string[] expectedNames) { var actualNames = attributes.Select(a => a.AttributeClass.ToTestDisplayString()).ToArray(); AssertEx.Equal(expectedNames, actualNames); } private static void AssertNoNativeIntegerAttributes(CSharpCompilation comp) { var image = comp.EmitToArray(); using (var reader = new PEReader(image)) { var metadataReader = reader.GetMetadataReader(); var attributes = metadataReader.GetCustomAttributeRows().Select(metadataReader.GetCustomAttributeName).ToArray(); Assert.False(attributes.Contains("NativeIntegerAttribute")); } } private void AssertNativeIntegerAttributes(CSharpCompilation comp, string expected) { CompileAndVerify(comp, symbolValidator: module => AssertNativeIntegerAttributes(module, expected)); } private static void AssertNativeIntegerAttributes(ModuleSymbol module, string expected) { var actual = NativeIntegerAttributesVisitor.GetString((PEModuleSymbol)module); AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual); } private static CSharpAttributeData GetNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes) { return attributes.Single(a => a.AttributeClass.ToTestDisplayString() == "System.Runtime.CompilerServices.NativeIntegerAttribute"); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Analyzers/CSharp/Tests/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.NewLines.ConsecutiveBracePlacement; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConsecutiveBracePlacement { using VerifyCS = CSharpCodeFixVerifier< ConsecutiveBracePlacementDiagnosticAnalyzer, ConsecutiveBracePlacementCodeFixProvider>; public class ConsecutiveBracePlacementTests { [Fact] public async Task NotForBracesOnSameLineDirectlyTouching() { var code = @"class C { void M() { }}"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSameLineWithSpace() { var code = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSameLineWithComment() { var code = @"class C { void M() { }/*goo*/}"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSameLineWithCommentAndSpaces() { var code = @"class C { void M() { } /*goo*/ }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLines_TopLevel() { var code = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesWithComment1_TopLevel() { var code = @"class C { void M() { } // comment }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesWithComment2_TopLevel() { var code = @"class C { void M() { } /* comment */ }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesIndented() { var code = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesIndentedWithComment1() { var code = @"namespace N { class C { void M() { } // comment } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesIndentedWithComment2() { var code = @"namespace N { class C { void M() { } /* comment */ } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween1_TopLevel() { var code = @"class C { void M() { } // comment }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween2_TopLevel() { var code = @"class C { void M() { } /* comment */ }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfDirectiveBetween1_TopLeve() { var code = @"class C { void M() { } #nullable enable }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween1_Nested() { var code = @"namespace N { class C { void M() { } // comment } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween2_Nested() { var code = @"namespace N { class C { void M() { } /* comment */ } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfDirectiveBetween_Nested() { var code = @"namespace N { class C { void M() { } #nullable enable } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task OneBlankLineBetweenBraces_TopLevel() { var code = @"class C { void M() { } [|}|]"; var fixedCode = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task OneBlankLineBetweenBraces_TopLevel_OptionDisabled() { var code = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.TrueWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TwoBlankLinesBetweenBraces_TopLevel() { var code = @"class C { void M() { } [|}|]"; var fixedCode = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task ThreeBlankLinesBetweenBraces_TopLevel() { var code = @"class C { void M() { } [|}|]"; var fixedCode = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_LeadingComment_TopLevel() { var code = @"class C { void M() { } /*comment*/[|}|]"; var fixedCode = @"class C { void M() { } /*comment*/}"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_TrailingComment_TopLevel() { var code = @"class C { void M() { } /*comment*/ [|}|]"; var fixedCode = @"class C { void M() { } /*comment*/ }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task OneBlankLineBetweenBraces_Nested() { var code = @"namespace N { class C { void M() { } [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TwoBlankLinesBetweenBraces_Nested() { var code = @"namespace N { class C { void M() { } [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task ThreeBlankLinesBetweenBraces_Nested() { var code = @"namespace N { class C { void M() { } [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_LeadingComment_Nested() { var code = @"namespace N { class C { void M() { } /*comment*/[|}|] }"; var fixedCode = @"namespace N { class C { void M() { } /*comment*/} }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_TrailingComment_Nested() { var code = @"namespace N { class C { void M() { } /*comment*/ [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } /*comment*/ } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task FixAll1() { var code = @"namespace N { class C { void M() { } [|}|] [|}|]"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task RealCode1() { var code = @" #nullable enable using System; #if CODE_STYLE using System.Collections.Generic; #endif namespace Microsoft.CodeAnalysis.Options { internal interface IOption { } internal interface IOption2 #if !CODE_STYLE : IOption #endif { string OptionDefinition { get; } #if CODE_STYLE string Feature { get; } string Name { get; } Type Type { get; } object? DefaultValue { get; } bool IsPerLanguage { get; } List<string> StorageLocations { get; } #endif } } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task RealCode2() { var code = @" #define CODE_STYLE #nullable enable using System; #if CODE_STYLE using System.Collections.Generic; #endif namespace Microsoft.CodeAnalysis.Options { internal interface IOption { } internal interface IOption2 #if !CODE_STYLE : IOption #endif { string OptionDefinition { get; } #if CODE_STYLE string Feature { get; } string Name { get; } Type Type { get; } object? DefaultValue { get; } bool IsPerLanguage { get; } List<string> StorageLocations { get; } #endif } } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.NewLines.ConsecutiveBracePlacement; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConsecutiveBracePlacement { using VerifyCS = CSharpCodeFixVerifier< ConsecutiveBracePlacementDiagnosticAnalyzer, ConsecutiveBracePlacementCodeFixProvider>; public class ConsecutiveBracePlacementTests { [Fact] public async Task NotForBracesOnSameLineDirectlyTouching() { var code = @"class C { void M() { }}"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSameLineWithSpace() { var code = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSameLineWithComment() { var code = @"class C { void M() { }/*goo*/}"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSameLineWithCommentAndSpaces() { var code = @"class C { void M() { } /*goo*/ }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLines_TopLevel() { var code = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesWithComment1_TopLevel() { var code = @"class C { void M() { } // comment }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesWithComment2_TopLevel() { var code = @"class C { void M() { } /* comment */ }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesIndented() { var code = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesIndentedWithComment1() { var code = @"namespace N { class C { void M() { } // comment } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesOnSubsequentLinesIndentedWithComment2() { var code = @"namespace N { class C { void M() { } /* comment */ } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween1_TopLevel() { var code = @"class C { void M() { } // comment }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween2_TopLevel() { var code = @"class C { void M() { } /* comment */ }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfDirectiveBetween1_TopLeve() { var code = @"class C { void M() { } #nullable enable }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween1_Nested() { var code = @"namespace N { class C { void M() { } // comment } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfCommentBetween2_Nested() { var code = @"namespace N { class C { void M() { } /* comment */ } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task NotForBracesWithBlankLinesIfDirectiveBetween_Nested() { var code = @"namespace N { class C { void M() { } #nullable enable } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task OneBlankLineBetweenBraces_TopLevel() { var code = @"class C { void M() { } [|}|]"; var fixedCode = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task OneBlankLineBetweenBraces_TopLevel_OptionDisabled() { var code = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.TrueWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TwoBlankLinesBetweenBraces_TopLevel() { var code = @"class C { void M() { } [|}|]"; var fixedCode = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task ThreeBlankLinesBetweenBraces_TopLevel() { var code = @"class C { void M() { } [|}|]"; var fixedCode = @"class C { void M() { } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_LeadingComment_TopLevel() { var code = @"class C { void M() { } /*comment*/[|}|]"; var fixedCode = @"class C { void M() { } /*comment*/}"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_TrailingComment_TopLevel() { var code = @"class C { void M() { } /*comment*/ [|}|]"; var fixedCode = @"class C { void M() { } /*comment*/ }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task OneBlankLineBetweenBraces_Nested() { var code = @"namespace N { class C { void M() { } [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TwoBlankLinesBetweenBraces_Nested() { var code = @"namespace N { class C { void M() { } [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task ThreeBlankLinesBetweenBraces_Nested() { var code = @"namespace N { class C { void M() { } [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_LeadingComment_Nested() { var code = @"namespace N { class C { void M() { } /*comment*/[|}|] }"; var fixedCode = @"namespace N { class C { void M() { } /*comment*/} }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task BlankLinesBetweenBraces_TrailingComment_Nested() { var code = @"namespace N { class C { void M() { } /*comment*/ [|}|] }"; var fixedCode = @"namespace N { class C { void M() { } /*comment*/ } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task FixAll1() { var code = @"namespace N { class C { void M() { } [|}|] [|}|]"; var fixedCode = @"namespace N { class C { void M() { } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task RealCode1() { var code = @" #nullable enable using System; #if CODE_STYLE using System.Collections.Generic; #endif namespace Microsoft.CodeAnalysis.Options { internal interface IOption { } internal interface IOption2 #if !CODE_STYLE : IOption #endif { string OptionDefinition { get; } #if CODE_STYLE string Feature { get; } string Name { get; } Type Type { get; } object? DefaultValue { get; } bool IsPerLanguage { get; } List<string> StorageLocations { get; } #endif } } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task RealCode2() { var code = @" #define CODE_STYLE #nullable enable using System; #if CODE_STYLE using System.Collections.Generic; #endif namespace Microsoft.CodeAnalysis.Options { internal interface IOption { } internal interface IOption2 #if !CODE_STYLE : IOption #endif { string OptionDefinition { get; } #if CODE_STYLE string Feature { get; } string Name { get; } Type Type { get; } object? DefaultValue { get; } bool IsPerLanguage { get; } List<string> StorageLocations { get; } #endif } } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8, Options = { { CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Parser/SyntaxParser.ResetPoint.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.CSharp.Syntax.InternalSyntax { internal partial class SyntaxParser { protected struct ResetPoint { internal readonly int ResetCount; internal readonly LexerMode Mode; internal readonly int Position; internal readonly GreenNode PrevTokenTrailingTrivia; internal ResetPoint(int resetCount, LexerMode mode, int position, GreenNode prevTokenTrailingTrivia) { this.ResetCount = resetCount; this.Mode = mode; this.Position = position; this.PrevTokenTrailingTrivia = prevTokenTrailingTrivia; } } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax.InternalSyntax { internal partial class SyntaxParser { protected struct ResetPoint { internal readonly int ResetCount; internal readonly LexerMode Mode; internal readonly int Position; internal readonly GreenNode PrevTokenTrailingTrivia; internal ResetPoint(int resetCount, LexerMode mode, int position, GreenNode prevTokenTrailingTrivia) { this.ResetCount = resetCount; this.Mode = mode; this.Position = position; this.PrevTokenTrailingTrivia = prevTokenTrailingTrivia; } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticLineEnderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticLineEnderTests { protected abstract string Language { get; } protected abstract Action CreateNextHandler(TestWorkspace workspace); internal abstract IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace); protected void Test(string expected, string markupCode, bool completionActive = false, bool assertNextHandlerInvoked = false) { TestFileMarkupParser.GetPositionsAndSpans(markupCode, out var code, out var positions, out _); Assert.NotEmpty(positions); foreach (var position in positions) { // Run the test once for each input position. All marked positions in the input for a test are expected // to have the same result. Test(expected, code, position, completionActive, assertNextHandlerInvoked); } } #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/45892 private void Test(string expected, string code, int position, bool completionActive = false, bool assertNextHandlerInvoked = false) #pragma warning restore IDE0060 // Remove unused parameter { var markupCode = code[0..position] + "$$" + code[position..]; // WPF is required for some reason: https://github.com/dotnet/roslyn/issues/46286 using var workspace = TestWorkspace.Create(Language, compilationOptions: null, parseOptions: null, new[] { markupCode }, composition: EditorTestCompositions.EditorFeaturesWpf); var view = workspace.Documents.Single().GetTextView(); var buffer = workspace.Documents.Single().GetTextBuffer(); var nextHandlerInvoked = false; view.Caret.MoveTo(new SnapshotPoint(buffer.CurrentSnapshot, workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var nextHandler = assertNextHandlerInvoked ? () => nextHandlerInvoked = true : CreateNextHandler(workspace); commandHandler.ExecuteCommand(new AutomaticLineEnderCommandArgs(view, buffer), nextHandler, TestCommandExecutionContext.Create()); Test(view, buffer, expected); Assert.Equal(assertNextHandlerInvoked, nextHandlerInvoked); } private static void Test(ITextView view, ITextBuffer buffer, string expectedWithAnnotations) { MarkupTestFile.GetPosition(expectedWithAnnotations, out var expected, out int expectedPosition); // Remove any virtual space from the expected text. var virtualPosition = view.Caret.Position.VirtualBufferPosition; expected = expected.Remove(virtualPosition.Position, virtualPosition.VirtualSpaces); Assert.Equal(expected, buffer.CurrentSnapshot.GetText()); Assert.Equal(expectedPosition, virtualPosition.Position.Position + virtualPosition.VirtualSpaces); } public static T GetService<T>(TestWorkspace workspace) => workspace.GetService<T>(); public static T GetExportedValue<T>(TestWorkspace workspace) => workspace.ExportProvider.GetExportedValue<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.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticLineEnderTests { protected abstract string Language { get; } protected abstract Action CreateNextHandler(TestWorkspace workspace); internal abstract IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace); protected void Test(string expected, string markupCode, bool completionActive = false, bool assertNextHandlerInvoked = false) { TestFileMarkupParser.GetPositionsAndSpans(markupCode, out var code, out var positions, out _); Assert.NotEmpty(positions); foreach (var position in positions) { // Run the test once for each input position. All marked positions in the input for a test are expected // to have the same result. Test(expected, code, position, completionActive, assertNextHandlerInvoked); } } #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/45892 private void Test(string expected, string code, int position, bool completionActive = false, bool assertNextHandlerInvoked = false) #pragma warning restore IDE0060 // Remove unused parameter { var markupCode = code[0..position] + "$$" + code[position..]; // WPF is required for some reason: https://github.com/dotnet/roslyn/issues/46286 using var workspace = TestWorkspace.Create(Language, compilationOptions: null, parseOptions: null, new[] { markupCode }, composition: EditorTestCompositions.EditorFeaturesWpf); var view = workspace.Documents.Single().GetTextView(); var buffer = workspace.Documents.Single().GetTextBuffer(); var nextHandlerInvoked = false; view.Caret.MoveTo(new SnapshotPoint(buffer.CurrentSnapshot, workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var nextHandler = assertNextHandlerInvoked ? () => nextHandlerInvoked = true : CreateNextHandler(workspace); commandHandler.ExecuteCommand(new AutomaticLineEnderCommandArgs(view, buffer), nextHandler, TestCommandExecutionContext.Create()); Test(view, buffer, expected); Assert.Equal(assertNextHandlerInvoked, nextHandlerInvoked); } private static void Test(ITextView view, ITextBuffer buffer, string expectedWithAnnotations) { MarkupTestFile.GetPosition(expectedWithAnnotations, out var expected, out int expectedPosition); // Remove any virtual space from the expected text. var virtualPosition = view.Caret.Position.VirtualBufferPosition; expected = expected.Remove(virtualPosition.Position, virtualPosition.VirtualSpaces); Assert.Equal(expected, buffer.CurrentSnapshot.GetText()); Assert.Equal(expectedPosition, virtualPosition.Position.Position + virtualPosition.VirtualSpaces); } public static T GetService<T>(TestWorkspace workspace) => workspace.GetService<T>(); public static T GetExportedValue<T>(TestWorkspace workspace) => workspace.ExportProvider.GetExportedValue<T>(); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/CSharp/Impl/ObjectBrowser/ListItemFactory.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; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class ListItemFactory : AbstractListItemFactory { 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); private static readonly SymbolDisplayFormat s_memberWithContainingTypeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); protected override string GetMemberDisplayString(ISymbol memberSymbol) => memberSymbol.ToDisplayString(s_memberDisplayFormat); protected override string GetMemberAndTypeDisplayString(ISymbol memberSymbol) => memberSymbol.ToDisplayString(s_memberWithContainingTypeDisplayFormat); } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class ListItemFactory : AbstractListItemFactory { 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); private static readonly SymbolDisplayFormat s_memberWithContainingTypeDisplayFormat = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); protected override string GetMemberDisplayString(ISymbol memberSymbol) => memberSymbol.ToDisplayString(s_memberDisplayFormat); protected override string GetMemberAndTypeDisplayString(ISymbol memberSymbol) => memberSymbol.ToDisplayString(s_memberWithContainingTypeDisplayFormat); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Workspaces/Core/Portable/Remote/PinnedSolutionInfo.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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Information related to pinned solution /// </summary> [DataContract] internal sealed class PinnedSolutionInfo { /// <summary> /// Unique ID for this pinned solution /// /// This later used to find matching solution between VS and remote host /// </summary> [DataMember(Order = 0)] public readonly int ScopeId; /// <summary> /// This indicates whether this scope is for primary branch or not (not forked solution) /// /// Features like OOP will use this flag to see whether caching information related to this solution /// can benefit other requests or not /// </summary> [DataMember(Order = 1)] public readonly bool FromPrimaryBranch; /// <summary> /// This indicates a Solution.WorkspaceVersion of this solution. remote host engine uses this version /// to decide whether caching this solution will benefit other requests or not /// </summary> [DataMember(Order = 2)] public readonly int WorkspaceVersion; [DataMember(Order = 3)] public readonly Checksum SolutionChecksum; /// <summary> /// An optional project that we are pinning information for. This is used for features that only need /// information for a project (and its dependencies) and not the entire solution. /// </summary> [DataMember(Order = 4)] public readonly ProjectId? ProjectId; public PinnedSolutionInfo( int scopeId, bool fromPrimaryBranch, int workspaceVersion, Checksum solutionChecksum, ProjectId? projectId) { ScopeId = scopeId; FromPrimaryBranch = fromPrimaryBranch; WorkspaceVersion = workspaceVersion; SolutionChecksum = solutionChecksum; ProjectId = projectId; } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Information related to pinned solution /// </summary> [DataContract] internal sealed class PinnedSolutionInfo { /// <summary> /// Unique ID for this pinned solution /// /// This later used to find matching solution between VS and remote host /// </summary> [DataMember(Order = 0)] public readonly int ScopeId; /// <summary> /// This indicates whether this scope is for primary branch or not (not forked solution) /// /// Features like OOP will use this flag to see whether caching information related to this solution /// can benefit other requests or not /// </summary> [DataMember(Order = 1)] public readonly bool FromPrimaryBranch; /// <summary> /// This indicates a Solution.WorkspaceVersion of this solution. remote host engine uses this version /// to decide whether caching this solution will benefit other requests or not /// </summary> [DataMember(Order = 2)] public readonly int WorkspaceVersion; [DataMember(Order = 3)] public readonly Checksum SolutionChecksum; /// <summary> /// An optional project that we are pinning information for. This is used for features that only need /// information for a project (and its dependencies) and not the entire solution. /// </summary> [DataMember(Order = 4)] public readonly ProjectId? ProjectId; public PinnedSolutionInfo( int scopeId, bool fromPrimaryBranch, int workspaceVersion, Checksum solutionChecksum, ProjectId? projectId) { ScopeId = scopeId; FromPrimaryBranch = fromPrimaryBranch; WorkspaceVersion = workspaceVersion; SolutionChecksum = solutionChecksum; ProjectId = projectId; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/Portable/PEWriter/ICustomAttribute.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 EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// A metadata custom attribute. /// </summary> internal interface ICustomAttribute { /// <summary> /// Zero or more positional arguments for the attribute constructor. /// </summary> ImmutableArray<IMetadataExpression> GetArguments(EmitContext context); /// <summary> /// A reference to the constructor that will be used to instantiate this custom attribute during execution (if the attribute is inspected via Reflection). /// </summary> IMethodReference Constructor(EmitContext context, bool reportDiagnostics); /// <summary> /// Zero or more named arguments that specify values for fields and properties of the attribute. /// </summary> ImmutableArray<IMetadataNamedArgument> GetNamedArguments(EmitContext context); /// <summary> /// The number of positional arguments. /// </summary> int ArgumentCount { get; } /// <summary> /// The number of named arguments. /// </summary> ushort NamedArgumentCount { get; } /// <summary> /// The type of the attribute. For example System.AttributeUsageAttribute. /// </summary> ITypeReference GetType(EmitContext context); /// <summary> /// Whether attribute allows multiple. /// </summary> bool AllowMultiple { 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.Collections.Generic; using System.Collections.Immutable; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// A metadata custom attribute. /// </summary> internal interface ICustomAttribute { /// <summary> /// Zero or more positional arguments for the attribute constructor. /// </summary> ImmutableArray<IMetadataExpression> GetArguments(EmitContext context); /// <summary> /// A reference to the constructor that will be used to instantiate this custom attribute during execution (if the attribute is inspected via Reflection). /// </summary> IMethodReference Constructor(EmitContext context, bool reportDiagnostics); /// <summary> /// Zero or more named arguments that specify values for fields and properties of the attribute. /// </summary> ImmutableArray<IMetadataNamedArgument> GetNamedArguments(EmitContext context); /// <summary> /// The number of positional arguments. /// </summary> int ArgumentCount { get; } /// <summary> /// The number of named arguments. /// </summary> ushort NamedArgumentCount { get; } /// <summary> /// The type of the attribute. For example System.AttributeUsageAttribute. /// </summary> ITypeReference GetType(EmitContext context); /// <summary> /// Whether attribute allows multiple. /// </summary> bool AllowMultiple { get; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Analyzers/CSharp/Analyzers/PopulateSwitch/CSharpPopulateSwitchStatementDiagnosticAnalyzer.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.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PopulateSwitch; namespace Microsoft.CodeAnalysis.CSharp.PopulateSwitch { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpPopulateSwitchStatementDiagnosticAnalyzer : AbstractPopulateSwitchStatementDiagnosticAnalyzer<SwitchStatementSyntax> { } }
// Licensed to the .NET Foundation under one or more 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.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PopulateSwitch; namespace Microsoft.CodeAnalysis.CSharp.PopulateSwitch { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpPopulateSwitchStatementDiagnosticAnalyzer : AbstractPopulateSwitchStatementDiagnosticAnalyzer<SwitchStatementSyntax> { } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.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.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class BlockSyntaxExtensions { public static bool TryConvertToExpressionBody( this BlockSyntax block, ParseOptions options, ExpressionBodyPreference preference, [NotNullWhen(true)] out ExpressionSyntax? expression, out SyntaxToken semicolonToken) { if (preference != ExpressionBodyPreference.Never && block != null && block.Statements.Count == 1) { var firstStatement = block.Statements[0]; var version = ((CSharpParseOptions)options).LanguageVersion; if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) && MatchesPreference(expression, preference)) { // The close brace of the block may have important trivia on it (like // comments or directives). Preserve them on the semicolon when we // convert to an expression body. semicolonToken = semicolonToken.WithAppendedTrailingTrivia( block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine())); return true; } } expression = null; semicolonToken = default; return false; } public static bool TryConvertToArrowExpressionBody( this BlockSyntax block, SyntaxKind declarationKind, ParseOptions options, ExpressionBodyPreference preference, [NotNullWhen(true)] out ArrowExpressionClauseSyntax? arrowExpression, out SyntaxToken semicolonToken) { var version = ((CSharpParseOptions)options).LanguageVersion; // We can always use arrow-expression bodies in C# 7 or above. // We can also use them in C# 6, but only a select set of member kinds. var acceptableVersion = version >= LanguageVersion.CSharp7 || (version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind)); if (!acceptableVersion || !block.TryConvertToExpressionBody( options, preference, out var expression, out semicolonToken)) { arrowExpression = null; semicolonToken = default; return false; } arrowExpression = SyntaxFactory.ArrowExpressionClause(expression); return true; } private static bool IsSupportedInCSharp6(SyntaxKind declarationKind) { switch (declarationKind) { case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return false; } return true; } public static bool MatchesPreference( ExpressionSyntax expression, ExpressionBodyPreference preference) { if (preference == ExpressionBodyPreference.WhenPossible) { return true; } Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine); return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false); } private static bool TryGetExpression( LanguageVersion version, StatementSyntax firstStatement, [NotNullWhen(true)] out ExpressionSyntax? expression, out SyntaxToken semicolonToken) { if (firstStatement is ExpressionStatementSyntax exprStatement) { expression = exprStatement.Expression; semicolonToken = exprStatement.SemicolonToken; return true; } else if (firstStatement is ReturnStatementSyntax returnStatement) { if (returnStatement.Expression != null) { // If there are any comments or directives on the return keyword, move them to // the expression. expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment()) ? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia()) : returnStatement.Expression; semicolonToken = returnStatement.SemicolonToken; return true; } } else if (firstStatement is ThrowStatementSyntax throwStatement) { if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null) { expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression); semicolonToken = throwStatement.SemicolonToken; return true; } } expression = null; semicolonToken = default; 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. using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class BlockSyntaxExtensions { public static bool TryConvertToExpressionBody( this BlockSyntax block, ParseOptions options, ExpressionBodyPreference preference, [NotNullWhen(true)] out ExpressionSyntax? expression, out SyntaxToken semicolonToken) { if (preference != ExpressionBodyPreference.Never && block != null && block.Statements.Count == 1) { var firstStatement = block.Statements[0]; var version = ((CSharpParseOptions)options).LanguageVersion; if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) && MatchesPreference(expression, preference)) { // The close brace of the block may have important trivia on it (like // comments or directives). Preserve them on the semicolon when we // convert to an expression body. semicolonToken = semicolonToken.WithAppendedTrailingTrivia( block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine())); return true; } } expression = null; semicolonToken = default; return false; } public static bool TryConvertToArrowExpressionBody( this BlockSyntax block, SyntaxKind declarationKind, ParseOptions options, ExpressionBodyPreference preference, [NotNullWhen(true)] out ArrowExpressionClauseSyntax? arrowExpression, out SyntaxToken semicolonToken) { var version = ((CSharpParseOptions)options).LanguageVersion; // We can always use arrow-expression bodies in C# 7 or above. // We can also use them in C# 6, but only a select set of member kinds. var acceptableVersion = version >= LanguageVersion.CSharp7 || (version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind)); if (!acceptableVersion || !block.TryConvertToExpressionBody( options, preference, out var expression, out semicolonToken)) { arrowExpression = null; semicolonToken = default; return false; } arrowExpression = SyntaxFactory.ArrowExpressionClause(expression); return true; } private static bool IsSupportedInCSharp6(SyntaxKind declarationKind) { switch (declarationKind) { case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return false; } return true; } public static bool MatchesPreference( ExpressionSyntax expression, ExpressionBodyPreference preference) { if (preference == ExpressionBodyPreference.WhenPossible) { return true; } Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine); return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false); } private static bool TryGetExpression( LanguageVersion version, StatementSyntax firstStatement, [NotNullWhen(true)] out ExpressionSyntax? expression, out SyntaxToken semicolonToken) { if (firstStatement is ExpressionStatementSyntax exprStatement) { expression = exprStatement.Expression; semicolonToken = exprStatement.SemicolonToken; return true; } else if (firstStatement is ReturnStatementSyntax returnStatement) { if (returnStatement.Expression != null) { // If there are any comments or directives on the return keyword, move them to // the expression. expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment()) ? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia()) : returnStatement.Expression; semicolonToken = returnStatement.SemicolonToken; return true; } } else if (firstStatement is ThrowStatementSyntax throwStatement) { if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null) { expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression); semicolonToken = throwStatement.SemicolonToken; return true; } } expression = null; semicolonToken = default; return false; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/Core/Impl/CodeModel/Collections/InheritsImplementsCollection.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.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class InheritsImplementsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new InheritsImplementsCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private InheritsImplementsCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = (AbstractCodeElement)this.Parent; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetInheritsNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImplementsNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; // Inherits statements var inheritsNodes = CodeModelService.GetInheritsNodes(node); var inheritsNodeCount = inheritsNodes.Count(); if (index < currentIndex + inheritsNodeCount) { var child = inheritsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } currentIndex += inheritsNodeCount; // Implements statements var implementsNodes = CodeModelService.GetImplementsNodes(node); var implementsNodeCount = implementsNodes.Count(); if (index < currentIndex + implementsNodeCount) { var child = implementsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); // Inherits statements foreach (var child in CodeModelService.GetInheritsNodes(node)) { CodeModelService.GetInheritsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } // Implements statements foreach (var child in CodeModelService.GetImplementsNodes(node)) { CodeModelService.GetImplementsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetInheritsNodes(node).Count() + CodeModelService.GetImplementsNodes(node).Count(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class InheritsImplementsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new InheritsImplementsCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private InheritsImplementsCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = (AbstractCodeElement)this.Parent; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetInheritsNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImplementsNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; // Inherits statements var inheritsNodes = CodeModelService.GetInheritsNodes(node); var inheritsNodeCount = inheritsNodes.Count(); if (index < currentIndex + inheritsNodeCount) { var child = inheritsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } currentIndex += inheritsNodeCount; // Implements statements var implementsNodes = CodeModelService.GetImplementsNodes(node); var implementsNodeCount = implementsNodes.Count(); if (index < currentIndex + implementsNodeCount) { var child = implementsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); // Inherits statements foreach (var child in CodeModelService.GetInheritsNodes(node)) { CodeModelService.GetInheritsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } // Implements statements foreach (var child in CodeModelService.GetImplementsNodes(node)) { CodeModelService.GetImplementsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetInheritsNodes(node).Count() + CodeModelService.GetImplementsNodes(node).Count(); } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/Core/Portable/GenerateConstructorFromMembers/AbstractGenerateConstructorFromMembersCodeRefactoringProvider.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider { private class State { public TextSpan TextSpan { get; private set; } public IMethodSymbol? MatchingConstructor { get; private set; } public IMethodSymbol? DelegatedConstructor { get; private set; } [NotNull] public INamedTypeSymbol? ContainingType { get; private set; } public ImmutableArray<ISymbol> SelectedMembers { get; private set; } public ImmutableArray<IParameterSymbol> Parameters { get; private set; } public bool IsContainedInUnsafeType { get; private set; } public static async Task<State?> TryGenerateAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return false; } SelectedMembers = selectedMembers; ContainingType = containingType; TextSpan = textSpan; if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface) { return false; } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType); var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); Parameters = DetermineParameters(selectedMembers, rules); MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters); return true; } private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes( INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) { var q = from c in containingType.InstanceConstructors orderby c.Parameters.Length descending where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams) let constructorTypes = c.Parameters.Select(p => p.Type) let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type) where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default) select c; return q.FirstOrDefault(); } private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) => containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters)); private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters) => parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider { private class State { public TextSpan TextSpan { get; private set; } public IMethodSymbol? MatchingConstructor { get; private set; } public IMethodSymbol? DelegatedConstructor { get; private set; } [NotNull] public INamedTypeSymbol? ContainingType { get; private set; } public ImmutableArray<ISymbol> SelectedMembers { get; private set; } public ImmutableArray<IParameterSymbol> Parameters { get; private set; } public bool IsContainedInUnsafeType { get; private set; } public static async Task<State?> TryGenerateAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return false; } SelectedMembers = selectedMembers; ContainingType = containingType; TextSpan = textSpan; if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface) { return false; } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType); var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); Parameters = DetermineParameters(selectedMembers, rules); MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters); return true; } private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes( INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) { var q = from c in containingType.InstanceConstructors orderby c.Parameters.Length descending where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams) let constructorTypes = c.Parameters.Select(p => p.Type) let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type) where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default) select c; return q.FirstOrDefault(); } private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) => containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters)); private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters) => parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type)); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/Test/CodeFixes/ErrorCases/CodeFixExceptionInRegisterMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes.ErrorCases { public class ExceptionInRegisterMethod : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(CodeFixServiceTests.MockFixer.Id); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => throw new Exception($"Exception thrown in register method of {nameof(ExceptionInRegisterMethod)}"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes.ErrorCases { public class ExceptionInRegisterMethod : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(CodeFixServiceTests.MockFixer.Id); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => throw new Exception($"Exception thrown in register method of {nameof(ExceptionInRegisterMethod)}"); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.Generation.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; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int SortUsings_SeparateImportDirectiveGroups { get { return GetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups); } set { SetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups, value); } } public int SortUsings_PlaceSystemFirst { get { return GetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst); } set { SetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst, value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editing; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int SortUsings_SeparateImportDirectiveGroups { get { return GetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups); } set { SetBooleanOption(GenerationOptions.SeparateImportDirectiveGroups, value); } } public int SortUsings_PlaceSystemFirst { get { return GetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst); } set { SetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst, value); } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/Portable/Symbols/Attributes/CommonAssemblyWellKnownAttributeData.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.Reflection; using Microsoft.CodeAnalysis.Text; using System.Collections.Generic; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on an assembly. /// </summary> internal class CommonAssemblyWellKnownAttributeData<TNamedTypeSymbol> : WellKnownAttributeData, ISecurityAttributeTarget { #region AssemblySignatureKeyAttributeSetting private string _assemblySignatureKeyAttributeSetting; public string AssemblySignatureKeyAttributeSetting { get { VerifySealed(expected: true); return _assemblySignatureKeyAttributeSetting; } set { VerifySealed(expected: false); _assemblySignatureKeyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDelaySignAttributeSetting private ThreeState _assemblyDelaySignAttributeSetting; public ThreeState AssemblyDelaySignAttributeSetting { get { VerifySealed(expected: true); return _assemblyDelaySignAttributeSetting; } set { VerifySealed(expected: false); _assemblyDelaySignAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyFileAttributeSetting private string _assemblyKeyFileAttributeSetting = StringMissingValue; public string AssemblyKeyFileAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyFileAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyFileAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyContainerAttributeSetting private string _assemblyKeyContainerAttributeSetting = StringMissingValue; public string AssemblyKeyContainerAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyContainerAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyContainerAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyVersionAttributeSetting private Version _assemblyVersionAttributeSetting; /// <summary> /// Raw assembly version as specified in the AssemblyVersionAttribute, or Nothing if none specified. /// If the string passed to AssemblyVersionAttribute contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </summary> public Version AssemblyVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFileVersionAttributeSetting private string _assemblyFileVersionAttributeSetting; public string AssemblyFileVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyFileVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyFileVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTitleAttributeSetting private string _assemblyTitleAttributeSetting; public string AssemblyTitleAttributeSetting { get { VerifySealed(expected: true); return _assemblyTitleAttributeSetting; } set { VerifySealed(expected: false); _assemblyTitleAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDescriptionAttributeSetting private string _assemblyDescriptionAttributeSetting; public string AssemblyDescriptionAttributeSetting { get { VerifySealed(expected: true); return _assemblyDescriptionAttributeSetting; } set { VerifySealed(expected: false); _assemblyDescriptionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCultureAttributeSetting private string _assemblyCultureAttributeSetting; public string AssemblyCultureAttributeSetting { get { VerifySealed(expected: true); return _assemblyCultureAttributeSetting; } set { VerifySealed(expected: false); _assemblyCultureAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCompanyAttributeSetting private string _assemblyCompanyAttributeSetting; public string AssemblyCompanyAttributeSetting { get { VerifySealed(expected: true); return _assemblyCompanyAttributeSetting; } set { VerifySealed(expected: false); _assemblyCompanyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyProductAttributeSetting private string _assemblyProductAttributeSetting; public string AssemblyProductAttributeSetting { get { VerifySealed(expected: true); return _assemblyProductAttributeSetting; } set { VerifySealed(expected: false); _assemblyProductAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyInformationalVersionAttributeSetting private string _assemblyInformationalVersionAttributeSetting; public string AssemblyInformationalVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyInformationalVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyInformationalVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCopyrightAttributeSetting private string _assemblyCopyrightAttributeSetting; public string AssemblyCopyrightAttributeSetting { get { VerifySealed(expected: true); return _assemblyCopyrightAttributeSetting; } set { VerifySealed(expected: false); _assemblyCopyrightAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTrademarkAttributeSetting private string _assemblyTrademarkAttributeSetting; public string AssemblyTrademarkAttributeSetting { get { VerifySealed(expected: true); return _assemblyTrademarkAttributeSetting; } set { VerifySealed(expected: false); _assemblyTrademarkAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFlagsAttributeSetting private AssemblyFlags _assemblyFlagsAttributeSetting; public AssemblyFlags AssemblyFlagsAttributeSetting { get { VerifySealed(expected: true); return _assemblyFlagsAttributeSetting; } set { VerifySealed(expected: false); _assemblyFlagsAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyAlgorithmIdAttribute private AssemblyHashAlgorithm? _assemblyAlgorithmIdAttributeSetting; public AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting { get { VerifySealed(expected: true); return _assemblyAlgorithmIdAttributeSetting; } set { VerifySealed(expected: false); _assemblyAlgorithmIdAttributeSetting = value; SetDataStored(); } } #endregion #region CompilationRelaxationsAttribute private bool _hasCompilationRelaxationsAttribute; public bool HasCompilationRelaxationsAttribute { get { VerifySealed(expected: true); return _hasCompilationRelaxationsAttribute; } set { VerifySealed(expected: false); _hasCompilationRelaxationsAttribute = value; SetDataStored(); } } #endregion #region ReferenceAssemblyAttribute private bool _hasReferenceAssemblyAttribute; public bool HasReferenceAssemblyAttribute { get { VerifySealed(expected: true); return _hasReferenceAssemblyAttribute; } set { VerifySealed(expected: false); _hasReferenceAssemblyAttribute = value; SetDataStored(); } } #endregion #region RuntimeCompatibilityAttribute private bool? _runtimeCompatibilityWrapNonExceptionThrows; // By default WrapNonExceptionThrows is considered to be true. internal const bool WrapNonExceptionThrowsDefault = true; public bool HasRuntimeCompatibilityAttribute { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows.HasValue; } } public bool RuntimeCompatibilityWrapNonExceptionThrows { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows ?? WrapNonExceptionThrowsDefault; } set { VerifySealed(expected: false); _runtimeCompatibilityWrapNonExceptionThrows = value; SetDataStored(); } } #endregion #region DebuggableAttribute private bool _hasDebuggableAttribute; public bool HasDebuggableAttribute { get { VerifySealed(expected: true); return _hasDebuggableAttribute; } set { VerifySealed(expected: false); _hasDebuggableAttribute = value; SetDataStored(); } } #endregion #region Security Attributes private SecurityWellKnownAttributeData _lazySecurityAttributeData; SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazySecurityAttributeData == null) { _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); SetDataStored(); } return _lazySecurityAttributeData; } /// <summary> /// Returns data decoded from security attributes or null if there are no security attributes. /// </summary> public SecurityWellKnownAttributeData SecurityInformation { get { VerifySealed(expected: true); return _lazySecurityAttributeData; } } #endregion #region ForwardedTypes private HashSet<TNamedTypeSymbol> _forwardedTypes; public HashSet<TNamedTypeSymbol> ForwardedTypes { get { return _forwardedTypes; } set { VerifySealed(expected: false); _forwardedTypes = value; SetDataStored(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; using Microsoft.CodeAnalysis.Text; using System.Collections.Generic; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on an assembly. /// </summary> internal class CommonAssemblyWellKnownAttributeData<TNamedTypeSymbol> : WellKnownAttributeData, ISecurityAttributeTarget { #region AssemblySignatureKeyAttributeSetting private string _assemblySignatureKeyAttributeSetting; public string AssemblySignatureKeyAttributeSetting { get { VerifySealed(expected: true); return _assemblySignatureKeyAttributeSetting; } set { VerifySealed(expected: false); _assemblySignatureKeyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDelaySignAttributeSetting private ThreeState _assemblyDelaySignAttributeSetting; public ThreeState AssemblyDelaySignAttributeSetting { get { VerifySealed(expected: true); return _assemblyDelaySignAttributeSetting; } set { VerifySealed(expected: false); _assemblyDelaySignAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyFileAttributeSetting private string _assemblyKeyFileAttributeSetting = StringMissingValue; public string AssemblyKeyFileAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyFileAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyFileAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyKeyContainerAttributeSetting private string _assemblyKeyContainerAttributeSetting = StringMissingValue; public string AssemblyKeyContainerAttributeSetting { get { VerifySealed(expected: true); return _assemblyKeyContainerAttributeSetting; } set { VerifySealed(expected: false); _assemblyKeyContainerAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyVersionAttributeSetting private Version _assemblyVersionAttributeSetting; /// <summary> /// Raw assembly version as specified in the AssemblyVersionAttribute, or Nothing if none specified. /// If the string passed to AssemblyVersionAttribute contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </summary> public Version AssemblyVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFileVersionAttributeSetting private string _assemblyFileVersionAttributeSetting; public string AssemblyFileVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyFileVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyFileVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTitleAttributeSetting private string _assemblyTitleAttributeSetting; public string AssemblyTitleAttributeSetting { get { VerifySealed(expected: true); return _assemblyTitleAttributeSetting; } set { VerifySealed(expected: false); _assemblyTitleAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyDescriptionAttributeSetting private string _assemblyDescriptionAttributeSetting; public string AssemblyDescriptionAttributeSetting { get { VerifySealed(expected: true); return _assemblyDescriptionAttributeSetting; } set { VerifySealed(expected: false); _assemblyDescriptionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCultureAttributeSetting private string _assemblyCultureAttributeSetting; public string AssemblyCultureAttributeSetting { get { VerifySealed(expected: true); return _assemblyCultureAttributeSetting; } set { VerifySealed(expected: false); _assemblyCultureAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCompanyAttributeSetting private string _assemblyCompanyAttributeSetting; public string AssemblyCompanyAttributeSetting { get { VerifySealed(expected: true); return _assemblyCompanyAttributeSetting; } set { VerifySealed(expected: false); _assemblyCompanyAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyProductAttributeSetting private string _assemblyProductAttributeSetting; public string AssemblyProductAttributeSetting { get { VerifySealed(expected: true); return _assemblyProductAttributeSetting; } set { VerifySealed(expected: false); _assemblyProductAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyInformationalVersionAttributeSetting private string _assemblyInformationalVersionAttributeSetting; public string AssemblyInformationalVersionAttributeSetting { get { VerifySealed(expected: true); return _assemblyInformationalVersionAttributeSetting; } set { VerifySealed(expected: false); _assemblyInformationalVersionAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyCopyrightAttributeSetting private string _assemblyCopyrightAttributeSetting; public string AssemblyCopyrightAttributeSetting { get { VerifySealed(expected: true); return _assemblyCopyrightAttributeSetting; } set { VerifySealed(expected: false); _assemblyCopyrightAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyTrademarkAttributeSetting private string _assemblyTrademarkAttributeSetting; public string AssemblyTrademarkAttributeSetting { get { VerifySealed(expected: true); return _assemblyTrademarkAttributeSetting; } set { VerifySealed(expected: false); _assemblyTrademarkAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyFlagsAttributeSetting private AssemblyFlags _assemblyFlagsAttributeSetting; public AssemblyFlags AssemblyFlagsAttributeSetting { get { VerifySealed(expected: true); return _assemblyFlagsAttributeSetting; } set { VerifySealed(expected: false); _assemblyFlagsAttributeSetting = value; SetDataStored(); } } #endregion #region AssemblyAlgorithmIdAttribute private AssemblyHashAlgorithm? _assemblyAlgorithmIdAttributeSetting; public AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting { get { VerifySealed(expected: true); return _assemblyAlgorithmIdAttributeSetting; } set { VerifySealed(expected: false); _assemblyAlgorithmIdAttributeSetting = value; SetDataStored(); } } #endregion #region CompilationRelaxationsAttribute private bool _hasCompilationRelaxationsAttribute; public bool HasCompilationRelaxationsAttribute { get { VerifySealed(expected: true); return _hasCompilationRelaxationsAttribute; } set { VerifySealed(expected: false); _hasCompilationRelaxationsAttribute = value; SetDataStored(); } } #endregion #region ReferenceAssemblyAttribute private bool _hasReferenceAssemblyAttribute; public bool HasReferenceAssemblyAttribute { get { VerifySealed(expected: true); return _hasReferenceAssemblyAttribute; } set { VerifySealed(expected: false); _hasReferenceAssemblyAttribute = value; SetDataStored(); } } #endregion #region RuntimeCompatibilityAttribute private bool? _runtimeCompatibilityWrapNonExceptionThrows; // By default WrapNonExceptionThrows is considered to be true. internal const bool WrapNonExceptionThrowsDefault = true; public bool HasRuntimeCompatibilityAttribute { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows.HasValue; } } public bool RuntimeCompatibilityWrapNonExceptionThrows { get { VerifySealed(expected: true); return _runtimeCompatibilityWrapNonExceptionThrows ?? WrapNonExceptionThrowsDefault; } set { VerifySealed(expected: false); _runtimeCompatibilityWrapNonExceptionThrows = value; SetDataStored(); } } #endregion #region DebuggableAttribute private bool _hasDebuggableAttribute; public bool HasDebuggableAttribute { get { VerifySealed(expected: true); return _hasDebuggableAttribute; } set { VerifySealed(expected: false); _hasDebuggableAttribute = value; SetDataStored(); } } #endregion #region Security Attributes private SecurityWellKnownAttributeData _lazySecurityAttributeData; SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazySecurityAttributeData == null) { _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); SetDataStored(); } return _lazySecurityAttributeData; } /// <summary> /// Returns data decoded from security attributes or null if there are no security attributes. /// </summary> public SecurityWellKnownAttributeData SecurityInformation { get { VerifySealed(expected: true); return _lazySecurityAttributeData; } } #endregion #region ForwardedTypes private HashSet<TNamedTypeSymbol> _forwardedTypes; public HashSet<TNamedTypeSymbol> ForwardedTypes { get { return _forwardedTypes; } set { VerifySealed(expected: false); _forwardedTypes = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/CodeAnalysisTest/FileSystem/RelativePathResolverTests.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 Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RelativePathResolverTests : TestBase { [ConditionalFact(typeof(WindowsOnly))] public void ResolveMetadataFile1() { string fileName = "f.dll"; string drive = "C"; string dir = @"C:\dir"; string subdir = @"C:\dir\subdir"; string filePath = dir + @"\" + fileName; string subFilePath = subdir + @"\" + fileName; string dotted = subdir + @"\" + ".x.dll"; var fs = new HashSet<string> { filePath, subFilePath, dotted }; var resolver = new VirtualizedRelativePathResolver( existingFullPaths: fs, searchPaths: ImmutableArray.Create<string>(), baseDirectory: subdir); // unqualified file name: var path = resolver.ResolvePath(fileName, baseFilePath: null); Assert.Equal(subFilePath, path); // prefer the base file over base directory: path = resolver.ResolvePath(fileName, baseFilePath: PathUtilities.CombineAbsoluteAndRelativePaths(dir, "goo.csx")); Assert.Equal(filePath, path); path = resolver.ResolvePath(@"\" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@"/" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@".", baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@".\" + fileName, baseFilePath: null); Assert.Equal(subFilePath, path); path = resolver.ResolvePath(@"./" + fileName, baseFilePath: null); Assert.Equal(subFilePath, path); path = resolver.ResolvePath(@".x.dll", baseFilePath: null); Assert.Equal(dotted, path); path = resolver.ResolvePath(@"..", baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@"..\" + fileName, baseFilePath: null); Assert.Equal(filePath, path); path = resolver.ResolvePath(@"../" + fileName, baseFilePath: null); Assert.Equal(filePath, path); path = resolver.ResolvePath(@"C:\" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@"C:/" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(filePath, baseFilePath: null); Assert.Equal(filePath, path); // drive-relative paths not supported: path = resolver.ResolvePath(drive + ":" + fileName, baseFilePath: null); Assert.Null(path); // \abc\def string rooted = filePath.Substring(2); path = resolver.ResolvePath(rooted, null); Assert.Equal(filePath, path); } [ConditionalFact(typeof(WindowsOnly))] public void ResolveMetadataFile2() { string fileName = "f.dll"; string dir = @"C:\dir"; string subdir = @"C:\dir\subdir"; string filePath = dir + @"\" + fileName; string subFilePath = subdir + @"\" + fileName; var fs = new HashSet<string> { filePath, subFilePath }; // with no search paths var resolver = new VirtualizedRelativePathResolver( existingFullPaths: fs, baseDirectory: subdir); // using base path var path = resolver.ResolvePath(fileName, baseFilePath: PathUtilities.CombineAbsoluteAndRelativePaths(dir, "goo.csx")); Assert.Equal(filePath, path); // using base dir path = resolver.ResolvePath(fileName, baseFilePath: null); Assert.Equal(subFilePath, path); // search paths var resolverSP = new VirtualizedRelativePathResolver( existingFullPaths: fs, searchPaths: new[] { dir, subdir }.AsImmutableOrNull(), baseDirectory: @"C:\goo"); path = resolverSP.ResolvePath(fileName, baseFilePath: null); Assert.Equal(filePath, path); // null base dir, no search paths var resolverNullBase = new VirtualizedRelativePathResolver( existingFullPaths: fs, baseDirectory: null); // relative path path = resolverNullBase.ResolvePath(fileName, baseFilePath: null); Assert.Null(path); // full path path = resolverNullBase.ResolvePath(filePath, baseFilePath: null); Assert.Equal(filePath, path); // null base dir var resolverNullBaseSP = new VirtualizedRelativePathResolver( existingFullPaths: fs, searchPaths: new[] { dir, subdir }.AsImmutableOrNull(), baseDirectory: null); // relative path path = resolverNullBaseSP.ResolvePath(fileName, baseFilePath: null); Assert.Equal(filePath, path); // full path path = resolverNullBaseSP.ResolvePath(filePath, baseFilePath: null); Assert.Equal(filePath, path); } [Fact] public void ResolvePath_Order() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("dir1"); var dir2 = dir.CreateDirectory("dir2"); var f1 = dir1.CreateFile("f.dll").Path; var f2 = dir2.CreateFile("f.dll").Path; var resolver = new RelativePathResolver( ImmutableArray.Create(dir1.Path, dir2.Path), baseDirectory: null); var path = resolver.ResolvePath("f.dll", null); Assert.Equal(f1, path); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RelativePathResolverTests : TestBase { [ConditionalFact(typeof(WindowsOnly))] public void ResolveMetadataFile1() { string fileName = "f.dll"; string drive = "C"; string dir = @"C:\dir"; string subdir = @"C:\dir\subdir"; string filePath = dir + @"\" + fileName; string subFilePath = subdir + @"\" + fileName; string dotted = subdir + @"\" + ".x.dll"; var fs = new HashSet<string> { filePath, subFilePath, dotted }; var resolver = new VirtualizedRelativePathResolver( existingFullPaths: fs, searchPaths: ImmutableArray.Create<string>(), baseDirectory: subdir); // unqualified file name: var path = resolver.ResolvePath(fileName, baseFilePath: null); Assert.Equal(subFilePath, path); // prefer the base file over base directory: path = resolver.ResolvePath(fileName, baseFilePath: PathUtilities.CombineAbsoluteAndRelativePaths(dir, "goo.csx")); Assert.Equal(filePath, path); path = resolver.ResolvePath(@"\" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@"/" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@".", baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@".\" + fileName, baseFilePath: null); Assert.Equal(subFilePath, path); path = resolver.ResolvePath(@"./" + fileName, baseFilePath: null); Assert.Equal(subFilePath, path); path = resolver.ResolvePath(@".x.dll", baseFilePath: null); Assert.Equal(dotted, path); path = resolver.ResolvePath(@"..", baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@"..\" + fileName, baseFilePath: null); Assert.Equal(filePath, path); path = resolver.ResolvePath(@"../" + fileName, baseFilePath: null); Assert.Equal(filePath, path); path = resolver.ResolvePath(@"C:\" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(@"C:/" + fileName, baseFilePath: null); Assert.Null(path); path = resolver.ResolvePath(filePath, baseFilePath: null); Assert.Equal(filePath, path); // drive-relative paths not supported: path = resolver.ResolvePath(drive + ":" + fileName, baseFilePath: null); Assert.Null(path); // \abc\def string rooted = filePath.Substring(2); path = resolver.ResolvePath(rooted, null); Assert.Equal(filePath, path); } [ConditionalFact(typeof(WindowsOnly))] public void ResolveMetadataFile2() { string fileName = "f.dll"; string dir = @"C:\dir"; string subdir = @"C:\dir\subdir"; string filePath = dir + @"\" + fileName; string subFilePath = subdir + @"\" + fileName; var fs = new HashSet<string> { filePath, subFilePath }; // with no search paths var resolver = new VirtualizedRelativePathResolver( existingFullPaths: fs, baseDirectory: subdir); // using base path var path = resolver.ResolvePath(fileName, baseFilePath: PathUtilities.CombineAbsoluteAndRelativePaths(dir, "goo.csx")); Assert.Equal(filePath, path); // using base dir path = resolver.ResolvePath(fileName, baseFilePath: null); Assert.Equal(subFilePath, path); // search paths var resolverSP = new VirtualizedRelativePathResolver( existingFullPaths: fs, searchPaths: new[] { dir, subdir }.AsImmutableOrNull(), baseDirectory: @"C:\goo"); path = resolverSP.ResolvePath(fileName, baseFilePath: null); Assert.Equal(filePath, path); // null base dir, no search paths var resolverNullBase = new VirtualizedRelativePathResolver( existingFullPaths: fs, baseDirectory: null); // relative path path = resolverNullBase.ResolvePath(fileName, baseFilePath: null); Assert.Null(path); // full path path = resolverNullBase.ResolvePath(filePath, baseFilePath: null); Assert.Equal(filePath, path); // null base dir var resolverNullBaseSP = new VirtualizedRelativePathResolver( existingFullPaths: fs, searchPaths: new[] { dir, subdir }.AsImmutableOrNull(), baseDirectory: null); // relative path path = resolverNullBaseSP.ResolvePath(fileName, baseFilePath: null); Assert.Equal(filePath, path); // full path path = resolverNullBaseSP.ResolvePath(filePath, baseFilePath: null); Assert.Equal(filePath, path); } [Fact] public void ResolvePath_Order() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("dir1"); var dir2 = dir.CreateDirectory("dir2"); var f1 = dir1.CreateFile("f.dll").Path; var f2 = dir2.CreateFile("f.dll").Path; var resolver = new RelativePathResolver( ImmutableArray.Create(dir1.Path, dir2.Path), baseDirectory: null); var path = resolver.ResolvePath("f.dll", null); Assert.Equal(f1, path); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Syntax/Parsing/NameParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NameParsingTests { private NameSyntax ParseName(string text) { return SyntaxFactory.ParseName(text); } private TypeSyntax ParseTypeName(string text) { return SyntaxFactory.ParseTypeName(text); } [Fact] public void TestBasicName() { var text = "goo"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(((IdentifierNameSyntax)name).Identifier.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestBasicNameWithTrash() { var text = "/*comment*/goo/*comment2*/ bar"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(((IdentifierNameSyntax)name).Identifier.IsMissing); Assert.Equal(1, name.Errors().Length); Assert.Equal(text, name.ToFullString()); } [Fact] public void TestMissingName() { var text = string.Empty; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(((IdentifierNameSyntax)name).Identifier.IsMissing); Assert.Equal(1, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, name.Errors()[0].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestMissingNameDueToKeyword() { var text = "class"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(name.IsMissing); Assert.Equal(2, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedToken, name.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, name.Errors()[1].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestMissingNameDueToPartialClassStart() { var text = "partial class"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(name.IsMissing); Assert.Equal(2, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedToken, name.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, name.Errors()[1].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestMissingNameDueToPartialMethodStart() { var text = "partial void Method()"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(name.IsMissing); Assert.Equal(2, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedToken, name.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, name.Errors()[1].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestAliasedName() { var text = "goo::bar"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestGlobalAliasedName() { var text = "global::bar"; var name = ParseName(text); Assert.NotNull(name); Assert.False(name.IsMissing); Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); var an = (AliasQualifiedNameSyntax)name; Assert.Equal(SyntaxKind.GlobalKeyword, an.Alias.Identifier.Kind()); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestDottedName() { var text = "goo.bar"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.QualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestAliasedDottedName() { var text = "goo::bar.Zed"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.QualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); name = ((QualifiedNameSyntax)name).Left; Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestDoubleAliasName() { // In the original implementation of the parser this error case was parsed as // // (goo :: bar ) :: baz // // However, we have decided that the left hand side of a :: should always be // an identifier, not a name, even in error cases. Therefore instead we // parse this as though the error was that the user intended to make the // second :: a dot; we parse this as // // (goo :: bar ) . baz var text = "goo::bar::baz"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.QualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(1, name.Errors().Length); Assert.Equal(text, name.ToString()); name = ((QualifiedNameSyntax)name).Left; Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestGenericName() { var text = "goo<bar>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestGenericNameWithTwoArguments() { var text = "goo<bar,zed>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(2, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestNestedGenericName() { var text = "goo<bar<zed>>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); Assert.Equal(SyntaxKind.GenericName, gname.TypeArgumentList.Arguments[0].Kind()); Assert.Equal(text, name.ToString()); } [Fact] public void TestOpenNameWithNoCommas() { var text = "goo<>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.Equal(0, gname.TypeArgumentList.Arguments.SeparatorCount); Assert.True(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestOpenNameWithAComma() { var text = "goo<,>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(2, gname.TypeArgumentList.Arguments.Count); Assert.Equal(1, gname.TypeArgumentList.Arguments.SeparatorCount); Assert.True(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestBasicTypeName() { var text = "goo"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.IdentifierName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestDottedTypeName() { var text = "goo.bar"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.QualifiedName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestGenericTypeName() { var text = "goo<bar>"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestNestedGenericTypeName() { var text = "goo<bar<zed>>"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); Assert.Equal(SyntaxKind.GenericName, gname.TypeArgumentList.Arguments[0].Kind()); Assert.Equal(text, name.ToString()); } [Fact] public void TestOpenTypeNameWithNoCommas() { var text = "goo<>"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.Equal(0, gname.TypeArgumentList.Arguments.SeparatorCount); Assert.True(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestKnownTypeNames() { ParseKnownTypeName(SyntaxKind.BoolKeyword); ParseKnownTypeName(SyntaxKind.ByteKeyword); ParseKnownTypeName(SyntaxKind.SByteKeyword); ParseKnownTypeName(SyntaxKind.ShortKeyword); ParseKnownTypeName(SyntaxKind.UShortKeyword); ParseKnownTypeName(SyntaxKind.IntKeyword); ParseKnownTypeName(SyntaxKind.UIntKeyword); ParseKnownTypeName(SyntaxKind.LongKeyword); ParseKnownTypeName(SyntaxKind.ULongKeyword); ParseKnownTypeName(SyntaxKind.FloatKeyword); ParseKnownTypeName(SyntaxKind.DoubleKeyword); ParseKnownTypeName(SyntaxKind.DecimalKeyword); ParseKnownTypeName(SyntaxKind.StringKeyword); ParseKnownTypeName(SyntaxKind.ObjectKeyword); } private void ParseKnownTypeName(SyntaxKind kind) { var text = SyntaxFacts.GetText(kind); var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.PredefinedType, tname.Kind()); Assert.Equal(text, tname.ToString()); var tok = ((PredefinedTypeSyntax)tname).Keyword; Assert.Equal(kind, tok.Kind()); } [Fact] public void TestNullableTypeName() { var text = "goo?"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.NullableType, tname.Kind()); Assert.Equal(text, tname.ToString()); var name = (NameSyntax)((NullableTypeSyntax)tname).ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestPointerTypeName() { var text = "goo*"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.PointerType, tname.Kind()); Assert.Equal(text, tname.ToString()); var name = (NameSyntax)((PointerTypeSyntax)tname).ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestPointerTypeNameWithMultipleAsterisks() { var text = "goo***"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.PointerType, tname.Kind()); // check depth of pointer defers int depth = 0; while (tname.Kind() == SyntaxKind.PointerType) { tname = ((PointerTypeSyntax)tname).ElementType; depth++; } Assert.Equal(3, depth); var name = (NameSyntax)tname; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestArrayTypeName() { var text = "goo[]"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.ArrayType, tname.Kind()); var array = (ArrayTypeSyntax)tname; Assert.Equal(1, array.RankSpecifiers.Count); Assert.Equal(1, array.RankSpecifiers[0].Sizes.Count); Assert.Equal(0, array.RankSpecifiers[0].Sizes.SeparatorCount); Assert.Equal(1, array.RankSpecifiers[0].Rank); var name = (NameSyntax)array.ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestMultiDimensionalArrayTypeName() { var text = "goo[,,]"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.ArrayType, tname.Kind()); var array = (ArrayTypeSyntax)tname; Assert.Equal(1, array.RankSpecifiers.Count); Assert.Equal(3, array.RankSpecifiers[0].Sizes.Count); Assert.Equal(2, array.RankSpecifiers[0].Sizes.SeparatorCount); Assert.Equal(3, array.RankSpecifiers[0].Rank); var name = (NameSyntax)array.ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestMultiRankedArrayTypeName() { var text = "goo[][,][,,]"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.ArrayType, tname.Kind()); var array = (ArrayTypeSyntax)tname; Assert.Equal(3, array.RankSpecifiers.Count); Assert.Equal(1, array.RankSpecifiers[0].Sizes.Count); Assert.Equal(0, array.RankSpecifiers[0].Sizes.SeparatorCount); Assert.Equal(1, array.RankSpecifiers[0].Rank); Assert.Equal(2, array.RankSpecifiers[1].Sizes.Count); Assert.Equal(1, array.RankSpecifiers[1].Sizes.SeparatorCount); Assert.Equal(2, array.RankSpecifiers[1].Rank); Assert.Equal(3, array.RankSpecifiers[2].Sizes.Count); Assert.Equal(2, array.RankSpecifiers[2].Sizes.SeparatorCount); Assert.Equal(3, array.RankSpecifiers[2].Rank); var name = (NameSyntax)array.ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestVarianceInNameBad() { var text = "goo<in bar>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IllegalVarianceSyntax, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [Fact] public void TestAttributeInNameBad() { var text = "goo<[My]bar>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [WorkItem(7177, "https://github.com/dotnet/roslyn/issues/7177")] [Fact] public void TestConstantInGenericNameBad() { var text = "goo<0>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [WorkItem(7177, "https://github.com/dotnet/roslyn/issues/7177")] [Fact] public void TestConstantInGenericNamePartiallyBad() { var text = "goo<0,bool>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(2, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); Assert.NotNull(gname.TypeArgumentList.Arguments[1]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); var arg2 = gname.TypeArgumentList.Arguments[1]; Assert.Equal(SyntaxKind.PredefinedType, arg2.Kind()); Assert.False(arg2.ContainsDiagnostics); Assert.Equal(0, arg2.Errors().Length); Assert.Equal(text, tname.ToString()); } [WorkItem(7177, "https://github.com/dotnet/roslyn/issues/7177")] [Fact] public void TestKeywordInGenericNameBad() { var text = "goo<static>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [Fact] public void TestAttributeAndVarianceInNameBad() { var text = "goo<[My]in bar>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(2, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IllegalVarianceSyntax, arg.Errors()[1].Code); Assert.Equal(text, tname.ToString()); } [WorkItem(545778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545778")] [Fact] public void TestFormattingCharacter() { var text = "\u0915\u094d\u200d\u0937"; var tok = SyntaxFactory.ParseToken(text); Assert.NotEqual(default, tok); Assert.Equal(text, tok.ToString()); Assert.NotEqual(text, tok.ValueText); Assert.Equal("\u0915\u094d\u0937", tok.ValueText); //formatting character \u200d removed Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters(text)); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters(tok.ValueText)); } [WorkItem(959148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/959148")] [Fact] public void TestSoftHyphen() { var text = "x\u00ady"; var tok = SyntaxFactory.ParseToken(text); Assert.NotEqual(default, tok); Assert.Equal(text, tok.ToString()); Assert.NotEqual(text, tok.ValueText); Assert.Equal("xy", tok.ValueText); // formatting character SOFT HYPHEN (U+00AD) removed Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters(text)); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters(tok.ValueText)); } [WorkItem(545778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545778")] [Fact] public void ContainsDroppedIdentifierCharacters() { Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters(null)); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters("")); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters("a")); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters("a@")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("@")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("@a")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("\u200d")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("a\u200d")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NameParsingTests { private NameSyntax ParseName(string text) { return SyntaxFactory.ParseName(text); } private TypeSyntax ParseTypeName(string text) { return SyntaxFactory.ParseTypeName(text); } [Fact] public void TestBasicName() { var text = "goo"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(((IdentifierNameSyntax)name).Identifier.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestBasicNameWithTrash() { var text = "/*comment*/goo/*comment2*/ bar"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(((IdentifierNameSyntax)name).Identifier.IsMissing); Assert.Equal(1, name.Errors().Length); Assert.Equal(text, name.ToFullString()); } [Fact] public void TestMissingName() { var text = string.Empty; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(((IdentifierNameSyntax)name).Identifier.IsMissing); Assert.Equal(1, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, name.Errors()[0].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestMissingNameDueToKeyword() { var text = "class"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(name.IsMissing); Assert.Equal(2, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedToken, name.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, name.Errors()[1].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestMissingNameDueToPartialClassStart() { var text = "partial class"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(name.IsMissing); Assert.Equal(2, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedToken, name.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, name.Errors()[1].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestMissingNameDueToPartialMethodStart() { var text = "partial void Method()"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.True(name.IsMissing); Assert.Equal(2, name.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedToken, name.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, name.Errors()[1].Code); Assert.Equal(string.Empty, name.ToString()); } [Fact] public void TestAliasedName() { var text = "goo::bar"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestGlobalAliasedName() { var text = "global::bar"; var name = ParseName(text); Assert.NotNull(name); Assert.False(name.IsMissing); Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); var an = (AliasQualifiedNameSyntax)name; Assert.Equal(SyntaxKind.GlobalKeyword, an.Alias.Identifier.Kind()); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestDottedName() { var text = "goo.bar"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.QualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestAliasedDottedName() { var text = "goo::bar.Zed"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.QualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); name = ((QualifiedNameSyntax)name).Left; Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestDoubleAliasName() { // In the original implementation of the parser this error case was parsed as // // (goo :: bar ) :: baz // // However, we have decided that the left hand side of a :: should always be // an identifier, not a name, even in error cases. Therefore instead we // parse this as though the error was that the user intended to make the // second :: a dot; we parse this as // // (goo :: bar ) . baz var text = "goo::bar::baz"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.QualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(1, name.Errors().Length); Assert.Equal(text, name.ToString()); name = ((QualifiedNameSyntax)name).Left; Assert.Equal(SyntaxKind.AliasQualifiedName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestGenericName() { var text = "goo<bar>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestGenericNameWithTwoArguments() { var text = "goo<bar,zed>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(2, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestNestedGenericName() { var text = "goo<bar<zed>>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); Assert.Equal(SyntaxKind.GenericName, gname.TypeArgumentList.Arguments[0].Kind()); Assert.Equal(text, name.ToString()); } [Fact] public void TestOpenNameWithNoCommas() { var text = "goo<>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.Equal(0, gname.TypeArgumentList.Arguments.SeparatorCount); Assert.True(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestOpenNameWithAComma() { var text = "goo<,>"; var name = ParseName(text); Assert.NotNull(name); Assert.Equal(SyntaxKind.GenericName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(2, gname.TypeArgumentList.Arguments.Count); Assert.Equal(1, gname.TypeArgumentList.Arguments.SeparatorCount); Assert.True(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestBasicTypeName() { var text = "goo"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.IdentifierName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestDottedTypeName() { var text = "goo.bar"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.QualifiedName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); Assert.Equal(text, name.ToString()); } [Fact] public void TestGenericTypeName() { var text = "goo<bar>"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestNestedGenericTypeName() { var text = "goo<bar<zed>>"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.False(gname.IsUnboundGenericName); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); Assert.Equal(SyntaxKind.GenericName, gname.TypeArgumentList.Arguments[0].Kind()); Assert.Equal(text, name.ToString()); } [Fact] public void TestOpenTypeNameWithNoCommas() { var text = "goo<>"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var name = (NameSyntax)tname; Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); var gname = (GenericNameSyntax)name; Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.Equal(0, gname.TypeArgumentList.Arguments.SeparatorCount); Assert.True(gname.IsUnboundGenericName); Assert.Equal(text, name.ToString()); } [Fact] public void TestKnownTypeNames() { ParseKnownTypeName(SyntaxKind.BoolKeyword); ParseKnownTypeName(SyntaxKind.ByteKeyword); ParseKnownTypeName(SyntaxKind.SByteKeyword); ParseKnownTypeName(SyntaxKind.ShortKeyword); ParseKnownTypeName(SyntaxKind.UShortKeyword); ParseKnownTypeName(SyntaxKind.IntKeyword); ParseKnownTypeName(SyntaxKind.UIntKeyword); ParseKnownTypeName(SyntaxKind.LongKeyword); ParseKnownTypeName(SyntaxKind.ULongKeyword); ParseKnownTypeName(SyntaxKind.FloatKeyword); ParseKnownTypeName(SyntaxKind.DoubleKeyword); ParseKnownTypeName(SyntaxKind.DecimalKeyword); ParseKnownTypeName(SyntaxKind.StringKeyword); ParseKnownTypeName(SyntaxKind.ObjectKeyword); } private void ParseKnownTypeName(SyntaxKind kind) { var text = SyntaxFacts.GetText(kind); var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.PredefinedType, tname.Kind()); Assert.Equal(text, tname.ToString()); var tok = ((PredefinedTypeSyntax)tname).Keyword; Assert.Equal(kind, tok.Kind()); } [Fact] public void TestNullableTypeName() { var text = "goo?"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.NullableType, tname.Kind()); Assert.Equal(text, tname.ToString()); var name = (NameSyntax)((NullableTypeSyntax)tname).ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestPointerTypeName() { var text = "goo*"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(SyntaxKind.PointerType, tname.Kind()); Assert.Equal(text, tname.ToString()); var name = (NameSyntax)((PointerTypeSyntax)tname).ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestPointerTypeNameWithMultipleAsterisks() { var text = "goo***"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.PointerType, tname.Kind()); // check depth of pointer defers int depth = 0; while (tname.Kind() == SyntaxKind.PointerType) { tname = ((PointerTypeSyntax)tname).ElementType; depth++; } Assert.Equal(3, depth); var name = (NameSyntax)tname; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestArrayTypeName() { var text = "goo[]"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.ArrayType, tname.Kind()); var array = (ArrayTypeSyntax)tname; Assert.Equal(1, array.RankSpecifiers.Count); Assert.Equal(1, array.RankSpecifiers[0].Sizes.Count); Assert.Equal(0, array.RankSpecifiers[0].Sizes.SeparatorCount); Assert.Equal(1, array.RankSpecifiers[0].Rank); var name = (NameSyntax)array.ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestMultiDimensionalArrayTypeName() { var text = "goo[,,]"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.ArrayType, tname.Kind()); var array = (ArrayTypeSyntax)tname; Assert.Equal(1, array.RankSpecifiers.Count); Assert.Equal(3, array.RankSpecifiers[0].Sizes.Count); Assert.Equal(2, array.RankSpecifiers[0].Sizes.SeparatorCount); Assert.Equal(3, array.RankSpecifiers[0].Rank); var name = (NameSyntax)array.ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestMultiRankedArrayTypeName() { var text = "goo[][,][,,]"; var tname = ParseTypeName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.ArrayType, tname.Kind()); var array = (ArrayTypeSyntax)tname; Assert.Equal(3, array.RankSpecifiers.Count); Assert.Equal(1, array.RankSpecifiers[0].Sizes.Count); Assert.Equal(0, array.RankSpecifiers[0].Sizes.SeparatorCount); Assert.Equal(1, array.RankSpecifiers[0].Rank); Assert.Equal(2, array.RankSpecifiers[1].Sizes.Count); Assert.Equal(1, array.RankSpecifiers[1].Sizes.SeparatorCount); Assert.Equal(2, array.RankSpecifiers[1].Rank); Assert.Equal(3, array.RankSpecifiers[2].Sizes.Count); Assert.Equal(2, array.RankSpecifiers[2].Sizes.SeparatorCount); Assert.Equal(3, array.RankSpecifiers[2].Rank); var name = (NameSyntax)array.ElementType; Assert.Equal(SyntaxKind.IdentifierName, name.Kind()); Assert.False(name.IsMissing); Assert.Equal(0, name.Errors().Length); } [Fact] public void TestVarianceInNameBad() { var text = "goo<in bar>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IllegalVarianceSyntax, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [Fact] public void TestAttributeInNameBad() { var text = "goo<[My]bar>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [WorkItem(7177, "https://github.com/dotnet/roslyn/issues/7177")] [Fact] public void TestConstantInGenericNameBad() { var text = "goo<0>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [WorkItem(7177, "https://github.com/dotnet/roslyn/issues/7177")] [Fact] public void TestConstantInGenericNamePartiallyBad() { var text = "goo<0,bool>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(2, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); Assert.NotNull(gname.TypeArgumentList.Arguments[1]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); var arg2 = gname.TypeArgumentList.Arguments[1]; Assert.Equal(SyntaxKind.PredefinedType, arg2.Kind()); Assert.False(arg2.ContainsDiagnostics); Assert.Equal(0, arg2.Errors().Length); Assert.Equal(text, tname.ToString()); } [WorkItem(7177, "https://github.com/dotnet/roslyn/issues/7177")] [Fact] public void TestKeywordInGenericNameBad() { var text = "goo<static>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(1, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal(text, tname.ToString()); } [Fact] public void TestAttributeAndVarianceInNameBad() { var text = "goo<[My]in bar>"; var tname = ParseName(text); Assert.NotNull(tname); Assert.Equal(text, tname.ToString()); Assert.Equal(SyntaxKind.GenericName, tname.Kind()); var gname = (GenericNameSyntax)tname; Assert.Equal("goo", gname.Identifier.ToString()); Assert.False(gname.IsUnboundGenericName); Assert.Equal(1, gname.TypeArgumentList.Arguments.Count); Assert.NotNull(gname.TypeArgumentList.Arguments[0]); var arg = gname.TypeArgumentList.Arguments[0]; Assert.Equal(SyntaxKind.IdentifierName, arg.Kind()); Assert.True(arg.ContainsDiagnostics); Assert.Equal(2, arg.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, arg.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IllegalVarianceSyntax, arg.Errors()[1].Code); Assert.Equal(text, tname.ToString()); } [WorkItem(545778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545778")] [Fact] public void TestFormattingCharacter() { var text = "\u0915\u094d\u200d\u0937"; var tok = SyntaxFactory.ParseToken(text); Assert.NotEqual(default, tok); Assert.Equal(text, tok.ToString()); Assert.NotEqual(text, tok.ValueText); Assert.Equal("\u0915\u094d\u0937", tok.ValueText); //formatting character \u200d removed Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters(text)); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters(tok.ValueText)); } [WorkItem(959148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/959148")] [Fact] public void TestSoftHyphen() { var text = "x\u00ady"; var tok = SyntaxFactory.ParseToken(text); Assert.NotEqual(default, tok); Assert.Equal(text, tok.ToString()); Assert.NotEqual(text, tok.ValueText); Assert.Equal("xy", tok.ValueText); // formatting character SOFT HYPHEN (U+00AD) removed Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters(text)); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters(tok.ValueText)); } [WorkItem(545778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545778")] [Fact] public void ContainsDroppedIdentifierCharacters() { Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters(null)); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters("")); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters("a")); Assert.False(SyntaxFacts.ContainsDroppedIdentifierCharacters("a@")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("@")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("@a")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("\u200d")); Assert.True(SyntaxFacts.ContainsDroppedIdentifierCharacters("a\u200d")); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/OperatorPlacementWhenWrappingPreference.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.CodeStyle { internal enum OperatorPlacementWhenWrappingPreference { BeginningOfLine, EndOfLine, } internal static class OperatorPlacementUtilities { private const string end_of_line = "end_of_line"; private const string beginning_of_line = "beginning_of_line"; // Default to beginning_of_line if we don't know the value. public static string GetEditorConfigString(OperatorPlacementWhenWrappingPreference value) => value == OperatorPlacementWhenWrappingPreference.EndOfLine ? end_of_line : beginning_of_line; public static Optional<OperatorPlacementWhenWrappingPreference> Parse(string optionString) { if (CodeStyleHelpers.TryGetCodeStyleValue(optionString, out var value)) { switch (value) { case end_of_line: return OperatorPlacementWhenWrappingPreference.EndOfLine; case beginning_of_line: return OperatorPlacementWhenWrappingPreference.BeginningOfLine; } } // Default to beginning_of_line if we get something we don't understand. return OperatorPlacementWhenWrappingPreference.BeginningOfLine; } } }
// Licensed to the .NET Foundation under one or more 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.CodeStyle { internal enum OperatorPlacementWhenWrappingPreference { BeginningOfLine, EndOfLine, } internal static class OperatorPlacementUtilities { private const string end_of_line = "end_of_line"; private const string beginning_of_line = "beginning_of_line"; // Default to beginning_of_line if we don't know the value. public static string GetEditorConfigString(OperatorPlacementWhenWrappingPreference value) => value == OperatorPlacementWhenWrappingPreference.EndOfLine ? end_of_line : beginning_of_line; public static Optional<OperatorPlacementWhenWrappingPreference> Parse(string optionString) { if (CodeStyleHelpers.TryGetCodeStyleValue(optionString, out var value)) { switch (value) { case end_of_line: return OperatorPlacementWhenWrappingPreference.EndOfLine; case beginning_of_line: return OperatorPlacementWhenWrappingPreference.BeginningOfLine; } } // Default to beginning_of_line if we get something we don't understand. return OperatorPlacementWhenWrappingPreference.BeginningOfLine; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MisplacedUsingDirectives { public class MisplacedUsingDirectivesInCompilationUnitCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MisplacedUsingDirectivesInCompilationUnitCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new MisplacedUsingDirectivesDiagnosticAnalyzer(), new MisplacedUsingDirectivesCodeFixProvider()); internal static readonly CodeStyleOption2<AddImportPlacement> OutsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.None); internal static readonly CodeStyleOption2<AddImportPlacement> InsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.None); internal static readonly CodeStyleOption2<AddImportPlacement> InsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error); internal static readonly CodeStyleOption2<AddImportPlacement> OutsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error); protected const string ClassDefinition = @"public class TestClass { }"; protected const string StructDefinition = @"public struct TestStruct { }"; protected const string InterfaceDefinition = @"public interface TestInterface { }"; protected const string EnumDefinition = @"public enum TestEnum { TestValue }"; protected const string DelegateDefinition = @"public delegate void TestDelegate();"; private TestParameters GetTestParameters(CodeStyleOption2<AddImportPlacement> preferredPlacementOption) => new TestParameters(options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption } }); private protected Task TestDiagnosticMissingAsync(string initialMarkup, CodeStyleOption2<AddImportPlacement> preferredPlacementOption) => TestDiagnosticMissingAsync(initialMarkup, GetTestParameters(preferredPlacementOption)); private protected Task TestMissingAsync(string initialMarkup, CodeStyleOption2<AddImportPlacement> preferredPlacementOption) => TestMissingAsync(initialMarkup, GetTestParameters(preferredPlacementOption)); private protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, CodeStyleOption2<AddImportPlacement> preferredPlacementOption, bool placeSystemNamespaceFirst) { var options = new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption }, { GenerationOptions.PlaceSystemNamespaceFirst, placeSystemNamespaceFirst }, }; return TestInRegularAndScriptAsync( initialMarkup, expectedMarkup, options: options, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10)); } #region Test Preserve /// <summary> /// Verifies that valid using statements in a namespace does not produce any diagnostics. /// </summary> [Fact] public Task WhenPreserve_UsingsInNamespace_ValidUsingStatements() { var testCode = @"namespace TestNamespace { [|using System; using System.Threading;|] } "; return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); } [Fact] public Task WhenPreserve_UsingsInNamespace_ValidUsingStatements_FileScopedNamespace() { var testCode = @"namespace TestNamespace; [|using System; using System.Threading;|] "; return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics, nor will /// having using statements inside a namespace. /// </summary> [Fact] public Task WhenPreserve_UsingsInCompilationUnitAndNamespace_ValidUsingStatements() { var testCode = @"using System; namespace TestNamespace { [|using System.Threading;|] } "; return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are type definition present. /// </summary> /// <param name="typeDefinition">The type definition to test.</param> [Theory] [InlineData(ClassDefinition)] [InlineData(StructDefinition)] [InlineData(InterfaceDefinition)] [InlineData(EnumDefinition)] [InlineData(DelegateDefinition)] public Task WhenPreserve_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition) { var testCode = $@"[|using System;|] {typeDefinition} "; return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are attributes present. /// </summary> [Fact] public Task WhenPreserve_UsingsInCompilationUnitWithAttributes_ValidUsingStatements() { var testCode = @"[|using System.Reflection;|] [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { using System; using System.Threading; } "; return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics, even if they could be /// moved inside a namespace. /// </summary> [Fact] public Task WhenPreserve_UsingsInCompilationUnit_ValidUsingStatements() { var testCode = @"[|using System; using System.Threading;|] namespace TestNamespace { } "; return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); } #endregion #region Test OutsideNamespace /// <summary> /// Verifies that valid using statements in the compilation unit does not produce any diagnostics. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInCompilationUnit_ValidUsingStatements() { var testCode = @"[|using System; using System.Threading;|] namespace TestNamespace { } "; return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); } [Fact] public Task WhenOutsidePreferred_UsingsInCompilationUnit_ValidUsingStatements_FileScopedNamespace() { var testCode = @"[|using System; using System.Threading;|] namespace TestNamespace; "; return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are type definition present. /// </summary> /// <param name="typeDefinition">The type definition to test.</param> [Theory] [InlineData(ClassDefinition)] [InlineData(StructDefinition)] [InlineData(InterfaceDefinition)] [InlineData(EnumDefinition)] [InlineData(DelegateDefinition)] public Task WhenOutsidePreferred_UsingsInCompilationUnitWithMember_ValidUsingStatements(string typeDefinition) { var testCode = $@"[|using System;|] {typeDefinition} "; return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); } /// <summary> /// Verifies that using statements in a namespace produces the expected diagnostics. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMoved() { var testCode = @"namespace TestNamespace { [|using System; using System.Threading;|] } "; var fixedTestCode = @"{|Warning:using System;|} {|Warning:using System.Threading;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMoved_FileScopedNamespace() { var testCode = @"namespace TestNamespace; [|using System; using System.Threading;|] "; var fixedTestCode = @" {|Warning:using System;|} {|Warning:using System.Threading;|} namespace TestNamespace; "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in a namespace are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_SimplifiedUsingInNamespace_UsingsMovedAndExpanded() { var testCode = @"namespace System { [|using System; using System.Threading; using Reflection;|] } "; var fixedTestCode = @"{|Warning:using System;|} {|Warning:using System.Threading;|} {|Warning:using System.Reflection;|} namespace System { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will move the using directives when they are present in both the compilation unit and namespace. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInBoth_UsingsMoved() { var testCode = @" using Microsoft.CodeAnalysis; namespace TestNamespace { [|using System;|] } "; var fixedTestCode = @" using Microsoft.CodeAnalysis; {|Warning:using System;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in a namespace are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_SimplifiedUsingAliasInNamespace_UsingsMovedAndExpanded() { var testCode = @"namespace System.MyExtension { [|using System.Threading; using Reflection; using Assembly = Reflection.Assembly; using List = Collections.Generic.IList<int>;|] } "; var fixedTestCode = @"{|Warning:using System.Threading;|} {|Warning:using System.Reflection;|} {|Warning:using Assembly = System.Reflection.Assembly;|} {|Warning:using List = System.Collections.Generic.IList<int>;|} namespace System.MyExtension { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are attributes present. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceAndCompilationUnitWithAttributes_UsingsMoved() { var testCode = @"using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { [|using System; using System.Threading;|] } "; var fixedTestCode = @"using System.Reflection; {|Warning:using System;|} {|Warning:using System.Threading;|} [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the file header of a file is properly preserved when moving using statements out of a namespace. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceAndCompilationUnitHasFileHeader_UsingsMovedAndHeaderPreserved() { var testCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace TestNamespace { [|using System;|] } "; var fixedTestCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. {|Warning:using System;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceWithCommentsAndCompilationUnitHasFileHeader_UsingsMovedWithCommentsAndHeaderPreserved() { var testCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace TestNamespace { // Separated Comment [|using System.Collections; // Comment using System;|] } "; var fixedTestCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. // Separated Comment {|Warning:using System.Collections;|} // Comment {|Warning:using System;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMovedAndSystemPlacedFirstIgnored() { var testCode = @"namespace Foo { [|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] public class Bar { } } "; var fixedTestCode = @"{|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} namespace Foo { public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMovedAndAlphaSortIgnored() { var testCode = @"namespace Foo { [|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] public class Bar { } } "; var fixedTestCode = @"{|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} namespace Foo { public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: false); } /// <summary> /// Verifies that simplified using statements in nested namespace are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNestedNamespaces_UsingsMovedAndExpanded() { var testCode = @"using System; namespace System.Namespace { // Outer Comment [|using Threading; namespace OtherNamespace { // Inner Comment using Reflection;|] } } "; var fixedTestCode = @"using System; // Outer Comment {|Warning:using System.Threading;|} // Inner Comment {|Warning:using System.Reflection;|} namespace System.Namespace { namespace OtherNamespace { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in multiple namespaces are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInMultipleNamespaces_UsingsMovedAndExpanded() { var testCode = @"using System; namespace System.Namespace { // A Comment [|using Threading; } namespace System.OtherNamespace { // Another Comment using Reflection;|] } "; var fixedTestCode = @"using System; // A Comment {|Warning:using System.Threading;|} // Another Comment {|Warning:using System.Reflection;|} namespace System.Namespace { } namespace System.OtherNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in multiple namespaces are deduplicated during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInMultipleNamespaces_UsingsMovedAndDeduplicated() { var testCode = @"using System; namespace System.Namespace { // Orphaned Comment 1 [|using System; // A Comment using Threading; } namespace B { // Orphaned Comment 2 using System.Threading;|] } "; var fixedTestCode = @"using System; // Orphaned Comment 1 // A Comment {|Warning:using System.Threading;|} // Orphaned Comment 2 namespace System.Namespace { } namespace B { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } #endregion #region Test InsideNamespace /// <summary> /// Verifies that valid using statements in a namespace does not produce any diagnostics. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInNamespace_ValidUsingStatements() { var testCode = @"namespace TestNamespace { [|using System; using System.Threading;|] } "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } [Fact] public Task WhenInsidePreferred_UsingsInNamespace_ValidUsingStatements_FileScopedNamespace() { var testCode = @"namespace TestNamespace; [|using System; using System.Threading;|] "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are type definition present. /// </summary> /// <param name="typeDefinition">The type definition to test.</param> [Theory] [InlineData(ClassDefinition)] [InlineData(StructDefinition)] [InlineData(InterfaceDefinition)] [InlineData(EnumDefinition)] [InlineData(DelegateDefinition)] public Task WhenInsidePreferred_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition) { var testCode = $@"[|using System;|] {typeDefinition} "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are attributes present. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithAttributes_ValidUsingStatements() { var testCode = @"[|using System.Reflection;|] [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { using System; using System.Threading; } "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that the code fix will move the using directives and not place System directives first. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnit_UsingsMovedAndSystemPlacedFirstIgnored() { var testCode = @"[|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] namespace Foo { public class Bar { } } "; var fixedTestCode = @"namespace Foo { {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will move the using directives and not sort them alphabetically. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnit_UsingsAndWithAlphaSortIgnored() { var testCode = @"[|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] namespace NamespaceName { public class Bar { } } "; var fixedTestCode = @"namespace NamespaceName { {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: false); } /// <summary> /// Verifies that the code fix will move the using directives, but will not move a file header comment separated by an new line. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeader_UsingsMovedNotHeader() { var testCode = @"// This is a file header. [|using Microsoft.CodeAnalysis; using System;|] namespace TestNamespace { } "; var fixedTestCode = @"// This is a file header. namespace TestNamespace { {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using System;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will move the using directives when they are present in both the compilation unit and namespace. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInBoth_UsingsMoved() { var testCode = @"[|using Microsoft.CodeAnalysis;|] namespace TestNamespace { using System; } "; var fixedTestCode = @"namespace TestNamespace { {|Warning:using Microsoft.CodeAnalysis;|} using System; } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenInsidePreferred_UsingsInBoth_UsingsMoved_FileScopedNamespaec() { var testCode = @"[|using Microsoft.CodeAnalysis;|] namespace TestNamespace; using System; "; var fixedTestCode = @"namespace TestNamespace; {|Warning:using Microsoft.CodeAnalysis;|} using System; "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will properly move separated trivia, but will not move a file header comment. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeaderAndTrivia_UsingsAndTriviaMovedNotHeader() { var testCode = @"// File Header // Leading Comment [|using Microsoft.CodeAnalysis; using System;|] namespace TestNamespace { } "; var fixedTestCode = @"// File Header namespace TestNamespace { // Leading Comment {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using System;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that a code fix will not be offered for MisplacedUsing diagnostics when multiple namespaces are present. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithMultipleNamespaces_NoCodeFixOffered() { var testCode = @"[|using System;|] namespace TestNamespace1 { public class TestClass1 { } } namespace TestNamespace2 { } "; return TestMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that the code fix will properly move pragmas. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithPragma_PragmaMoved() { var testCode = @"#pragma warning disable 1573 // Comment [|using System; using System.Threading;|] namespace TestNamespace { } "; var fixedTestCode = @"namespace TestNamespace { #pragma warning disable 1573 // Comment {|Warning:using System;|} {|Warning:using System.Threading;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will properly move regions. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithRegion_RegionMoved() { var testCode = @"#region Comment #endregion Comment [|using System; using System.Threading;|] namespace TestNamespace { } "; var fixedTestCode = @"namespace TestNamespace { #region Comment #endregion Comment {|Warning:using System;|} {|Warning:using System.Threading;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will properly move comment trivia. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithCommentTrivia_TriviaMoved() { var testCode = @" // Some comment [|using System; using System.Threading;|] namespace TestNamespace { } "; var fixedTestCode = @"namespace TestNamespace { // Some comment {|Warning:using System;|} {|Warning:using System.Threading;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } #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.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MisplacedUsingDirectives { public class MisplacedUsingDirectivesInCompilationUnitCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MisplacedUsingDirectivesInCompilationUnitCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new MisplacedUsingDirectivesDiagnosticAnalyzer(), new MisplacedUsingDirectivesCodeFixProvider()); internal static readonly CodeStyleOption2<AddImportPlacement> OutsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.None); internal static readonly CodeStyleOption2<AddImportPlacement> InsidePreferPreservationOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.None); internal static readonly CodeStyleOption2<AddImportPlacement> InsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error); internal static readonly CodeStyleOption2<AddImportPlacement> OutsideNamespaceOption = new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error); protected const string ClassDefinition = @"public class TestClass { }"; protected const string StructDefinition = @"public struct TestStruct { }"; protected const string InterfaceDefinition = @"public interface TestInterface { }"; protected const string EnumDefinition = @"public enum TestEnum { TestValue }"; protected const string DelegateDefinition = @"public delegate void TestDelegate();"; private TestParameters GetTestParameters(CodeStyleOption2<AddImportPlacement> preferredPlacementOption) => new TestParameters(options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption } }); private protected Task TestDiagnosticMissingAsync(string initialMarkup, CodeStyleOption2<AddImportPlacement> preferredPlacementOption) => TestDiagnosticMissingAsync(initialMarkup, GetTestParameters(preferredPlacementOption)); private protected Task TestMissingAsync(string initialMarkup, CodeStyleOption2<AddImportPlacement> preferredPlacementOption) => TestMissingAsync(initialMarkup, GetTestParameters(preferredPlacementOption)); private protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, CodeStyleOption2<AddImportPlacement> preferredPlacementOption, bool placeSystemNamespaceFirst) { var options = new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption }, { GenerationOptions.PlaceSystemNamespaceFirst, placeSystemNamespaceFirst }, }; return TestInRegularAndScriptAsync( initialMarkup, expectedMarkup, options: options, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10)); } #region Test Preserve /// <summary> /// Verifies that valid using statements in a namespace does not produce any diagnostics. /// </summary> [Fact] public Task WhenPreserve_UsingsInNamespace_ValidUsingStatements() { var testCode = @"namespace TestNamespace { [|using System; using System.Threading;|] } "; return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); } [Fact] public Task WhenPreserve_UsingsInNamespace_ValidUsingStatements_FileScopedNamespace() { var testCode = @"namespace TestNamespace; [|using System; using System.Threading;|] "; return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics, nor will /// having using statements inside a namespace. /// </summary> [Fact] public Task WhenPreserve_UsingsInCompilationUnitAndNamespace_ValidUsingStatements() { var testCode = @"using System; namespace TestNamespace { [|using System.Threading;|] } "; return TestDiagnosticMissingAsync(testCode, OutsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are type definition present. /// </summary> /// <param name="typeDefinition">The type definition to test.</param> [Theory] [InlineData(ClassDefinition)] [InlineData(StructDefinition)] [InlineData(InterfaceDefinition)] [InlineData(EnumDefinition)] [InlineData(DelegateDefinition)] public Task WhenPreserve_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition) { var testCode = $@"[|using System;|] {typeDefinition} "; return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are attributes present. /// </summary> [Fact] public Task WhenPreserve_UsingsInCompilationUnitWithAttributes_ValidUsingStatements() { var testCode = @"[|using System.Reflection;|] [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { using System; using System.Threading; } "; return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics, even if they could be /// moved inside a namespace. /// </summary> [Fact] public Task WhenPreserve_UsingsInCompilationUnit_ValidUsingStatements() { var testCode = @"[|using System; using System.Threading;|] namespace TestNamespace { } "; return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption); } #endregion #region Test OutsideNamespace /// <summary> /// Verifies that valid using statements in the compilation unit does not produce any diagnostics. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInCompilationUnit_ValidUsingStatements() { var testCode = @"[|using System; using System.Threading;|] namespace TestNamespace { } "; return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); } [Fact] public Task WhenOutsidePreferred_UsingsInCompilationUnit_ValidUsingStatements_FileScopedNamespace() { var testCode = @"[|using System; using System.Threading;|] namespace TestNamespace; "; return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are type definition present. /// </summary> /// <param name="typeDefinition">The type definition to test.</param> [Theory] [InlineData(ClassDefinition)] [InlineData(StructDefinition)] [InlineData(InterfaceDefinition)] [InlineData(EnumDefinition)] [InlineData(DelegateDefinition)] public Task WhenOutsidePreferred_UsingsInCompilationUnitWithMember_ValidUsingStatements(string typeDefinition) { var testCode = $@"[|using System;|] {typeDefinition} "; return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption); } /// <summary> /// Verifies that using statements in a namespace produces the expected diagnostics. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMoved() { var testCode = @"namespace TestNamespace { [|using System; using System.Threading;|] } "; var fixedTestCode = @"{|Warning:using System;|} {|Warning:using System.Threading;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMoved_FileScopedNamespace() { var testCode = @"namespace TestNamespace; [|using System; using System.Threading;|] "; var fixedTestCode = @" {|Warning:using System;|} {|Warning:using System.Threading;|} namespace TestNamespace; "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in a namespace are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_SimplifiedUsingInNamespace_UsingsMovedAndExpanded() { var testCode = @"namespace System { [|using System; using System.Threading; using Reflection;|] } "; var fixedTestCode = @"{|Warning:using System;|} {|Warning:using System.Threading;|} {|Warning:using System.Reflection;|} namespace System { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will move the using directives when they are present in both the compilation unit and namespace. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInBoth_UsingsMoved() { var testCode = @" using Microsoft.CodeAnalysis; namespace TestNamespace { [|using System;|] } "; var fixedTestCode = @" using Microsoft.CodeAnalysis; {|Warning:using System;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in a namespace are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_SimplifiedUsingAliasInNamespace_UsingsMovedAndExpanded() { var testCode = @"namespace System.MyExtension { [|using System.Threading; using Reflection; using Assembly = Reflection.Assembly; using List = Collections.Generic.IList<int>;|] } "; var fixedTestCode = @"{|Warning:using System.Threading;|} {|Warning:using System.Reflection;|} {|Warning:using Assembly = System.Reflection.Assembly;|} {|Warning:using List = System.Collections.Generic.IList<int>;|} namespace System.MyExtension { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are attributes present. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceAndCompilationUnitWithAttributes_UsingsMoved() { var testCode = @"using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { [|using System; using System.Threading;|] } "; var fixedTestCode = @"using System.Reflection; {|Warning:using System;|} {|Warning:using System.Threading;|} [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the file header of a file is properly preserved when moving using statements out of a namespace. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceAndCompilationUnitHasFileHeader_UsingsMovedAndHeaderPreserved() { var testCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace TestNamespace { [|using System;|] } "; var fixedTestCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. {|Warning:using System;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespaceWithCommentsAndCompilationUnitHasFileHeader_UsingsMovedWithCommentsAndHeaderPreserved() { var testCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace TestNamespace { // Separated Comment [|using System.Collections; // Comment using System;|] } "; var fixedTestCode = @"// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. // Separated Comment {|Warning:using System.Collections;|} // Comment {|Warning:using System;|} namespace TestNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMovedAndSystemPlacedFirstIgnored() { var testCode = @"namespace Foo { [|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] public class Bar { } } "; var fixedTestCode = @"{|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} namespace Foo { public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenOutsidePreferred_UsingsInNamespace_UsingsMovedAndAlphaSortIgnored() { var testCode = @"namespace Foo { [|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] public class Bar { } } "; var fixedTestCode = @"{|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} namespace Foo { public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: false); } /// <summary> /// Verifies that simplified using statements in nested namespace are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInNestedNamespaces_UsingsMovedAndExpanded() { var testCode = @"using System; namespace System.Namespace { // Outer Comment [|using Threading; namespace OtherNamespace { // Inner Comment using Reflection;|] } } "; var fixedTestCode = @"using System; // Outer Comment {|Warning:using System.Threading;|} // Inner Comment {|Warning:using System.Reflection;|} namespace System.Namespace { namespace OtherNamespace { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in multiple namespaces are expanded during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInMultipleNamespaces_UsingsMovedAndExpanded() { var testCode = @"using System; namespace System.Namespace { // A Comment [|using Threading; } namespace System.OtherNamespace { // Another Comment using Reflection;|] } "; var fixedTestCode = @"using System; // A Comment {|Warning:using System.Threading;|} // Another Comment {|Warning:using System.Reflection;|} namespace System.Namespace { } namespace System.OtherNamespace { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that simplified using statements in multiple namespaces are deduplicated during the code fix operation. /// </summary> [Fact] public Task WhenOutsidePreferred_UsingsInMultipleNamespaces_UsingsMovedAndDeduplicated() { var testCode = @"using System; namespace System.Namespace { // Orphaned Comment 1 [|using System; // A Comment using Threading; } namespace B { // Orphaned Comment 2 using System.Threading;|] } "; var fixedTestCode = @"using System; // Orphaned Comment 1 // A Comment {|Warning:using System.Threading;|} // Orphaned Comment 2 namespace System.Namespace { } namespace B { } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, OutsideNamespaceOption, placeSystemNamespaceFirst: true); } #endregion #region Test InsideNamespace /// <summary> /// Verifies that valid using statements in a namespace does not produce any diagnostics. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInNamespace_ValidUsingStatements() { var testCode = @"namespace TestNamespace { [|using System; using System.Threading;|] } "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } [Fact] public Task WhenInsidePreferred_UsingsInNamespace_ValidUsingStatements_FileScopedNamespace() { var testCode = @"namespace TestNamespace; [|using System; using System.Threading;|] "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are type definition present. /// </summary> /// <param name="typeDefinition">The type definition to test.</param> [Theory] [InlineData(ClassDefinition)] [InlineData(StructDefinition)] [InlineData(InterfaceDefinition)] [InlineData(EnumDefinition)] [InlineData(DelegateDefinition)] public Task WhenInsidePreferred_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition) { var testCode = $@"[|using System;|] {typeDefinition} "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that having using statements in the compilation unit will not produce any diagnostics when there are attributes present. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithAttributes_ValidUsingStatements() { var testCode = @"[|using System.Reflection;|] [assembly: AssemblyVersion(""1.0.0.0"")] namespace TestNamespace { using System; using System.Threading; } "; return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that the code fix will move the using directives and not place System directives first. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnit_UsingsMovedAndSystemPlacedFirstIgnored() { var testCode = @"[|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] namespace Foo { public class Bar { } } "; var fixedTestCode = @"namespace Foo { {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will move the using directives and not sort them alphabetically. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnit_UsingsAndWithAlphaSortIgnored() { var testCode = @"[|using Microsoft.CodeAnalysis; using SystemAction = System.Action; using static System.Math; using System; using static System.String; using MyFunc = System.Func<int, bool>; using System.Collections.Generic; using System.Collections;|] namespace NamespaceName { public class Bar { } } "; var fixedTestCode = @"namespace NamespaceName { {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using SystemAction = System.Action;|} {|Warning:using static System.Math;|} {|Warning:using System;|} {|Warning:using static System.String;|} {|Warning:using MyFunc = System.Func<int, bool>;|} {|Warning:using System.Collections.Generic;|} {|Warning:using System.Collections;|} public class Bar { } } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: false); } /// <summary> /// Verifies that the code fix will move the using directives, but will not move a file header comment separated by an new line. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeader_UsingsMovedNotHeader() { var testCode = @"// This is a file header. [|using Microsoft.CodeAnalysis; using System;|] namespace TestNamespace { } "; var fixedTestCode = @"// This is a file header. namespace TestNamespace { {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using System;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will move the using directives when they are present in both the compilation unit and namespace. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInBoth_UsingsMoved() { var testCode = @"[|using Microsoft.CodeAnalysis;|] namespace TestNamespace { using System; } "; var fixedTestCode = @"namespace TestNamespace { {|Warning:using Microsoft.CodeAnalysis;|} using System; } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } [Fact] public Task WhenInsidePreferred_UsingsInBoth_UsingsMoved_FileScopedNamespaec() { var testCode = @"[|using Microsoft.CodeAnalysis;|] namespace TestNamespace; using System; "; var fixedTestCode = @"namespace TestNamespace; {|Warning:using Microsoft.CodeAnalysis;|} using System; "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will properly move separated trivia, but will not move a file header comment. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithFileHeaderAndTrivia_UsingsAndTriviaMovedNotHeader() { var testCode = @"// File Header // Leading Comment [|using Microsoft.CodeAnalysis; using System;|] namespace TestNamespace { } "; var fixedTestCode = @"// File Header namespace TestNamespace { // Leading Comment {|Warning:using Microsoft.CodeAnalysis;|} {|Warning:using System;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that a code fix will not be offered for MisplacedUsing diagnostics when multiple namespaces are present. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithMultipleNamespaces_NoCodeFixOffered() { var testCode = @"[|using System;|] namespace TestNamespace1 { public class TestClass1 { } } namespace TestNamespace2 { } "; return TestMissingAsync(testCode, InsideNamespaceOption); } /// <summary> /// Verifies that the code fix will properly move pragmas. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithPragma_PragmaMoved() { var testCode = @"#pragma warning disable 1573 // Comment [|using System; using System.Threading;|] namespace TestNamespace { } "; var fixedTestCode = @"namespace TestNamespace { #pragma warning disable 1573 // Comment {|Warning:using System;|} {|Warning:using System.Threading;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will properly move regions. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithRegion_RegionMoved() { var testCode = @"#region Comment #endregion Comment [|using System; using System.Threading;|] namespace TestNamespace { } "; var fixedTestCode = @"namespace TestNamespace { #region Comment #endregion Comment {|Warning:using System;|} {|Warning:using System.Threading;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } /// <summary> /// Verifies that the code fix will properly move comment trivia. /// </summary> [Fact] public Task WhenInsidePreferred_UsingsInCompilationUnitWithCommentTrivia_TriviaMoved() { var testCode = @" // Some comment [|using System; using System.Threading;|] namespace TestNamespace { } "; var fixedTestCode = @"namespace TestNamespace { // Some comment {|Warning:using System;|} {|Warning:using System.Threading;|} } "; return TestInRegularAndScriptAsync(testCode, fixedTestCode, InsideNamespaceOption, placeSystemNamespaceFirst: true); } #endregion } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.ReadOnly.Enumerable`2.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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class ReadOnly { internal class Enumerable<TUnderlying, T> : Enumerable<TUnderlying>, IEnumerable<T> where TUnderlying : IEnumerable<T> { public Enumerable(TUnderlying underlying) : base(underlying) { } public new IEnumerator<T> GetEnumerator() { return this.Underlying.GetEnumerator(); } } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class ReadOnly { internal class Enumerable<TUnderlying, T> : Enumerable<TUnderlying>, IEnumerable<T> where TUnderlying : IEnumerable<T> { public Enumerable(TUnderlying underlying) : base(underlying) { } public new IEnumerator<T> GetEnumerator() { return this.Underlying.GetEnumerator(); } } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/Diagnostics/IVisualStudioDiagnosticAnalyzerService.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 Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Diagnostics { internal interface IVisualStudioDiagnosticAnalyzerService { /// <summary> /// Gets a list of the diagnostics that are provided by this service. /// If the given <paramref name="hierarchy"/> is non-null and corresponds to an existing project in the workspace, then gets the diagnostics for the project. /// Otherwise, returns the global set of diagnostics enabled for the workspace. /// </summary> /// <returns>A mapping from analyzer name to the diagnostics produced by that analyzer</returns> /// <remarks> /// This is used by the Ruleset Editor from ManagedSourceCodeAnalysis.dll in VisualStudio. /// </remarks> IReadOnlyDictionary<string, IEnumerable<DiagnosticDescriptor>> GetAllDiagnosticDescriptors(IVsHierarchy? hierarchy); /// <summary> /// Runs all the applicable NuGet and VSIX diagnostic analyzers for the given project OR current solution in background and updates the error list. /// </summary> /// <param name="hierarchy"> /// If non-null hierarchy for a project, then analyzers are run on the project. /// Otherwise, analyzers are run on the current solution. /// </param> void RunAnalyzers(IVsHierarchy? hierarchy); /// <summary> /// Initializes the service. /// </summary> void Initialize(IServiceProvider serviceProvider); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Diagnostics { internal interface IVisualStudioDiagnosticAnalyzerService { /// <summary> /// Gets a list of the diagnostics that are provided by this service. /// If the given <paramref name="hierarchy"/> is non-null and corresponds to an existing project in the workspace, then gets the diagnostics for the project. /// Otherwise, returns the global set of diagnostics enabled for the workspace. /// </summary> /// <returns>A mapping from analyzer name to the diagnostics produced by that analyzer</returns> /// <remarks> /// This is used by the Ruleset Editor from ManagedSourceCodeAnalysis.dll in VisualStudio. /// </remarks> IReadOnlyDictionary<string, IEnumerable<DiagnosticDescriptor>> GetAllDiagnosticDescriptors(IVsHierarchy? hierarchy); /// <summary> /// Runs all the applicable NuGet and VSIX diagnostic analyzers for the given project OR current solution in background and updates the error list. /// </summary> /// <param name="hierarchy"> /// If non-null hierarchy for a project, then analyzers are run on the project. /// Otherwise, analyzers are run on the current solution. /// </param> void RunAnalyzers(IVsHierarchy? hierarchy); /// <summary> /// Initializes the service. /// </summary> void Initialize(IServiceProvider serviceProvider); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Locations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Locations : CSharpTestBase { [Fact] public void Global1() { var source1 = @" [assembly: A] [module: A] "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics(); } [Fact] public void Global2() { var source1 = @" namespace N { [assembly: A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (4,6): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [Fact] public void Global3() { var source1 = @" class X { [A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (5,1): error CS1519: Unexpected token '}', member declaration expected. Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}")); } [Fact] public void OnClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] struct S { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record struct S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record class S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnEnum() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] enum E { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnInterface() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] interface I { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnDelegate() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] delegate void D(int a); "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type, return"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type, return"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type, return"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type, return"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type, return"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type, return"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type, return"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type, return"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type, return")); } [Fact] public void OnMethod() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] void M(int a) { } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field"), // (21,9): warning CS0169: The field 'C.a' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C.a")); } [Fact] public void OnEnumField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } enum E { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] x } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field")); } [Fact] public void OnProperty() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a { get; set; } } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field, property").WithLocation(10, 6), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field, property").WithLocation(11, 6), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field, property").WithLocation(12, 6), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property").WithLocation(13, 6), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field, property").WithLocation(16, 6), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field, property").WithLocation(17, 6), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field, property").WithLocation(18, 6), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field, property").WithLocation(19, 6), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field, property").WithLocation(20, 6)); } [Fact] public void OnPropertyGetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (20,10): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnPropertySetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { get { return 0; } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, field, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, field, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, field, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, field, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, field, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, field, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, field, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, field, event"), // (21,25): warning CS0067: The event 'C.e' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("C.e")); } [Fact, WorkItem(543977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543977")] public void OnInterfaceFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } interface I { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, event")); } [Fact] public void OnCustomEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event Action E { add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "event"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "event")); } [Fact] public void OnEventAdder() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnEventRemover() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { add { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnTypeParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C < [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] T > { } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "typevar"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "typevar"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "typevar"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "typevar"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "typevar"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "typevar"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "typevar"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "typevar"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "typevar"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "typevar")); } [Fact] public void OnMethodParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { void f( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnDelegateParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } delegate void D( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ); "; CreateCompilation(source).VerifyDiagnostics( // (9,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (10,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (11,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (12,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (13,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (14,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (15,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (16,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (18,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (19,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnIndexerParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int this[ [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void UnrecognizedLocations() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [class: A] [struct: A] [interface: A] [delegate: A] [enum: A] [add: A] [remove: A] [get: A] [set: A] class C { }"; CreateCompilation(source).VerifyDiagnostics( // (7,2): warning CS0658: 'class' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "class").WithArguments("class", "type"), // (8,2): warning CS0658: 'struct' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "struct").WithArguments("struct", "type"), // (9,2): warning CS0658: 'interface' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "interface").WithArguments("interface", "type"), // (10,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type"), // (11,2): warning CS0658: 'enum' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "enum").WithArguments("enum", "type"), // (12,2): warning CS0658: 'add' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "add").WithArguments("add", "type"), // (13,2): warning CS0658: 'remove' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "remove").WithArguments("remove", "type"), // (14,2): warning CS0658: 'get' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "get").WithArguments("get", "type"), // (15,2): warning CS0658: 'set' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "set").WithArguments("set", "type")); } [Fact, WorkItem(545555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545555")] public void AttributesWithInvalidLocationNotEmitted() { var source = @" using System; public class goo { public static void Main() { object[] o = typeof(goo).GetMethod(""Boo"").GetCustomAttributes(typeof(A), false); Console.WriteLine(""Attribute Count={0}"", o.Length); } [goo: A] [method: A] public int Boo(int i) { return 1; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CompileAndVerify(source, expectedOutput: "Attribute Count=1").VerifyDiagnostics( // (12,6): warning CS0658: 'goo' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "goo").WithArguments("goo", "method, return")); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTarget() { CreateCompilation(@"class A { [@return:X] void B() { } }").VerifyDiagnostics( // (1,20): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(1, 20), // (1,20): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(1, 20)); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTargetAndAttribute() { var source = @" using System; class X: Attribute {} class XAttribute: Attribute {} class A { [return:X] void M() { } } // Ambiguous class B { [@return:X] void M() { } } // Ambiguous class C { [return:@X] void M() { } } // Fine, binds to X class D { [@return:@X] void M() { } } // Fine, binds to X "; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class A { [return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute"), // (8,20): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class B { [@return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Locations : CSharpTestBase { [Fact] public void Global1() { var source1 = @" [assembly: A] [module: A] "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics(); } [Fact] public void Global2() { var source1 = @" namespace N { [assembly: A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (4,6): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly")); } [Fact] public void Global3() { var source1 = @" class X { [A] } "; var source2 = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CreateCompilation(new[] { source1, source2 }).VerifyDiagnostics( // (5,1): error CS1519: Unexpected token '}', member declaration expected. Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}")); } [Fact] public void OnClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] struct S { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordStruct() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record struct S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnRecordClass() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] record class S { } "; CreateCompilation(source, parseOptions: TestOptions.Regular10).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnEnum() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] enum E { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnInterface() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] interface I { } "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type"), // (15,2): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "type"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type")); } [Fact] public void OnDelegate() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] delegate void D(int a); "; CreateCompilation(source).VerifyDiagnostics( // (8,2): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type, return"), // (9,2): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "type, return"), // (11,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type, return"), // (12,2): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "type, return"), // (13,2): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "type, return"), // (14,2): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "type, return"), // (16,2): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "type, return"), // (17,2): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "type, return"), // (18,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type, return")); } [Fact] public void OnMethod() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] void M(int a) { } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field"), // (21,9): warning CS0169: The field 'C.a' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C.a")); } [Fact] public void OnEnumField() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } enum E { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] x } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "field"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field")); } [Fact] public void OnProperty() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int a { get; set; } } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "field, property").WithLocation(10, 6), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "field, property").WithLocation(11, 6), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "field, property").WithLocation(12, 6), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property").WithLocation(13, 6), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "field, property").WithLocation(16, 6), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "field, property").WithLocation(17, 6), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "field, property").WithLocation(18, 6), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "field, property").WithLocation(19, 6), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'field, property'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "field, property").WithLocation(20, 6)); } [Fact] public void OnPropertyGetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, return"), // (20,10): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, return")); } [Fact] public void OnPropertySetter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int Goo { get { return 0; } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, field, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, field, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, field, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, field, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, field, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, field, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, field, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, field, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, field, event"), // (21,25): warning CS0067: The event 'C.e' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("C.e")); } [Fact, WorkItem(543977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543977")] public void OnInterfaceFieldEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } interface I { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event System.Action e; } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "method, event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "method, event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, event")); } [Fact] public void OnCustomEvent() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] event Action E { add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "event"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "event"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "event"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "event"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "event"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "event"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "event"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "event"), // (19,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "event"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'event'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "event")); } [Fact] public void OnEventAdder() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] add { } remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (13,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (14,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (16,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (17,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (18,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (21,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (22,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnEventRemover() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { event Action Goo { add { } [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] remove { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "method, param, return"), // (15,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "method, param, return"), // (16,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "method, param, return"), // (18,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, param, return"), // (19,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "method, param, return"), // (20,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "method, param, return"), // (23,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "method, param, return"), // (24,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, param, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "method, param, return")); } [Fact] public void OnTypeParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C < [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] T > { } "; CreateCompilation(source).VerifyDiagnostics( // (10,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "typevar"), // (11,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "typevar"), // (12,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "typevar"), // (13,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "typevar"), // (14,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "typevar"), // (15,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "typevar"), // (16,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "typevar"), // (17,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "typevar"), // (18,6): warning CS0657: 'param' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "param").WithArguments("param", "typevar"), // (20,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'typevar'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "typevar")); } [Fact] public void OnMethodParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { void f( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnDelegateParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } delegate void D( [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x ); "; CreateCompilation(source).VerifyDiagnostics( // (9,6): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (10,6): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (11,6): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (12,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (13,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (14,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (15,6): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (16,6): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (18,6): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (19,6): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void OnIndexerParameter() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } class C { int this[ [A] [assembly: A] [module: A] [type: A] [method: A] [field: A] [property: A] [event: A] [return: A] [param: A] [typevar: A] [delegate: A] int x] { get { return 0; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (11,10): warning CS0657: 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "param"), // (12,10): warning CS0657: 'module' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "module").WithArguments("module", "param"), // (13,10): warning CS0657: 'type' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "type").WithArguments("type", "param"), // (14,10): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "param"), // (15,10): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param"), // (16,10): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param"), // (17,10): warning CS0657: 'event' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "event").WithArguments("event", "param"), // (18,10): warning CS0657: 'return' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "return").WithArguments("return", "param"), // (20,10): warning CS0657: 'typevar' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "typevar").WithArguments("typevar", "param"), // (21,10): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "param")); } [Fact] public void UnrecognizedLocations() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } [class: A] [struct: A] [interface: A] [delegate: A] [enum: A] [add: A] [remove: A] [get: A] [set: A] class C { }"; CreateCompilation(source).VerifyDiagnostics( // (7,2): warning CS0658: 'class' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "class").WithArguments("class", "type"), // (8,2): warning CS0658: 'struct' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "struct").WithArguments("struct", "type"), // (9,2): warning CS0658: 'interface' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "interface").WithArguments("interface", "type"), // (10,2): warning CS0658: 'delegate' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "delegate").WithArguments("delegate", "type"), // (11,2): warning CS0658: 'enum' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "enum").WithArguments("enum", "type"), // (12,2): warning CS0658: 'add' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "add").WithArguments("add", "type"), // (13,2): warning CS0658: 'remove' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "remove").WithArguments("remove", "type"), // (14,2): warning CS0658: 'get' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "get").WithArguments("get", "type"), // (15,2): warning CS0658: 'set' is not a recognized attribute location. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "set").WithArguments("set", "type")); } [Fact, WorkItem(545555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545555")] public void AttributesWithInvalidLocationNotEmitted() { var source = @" using System; public class goo { public static void Main() { object[] o = typeof(goo).GetMethod(""Boo"").GetCustomAttributes(typeof(A), false); Console.WriteLine(""Attribute Count={0}"", o.Length); } [goo: A] [method: A] public int Boo(int i) { return 1; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class A : Attribute { } "; CompileAndVerify(source, expectedOutput: "Attribute Count=1").VerifyDiagnostics( // (12,6): warning CS0658: 'goo' is not a recognized attribute location. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_InvalidAttributeLocation, "goo").WithArguments("goo", "method, return")); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTarget() { CreateCompilation(@"class A { [@return:X] void B() { } }").VerifyDiagnostics( // (1,20): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(1, 20), // (1,20): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // class A { [@return:X] void B() { } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(1, 20)); } [WorkItem(537613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537613"), WorkItem(537738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537738")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_VerbatimIdentifierAttributeTargetAndAttribute() { var source = @" using System; class X: Attribute {} class XAttribute: Attribute {} class A { [return:X] void M() { } } // Ambiguous class B { [@return:X] void M() { } } // Ambiguous class C { [return:@X] void M() { } } // Fine, binds to X class D { [@return:@X] void M() { } } // Fine, binds to X "; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class A { [return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute"), // (8,20): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // class B { [@return:X] void M() { } } // Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute")); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/CodeAnalysisTest/Collections/IdentifierCollectionTests.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.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class IdentifierCollectionTests { [Fact] public void TestSupportedCollectionInterface() { TestCases(new string[] { }); TestCases("a"); TestCases("a", "b", "c"); TestCases("c", "b", "a"); TestCases("alpha", "Alpha", "alphA", "AlphA"); TestCases("alpha", "beta", "gamma", "Alpha", "betA", "gaMMa"); } private void TestCases(params string[] strings) { TestCaseSensitive(strings); TestCaseInsensitive(strings); } private void TestCaseSensitive(params string[] strings) { var idcol = new IdentifierCollection(strings).AsCaseSensitiveCollection(); Assert.Equal(strings.Length, idcol.Count); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), idcol.OrderBy(x => x))); Assert.Equal(idcol.GetEnumerator().GetType(), ((System.Collections.IEnumerable)idcol).GetEnumerator().GetType()); AssertContains(idcol, strings); AssertNotContains(idcol, strings.Select(s => s.ToUpper())); AssertNotContains(idcol, "x"); var copy = new string[strings.Length]; idcol.CopyTo(copy, 0); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), copy.OrderBy(x => x))); } private void TestCaseInsensitive(params string[] strings) { var idcol = new IdentifierCollection(strings).AsCaseInsensitiveCollection(); Assert.Equal(strings.Length, idcol.Count); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), idcol.OrderBy(x => x))); Assert.Equal(idcol.GetEnumerator().GetType(), ((System.Collections.IEnumerable)idcol).GetEnumerator().GetType()); AssertContains(idcol, strings); AssertContains(idcol, strings.Select(s => s.ToUpper())); AssertNotContains(idcol, "x"); var copy = new string[strings.Length]; idcol.CopyTo(copy, 0); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), copy.OrderBy(x => x))); } [Fact] public void TestUnsupportedCollectionInterface() { var strs = new string[] { "a", "b", "c" }; TestReadOnly(new IdentifierCollection(strs).AsCaseSensitiveCollection()); TestReadOnly(new IdentifierCollection(strs).AsCaseInsensitiveCollection()); } private void TestReadOnly(ICollection<string> collection) { Assert.True(collection.IsReadOnly); Assert.Throws<NotSupportedException>(() => collection.Add("x")); Assert.Throws<NotSupportedException>(() => collection.Remove("x")); Assert.Throws<NotSupportedException>(() => collection.Clear()); } private void AssertContains(ICollection<string> collection, params string[] strings) { AssertContains(collection, (IEnumerable<string>)strings); } private void AssertContains(ICollection<string> collection, IEnumerable<string> strings) { foreach (var str in strings) { Assert.True(collection.Contains(str)); } } private void AssertNotContains(ICollection<string> collection, params string[] strings) { AssertNotContains(collection, (IEnumerable<string>)strings); } private void AssertNotContains(ICollection<string> collection, IEnumerable<string> strings) { foreach (var str in strings) { Assert.False(collection.Contains(str)); } } } }
// Licensed to the .NET Foundation under one or more 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.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class IdentifierCollectionTests { [Fact] public void TestSupportedCollectionInterface() { TestCases(new string[] { }); TestCases("a"); TestCases("a", "b", "c"); TestCases("c", "b", "a"); TestCases("alpha", "Alpha", "alphA", "AlphA"); TestCases("alpha", "beta", "gamma", "Alpha", "betA", "gaMMa"); } private void TestCases(params string[] strings) { TestCaseSensitive(strings); TestCaseInsensitive(strings); } private void TestCaseSensitive(params string[] strings) { var idcol = new IdentifierCollection(strings).AsCaseSensitiveCollection(); Assert.Equal(strings.Length, idcol.Count); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), idcol.OrderBy(x => x))); Assert.Equal(idcol.GetEnumerator().GetType(), ((System.Collections.IEnumerable)idcol).GetEnumerator().GetType()); AssertContains(idcol, strings); AssertNotContains(idcol, strings.Select(s => s.ToUpper())); AssertNotContains(idcol, "x"); var copy = new string[strings.Length]; idcol.CopyTo(copy, 0); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), copy.OrderBy(x => x))); } private void TestCaseInsensitive(params string[] strings) { var idcol = new IdentifierCollection(strings).AsCaseInsensitiveCollection(); Assert.Equal(strings.Length, idcol.Count); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), idcol.OrderBy(x => x))); Assert.Equal(idcol.GetEnumerator().GetType(), ((System.Collections.IEnumerable)idcol).GetEnumerator().GetType()); AssertContains(idcol, strings); AssertContains(idcol, strings.Select(s => s.ToUpper())); AssertNotContains(idcol, "x"); var copy = new string[strings.Length]; idcol.CopyTo(copy, 0); Assert.True(Enumerable.SequenceEqual(strings.OrderBy(x => x), copy.OrderBy(x => x))); } [Fact] public void TestUnsupportedCollectionInterface() { var strs = new string[] { "a", "b", "c" }; TestReadOnly(new IdentifierCollection(strs).AsCaseSensitiveCollection()); TestReadOnly(new IdentifierCollection(strs).AsCaseInsensitiveCollection()); } private void TestReadOnly(ICollection<string> collection) { Assert.True(collection.IsReadOnly); Assert.Throws<NotSupportedException>(() => collection.Add("x")); Assert.Throws<NotSupportedException>(() => collection.Remove("x")); Assert.Throws<NotSupportedException>(() => collection.Clear()); } private void AssertContains(ICollection<string> collection, params string[] strings) { AssertContains(collection, (IEnumerable<string>)strings); } private void AssertContains(ICollection<string> collection, IEnumerable<string> strings) { foreach (var str in strings) { Assert.True(collection.Contains(str)); } } private void AssertNotContains(ICollection<string> collection, params string[] strings) { AssertNotContains(collection, (IEnumerable<string>)strings); } private void AssertNotContains(ICollection<string> collection, IEnumerable<string> strings) { foreach (var str in strings) { Assert.False(collection.Contains(str)); } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Symbols/Source/QuickAttributeChecker.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.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The QuickAttributeChecker applies a simple fast heuristic for determining probable /// attributes of certain kinds without binding attribute types, just by looking at the final syntax of an /// attribute usage. /// </summary> /// <remarks> /// It works by maintaining a dictionary of all possible simple names that might map to the given /// attribute. /// </remarks> internal sealed class QuickAttributeChecker { private readonly Dictionary<string, QuickAttributes> _nameToAttributeMap; private static QuickAttributeChecker _lazyPredefinedQuickAttributeChecker; #if DEBUG private bool _sealed; #endif internal static QuickAttributeChecker Predefined { get { if (_lazyPredefinedQuickAttributeChecker is null) { Interlocked.CompareExchange(ref _lazyPredefinedQuickAttributeChecker, CreatePredefinedQuickAttributeChecker(), null); } return _lazyPredefinedQuickAttributeChecker; } } private static QuickAttributeChecker CreatePredefinedQuickAttributeChecker() { var result = new QuickAttributeChecker(); result.AddName(AttributeDescription.TypeIdentifierAttribute.Name, QuickAttributes.TypeIdentifier); result.AddName(AttributeDescription.TypeForwardedToAttribute.Name, QuickAttributes.TypeForwardedTo); result.AddName(AttributeDescription.AssemblyKeyNameAttribute.Name, QuickAttributes.AssemblyKeyName); result.AddName(AttributeDescription.AssemblyKeyFileAttribute.Name, QuickAttributes.AssemblyKeyFile); result.AddName(AttributeDescription.AssemblySignatureKeyAttribute.Name, QuickAttributes.AssemblySignatureKey); #if DEBUG result._sealed = true; #endif return result; } private QuickAttributeChecker() { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(StringComparer.Ordinal); // NOTE: caller must seal } private QuickAttributeChecker(QuickAttributeChecker previous) { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(previous._nameToAttributeMap, StringComparer.Ordinal); // NOTE: caller must seal } private void AddName(string name, QuickAttributes newAttributes) { #if DEBUG Debug.Assert(!_sealed); #endif var currentValue = QuickAttributes.None; _nameToAttributeMap.TryGetValue(name, out currentValue); QuickAttributes newValue = newAttributes | currentValue; _nameToAttributeMap[name] = newValue; } internal QuickAttributeChecker AddAliasesIfAny(SyntaxList<UsingDirectiveSyntax> usingsSyntax, bool onlyGlobalAliases = false) { if (usingsSyntax.Count == 0) { return this; } QuickAttributeChecker newChecker = null; foreach (var usingDirective in usingsSyntax) { if (usingDirective.Alias != null && (!onlyGlobalAliases || usingDirective.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) { string name = usingDirective.Alias.Name.Identifier.ValueText; string target = usingDirective.Name.GetUnqualifiedName().Identifier.ValueText; if (_nameToAttributeMap.TryGetValue(target, out var foundAttributes)) { // copy the QuickAttributes from alias target to alias name (newChecker ?? (newChecker = new QuickAttributeChecker(this))).AddName(name, foundAttributes); } } } if (newChecker != null) { #if DEBUG newChecker._sealed = true; #endif return newChecker; } return this; } public bool IsPossibleMatch(AttributeSyntax attr, QuickAttributes pattern) { #if DEBUG Debug.Assert(_sealed); #endif string name = attr.Name.GetUnqualifiedName().Identifier.ValueText; QuickAttributes foundAttributes; // We allow "Name" to bind to "NameAttribute" if (_nameToAttributeMap.TryGetValue(name, out foundAttributes) || _nameToAttributeMap.TryGetValue(name + "Attribute", out foundAttributes)) { return (foundAttributes & pattern) != 0; } return false; } } [Flags] internal enum QuickAttributes : byte { None = 0, TypeIdentifier = 1 << 0, TypeForwardedTo = 1 << 1, AssemblyKeyName = 1 << 2, AssemblyKeyFile = 1 << 3, AssemblySignatureKey = 1 << 4, Last = AssemblySignatureKey, } internal static class QuickAttributeHelpers { /// <summary> /// Returns the <see cref="QuickAttributes"/> that corresponds to the particular type /// <paramref name="name"/> passed in. If <paramref name="inAttribute"/> is <see langword="true"/> /// then the name will be checked both as-is as well as with the 'Attribute' suffix. /// </summary> public static QuickAttributes GetQuickAttributes(string name, bool inAttribute) { // Update this code if we add new quick attributes. Debug.Assert(QuickAttributes.Last == QuickAttributes.AssemblySignatureKey); var result = QuickAttributes.None; if (matches(AttributeDescription.TypeIdentifierAttribute)) { result |= QuickAttributes.TypeIdentifier; } else if (matches(AttributeDescription.TypeForwardedToAttribute)) { result |= QuickAttributes.TypeForwardedTo; } else if (matches(AttributeDescription.AssemblyKeyNameAttribute)) { result |= QuickAttributes.AssemblyKeyName; } else if (matches(AttributeDescription.AssemblyKeyFileAttribute)) { result |= QuickAttributes.AssemblyKeyFile; } else if (matches(AttributeDescription.AssemblySignatureKeyAttribute)) { result |= QuickAttributes.AssemblySignatureKey; } return result; bool matches(AttributeDescription attributeDescription) { Debug.Assert(attributeDescription.Name.EndsWith(nameof(System.Attribute))); if (name == attributeDescription.Name) { return true; } // In an attribute context the name might be referenced as the full name (like 'TypeForwardedToAttribute') // or the short name (like 'TypeForwardedTo'). if (inAttribute && (name.Length + nameof(System.Attribute).Length) == attributeDescription.Name.Length && attributeDescription.Name.StartsWith(name)) { return true; } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The QuickAttributeChecker applies a simple fast heuristic for determining probable /// attributes of certain kinds without binding attribute types, just by looking at the final syntax of an /// attribute usage. /// </summary> /// <remarks> /// It works by maintaining a dictionary of all possible simple names that might map to the given /// attribute. /// </remarks> internal sealed class QuickAttributeChecker { private readonly Dictionary<string, QuickAttributes> _nameToAttributeMap; private static QuickAttributeChecker _lazyPredefinedQuickAttributeChecker; #if DEBUG private bool _sealed; #endif internal static QuickAttributeChecker Predefined { get { if (_lazyPredefinedQuickAttributeChecker is null) { Interlocked.CompareExchange(ref _lazyPredefinedQuickAttributeChecker, CreatePredefinedQuickAttributeChecker(), null); } return _lazyPredefinedQuickAttributeChecker; } } private static QuickAttributeChecker CreatePredefinedQuickAttributeChecker() { var result = new QuickAttributeChecker(); result.AddName(AttributeDescription.TypeIdentifierAttribute.Name, QuickAttributes.TypeIdentifier); result.AddName(AttributeDescription.TypeForwardedToAttribute.Name, QuickAttributes.TypeForwardedTo); result.AddName(AttributeDescription.AssemblyKeyNameAttribute.Name, QuickAttributes.AssemblyKeyName); result.AddName(AttributeDescription.AssemblyKeyFileAttribute.Name, QuickAttributes.AssemblyKeyFile); result.AddName(AttributeDescription.AssemblySignatureKeyAttribute.Name, QuickAttributes.AssemblySignatureKey); #if DEBUG result._sealed = true; #endif return result; } private QuickAttributeChecker() { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(StringComparer.Ordinal); // NOTE: caller must seal } private QuickAttributeChecker(QuickAttributeChecker previous) { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(previous._nameToAttributeMap, StringComparer.Ordinal); // NOTE: caller must seal } private void AddName(string name, QuickAttributes newAttributes) { #if DEBUG Debug.Assert(!_sealed); #endif var currentValue = QuickAttributes.None; _nameToAttributeMap.TryGetValue(name, out currentValue); QuickAttributes newValue = newAttributes | currentValue; _nameToAttributeMap[name] = newValue; } internal QuickAttributeChecker AddAliasesIfAny(SyntaxList<UsingDirectiveSyntax> usingsSyntax, bool onlyGlobalAliases = false) { if (usingsSyntax.Count == 0) { return this; } QuickAttributeChecker newChecker = null; foreach (var usingDirective in usingsSyntax) { if (usingDirective.Alias != null && (!onlyGlobalAliases || usingDirective.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) { string name = usingDirective.Alias.Name.Identifier.ValueText; string target = usingDirective.Name.GetUnqualifiedName().Identifier.ValueText; if (_nameToAttributeMap.TryGetValue(target, out var foundAttributes)) { // copy the QuickAttributes from alias target to alias name (newChecker ?? (newChecker = new QuickAttributeChecker(this))).AddName(name, foundAttributes); } } } if (newChecker != null) { #if DEBUG newChecker._sealed = true; #endif return newChecker; } return this; } public bool IsPossibleMatch(AttributeSyntax attr, QuickAttributes pattern) { #if DEBUG Debug.Assert(_sealed); #endif string name = attr.Name.GetUnqualifiedName().Identifier.ValueText; QuickAttributes foundAttributes; // We allow "Name" to bind to "NameAttribute" if (_nameToAttributeMap.TryGetValue(name, out foundAttributes) || _nameToAttributeMap.TryGetValue(name + "Attribute", out foundAttributes)) { return (foundAttributes & pattern) != 0; } return false; } } [Flags] internal enum QuickAttributes : byte { None = 0, TypeIdentifier = 1 << 0, TypeForwardedTo = 1 << 1, AssemblyKeyName = 1 << 2, AssemblyKeyFile = 1 << 3, AssemblySignatureKey = 1 << 4, Last = AssemblySignatureKey, } internal static class QuickAttributeHelpers { /// <summary> /// Returns the <see cref="QuickAttributes"/> that corresponds to the particular type /// <paramref name="name"/> passed in. If <paramref name="inAttribute"/> is <see langword="true"/> /// then the name will be checked both as-is as well as with the 'Attribute' suffix. /// </summary> public static QuickAttributes GetQuickAttributes(string name, bool inAttribute) { // Update this code if we add new quick attributes. Debug.Assert(QuickAttributes.Last == QuickAttributes.AssemblySignatureKey); var result = QuickAttributes.None; if (matches(AttributeDescription.TypeIdentifierAttribute)) { result |= QuickAttributes.TypeIdentifier; } else if (matches(AttributeDescription.TypeForwardedToAttribute)) { result |= QuickAttributes.TypeForwardedTo; } else if (matches(AttributeDescription.AssemblyKeyNameAttribute)) { result |= QuickAttributes.AssemblyKeyName; } else if (matches(AttributeDescription.AssemblyKeyFileAttribute)) { result |= QuickAttributes.AssemblyKeyFile; } else if (matches(AttributeDescription.AssemblySignatureKeyAttribute)) { result |= QuickAttributes.AssemblySignatureKey; } return result; bool matches(AttributeDescription attributeDescription) { Debug.Assert(attributeDescription.Name.EndsWith(nameof(System.Attribute))); if (name == attributeDescription.Name) { return true; } // In an attribute context the name might be referenced as the full name (like 'TypeForwardedToAttribute') // or the short name (like 'TypeForwardedTo'). if (inAttribute && (name.Length + nameof(System.Attribute).Length) == attributeDescription.Name.Length && attributeDescription.Name.StartsWith(name)) { return true; } return false; } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrDebuggerVisualizerAttribute.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using Microsoft.VisualStudio.Debugger.Clr; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrDebuggerVisualizerAttribute : DkmClrEvalAttribute { /// <summary> /// Constructor for mock DkmClrDebuggerVisualizerAttribute. /// </summary> /// <param name="targetMember">[Optional] Should be null. Not supported for the DebuggerVisualizer attribute</param> /// <param name="uiSideVisualizerTypeName">[Required] The full name of the UI-side visualizer type</param> /// <param name="uiSideVisualizerAssemblyName">[Required] The full name of the UI-side visualizer assembly</param> /// <param name="uiSideVisualizerAssemblyLocation">[Required] The location of the UI-side visualizer assembly</param> /// <param name="debuggeeSideVisualizerTypeName">[Required] The full name of the debuggee-side visualizer type</param> /// <param name="debuggeeSideVisualizerAssemblyName">[Required] The full name of the debuggee-side visualizer assembly</param> /// <param name="visualizerDescription">[Required] The visualizer description</param> internal DkmClrDebuggerVisualizerAttribute(string targetMember, string uiSideVisualizerTypeName, string uiSideVisualizerAssemblyName, DkmClrCustomVisualizerAssemblyLocation uiSideVisualizerAssemblyLocation, string debuggeeSideVisualizerTypeName, string debuggeeSideVisualizerAssemblyName, string visualizerDescription) : base(null) { UISideVisualizerTypeName = uiSideVisualizerTypeName; UISideVisualizerAssemblyName = uiSideVisualizerAssemblyName; UISideVisualizerAssemblyLocation = uiSideVisualizerAssemblyLocation; DebuggeeSideVisualizerTypeName = debuggeeSideVisualizerTypeName; DebuggeeSideVisualizerAssemblyName = debuggeeSideVisualizerAssemblyName; VisualizerDescription = visualizerDescription; } public readonly string UISideVisualizerTypeName; public readonly string UISideVisualizerAssemblyName; public readonly DkmClrCustomVisualizerAssemblyLocation UISideVisualizerAssemblyLocation; public readonly string DebuggeeSideVisualizerTypeName; public readonly string DebuggeeSideVisualizerAssemblyName; public readonly string VisualizerDescription; } } namespace Microsoft.VisualStudio.Debugger.Evaluation { // // Summary: // Enum that describes the location of the visualizer assembly. This API was introduced // in Visual Studio 14 RTM (DkmApiVersion.VS14RTM). public enum DkmClrCustomVisualizerAssemblyLocation { // // Summary: // Location unknown. Unknown, // // Summary: // The ...\Documents\...\Visual Studio X\Visualizers directory. UserDirectory, // // Summary: // The ...\Common7\Packages\Debugger\Visualizers directory. SharedDirectory, // // Summary: // Present on an assembly loaded by the debuggee. Debuggee } }
// Licensed to the .NET Foundation under one or more 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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using Microsoft.VisualStudio.Debugger.Clr; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrDebuggerVisualizerAttribute : DkmClrEvalAttribute { /// <summary> /// Constructor for mock DkmClrDebuggerVisualizerAttribute. /// </summary> /// <param name="targetMember">[Optional] Should be null. Not supported for the DebuggerVisualizer attribute</param> /// <param name="uiSideVisualizerTypeName">[Required] The full name of the UI-side visualizer type</param> /// <param name="uiSideVisualizerAssemblyName">[Required] The full name of the UI-side visualizer assembly</param> /// <param name="uiSideVisualizerAssemblyLocation">[Required] The location of the UI-side visualizer assembly</param> /// <param name="debuggeeSideVisualizerTypeName">[Required] The full name of the debuggee-side visualizer type</param> /// <param name="debuggeeSideVisualizerAssemblyName">[Required] The full name of the debuggee-side visualizer assembly</param> /// <param name="visualizerDescription">[Required] The visualizer description</param> internal DkmClrDebuggerVisualizerAttribute(string targetMember, string uiSideVisualizerTypeName, string uiSideVisualizerAssemblyName, DkmClrCustomVisualizerAssemblyLocation uiSideVisualizerAssemblyLocation, string debuggeeSideVisualizerTypeName, string debuggeeSideVisualizerAssemblyName, string visualizerDescription) : base(null) { UISideVisualizerTypeName = uiSideVisualizerTypeName; UISideVisualizerAssemblyName = uiSideVisualizerAssemblyName; UISideVisualizerAssemblyLocation = uiSideVisualizerAssemblyLocation; DebuggeeSideVisualizerTypeName = debuggeeSideVisualizerTypeName; DebuggeeSideVisualizerAssemblyName = debuggeeSideVisualizerAssemblyName; VisualizerDescription = visualizerDescription; } public readonly string UISideVisualizerTypeName; public readonly string UISideVisualizerAssemblyName; public readonly DkmClrCustomVisualizerAssemblyLocation UISideVisualizerAssemblyLocation; public readonly string DebuggeeSideVisualizerTypeName; public readonly string DebuggeeSideVisualizerAssemblyName; public readonly string VisualizerDescription; } } namespace Microsoft.VisualStudio.Debugger.Evaluation { // // Summary: // Enum that describes the location of the visualizer assembly. This API was introduced // in Visual Studio 14 RTM (DkmApiVersion.VS14RTM). public enum DkmClrCustomVisualizerAssemblyLocation { // // Summary: // Location unknown. Unknown, // // Summary: // The ...\Documents\...\Visual Studio X\Visualizers directory. UserDirectory, // // Summary: // The ...\Common7\Packages\Debugger\Visualizers directory. SharedDirectory, // // Summary: // Present on an assembly loaded by the debuggee. Debuggee } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Scripting/Core/ScriptState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// The result of running a script. /// </summary> public abstract class ScriptState { /// <summary> /// The script that ran to produce this result. /// </summary> public Script Script { get; } /// <summary> /// Caught exception originating from the script top-level code. /// </summary> /// <remarks> /// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so. /// By default they are propagated to the caller of the API. /// </remarks> public Exception Exception { get; } internal ScriptExecutionState ExecutionState { get; } private ImmutableArray<ScriptVariable> _lazyVariables; private IReadOnlyDictionary<string, int> _lazyVariableMap; internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt) { Debug.Assert(executionState != null); Debug.Assert(script != null); ExecutionState = executionState; Script = script; Exception = exceptionOpt; } /// <summary> /// The final value produced by running the script. /// </summary> public object ReturnValue => GetReturnValue(); internal abstract object GetReturnValue(); /// <summary> /// Returns variables defined by the scripts in the declaration order. /// </summary> public ImmutableArray<ScriptVariable> Variables { get { if (_lazyVariables == null) { ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables()); } return _lazyVariables; } } /// <summary> /// Returns a script variable of the specified name. /// </summary> /// <remarks> /// If multiple script variables are defined in the script (in distinct submissions) returns the last one. /// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts. /// </remarks> /// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> public ScriptVariable GetVariable(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } int index; return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null; } private ImmutableArray<ScriptVariable> CreateVariables() { var result = ArrayBuilder<ScriptVariable>.GetInstance(); var executionState = ExecutionState; // Don't include the globals object (slot #0) for (int i = 1; i < executionState.SubmissionStateCount; i++) { var state = executionState.GetSubmissionState(i); Debug.Assert(state != null); foreach (var field in state.GetType().GetTypeInfo().DeclaredFields) { // TODO: synthesized fields of submissions shouldn't be public if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_')) { result.Add(new ScriptVariable(state, field)); } } } return result.ToImmutableAndFree(); } private IReadOnlyDictionary<string, int> GetVariableMap() { if (_lazyVariableMap == null) { var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer); for (int i = 0; i < Variables.Length; i++) { map[Variables[i].Name] = i; } _lazyVariableMap = map; } return _lazyVariableMap; } /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<object>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<TResult>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken); // How do we resolve overloads? We should use the language semantics. // https://github.com/dotnet/roslyn/issues/3720 #if TODO /// <summary> /// Invoke a method declared by the script. /// </summary> public object Invoke(string name, params object[] args) { var func = this.FindMethod(name, args != null ? args.Length : 0); if (func != null) { return func(args); } return null; } private Func<object[], object> FindMethod(string name, int argCount) { for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMethod(type, name, argCount); if (method != null) { return (args) => method.Invoke(sub, args); } } } return null; } private MethodInfo FindMethod(Type type, string name, int argCount) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } /// <summary> /// Create a delegate to a method declared by the script. /// </summary> public TDelegate CreateDelegate<TDelegate>(string name) { var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMatchingMethod(type, name, delegateInvokeMethod); if (method != null) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub); } } } return default(TDelegate); } private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod) { var dprms = delegateInvokeMethod.GetParameters(); foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (mi.Name == name) { var prms = mi.GetParameters(); if (prms.Length == dprms.Length) { // TODO: better matching.. return mi; } } } return null; } #endif } public sealed class ScriptState<T> : ScriptState { public new T ReturnValue { get; } internal override object GetReturnValue() => ReturnValue; internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt) : base(executionState, script, exceptionOpt) { ReturnValue = value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// The result of running a script. /// </summary> public abstract class ScriptState { /// <summary> /// The script that ran to produce this result. /// </summary> public Script Script { get; } /// <summary> /// Caught exception originating from the script top-level code. /// </summary> /// <remarks> /// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so. /// By default they are propagated to the caller of the API. /// </remarks> public Exception Exception { get; } internal ScriptExecutionState ExecutionState { get; } private ImmutableArray<ScriptVariable> _lazyVariables; private IReadOnlyDictionary<string, int> _lazyVariableMap; internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt) { Debug.Assert(executionState != null); Debug.Assert(script != null); ExecutionState = executionState; Script = script; Exception = exceptionOpt; } /// <summary> /// The final value produced by running the script. /// </summary> public object ReturnValue => GetReturnValue(); internal abstract object GetReturnValue(); /// <summary> /// Returns variables defined by the scripts in the declaration order. /// </summary> public ImmutableArray<ScriptVariable> Variables { get { if (_lazyVariables == null) { ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables()); } return _lazyVariables; } } /// <summary> /// Returns a script variable of the specified name. /// </summary> /// <remarks> /// If multiple script variables are defined in the script (in distinct submissions) returns the last one. /// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts. /// </remarks> /// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> public ScriptVariable GetVariable(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } int index; return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null; } private ImmutableArray<ScriptVariable> CreateVariables() { var result = ArrayBuilder<ScriptVariable>.GetInstance(); var executionState = ExecutionState; // Don't include the globals object (slot #0) for (int i = 1; i < executionState.SubmissionStateCount; i++) { var state = executionState.GetSubmissionState(i); Debug.Assert(state != null); foreach (var field in state.GetType().GetTypeInfo().DeclaredFields) { // TODO: synthesized fields of submissions shouldn't be public if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_')) { result.Add(new ScriptVariable(state, field)); } } } return result.ToImmutableAndFree(); } private IReadOnlyDictionary<string, int> GetVariableMap() { if (_lazyVariableMap == null) { var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer); for (int i = 0; i < Variables.Length; i++) { map[Variables[i].Name] = i; } _lazyVariableMap = map; } return _lazyVariableMap; } /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<object>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<TResult>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken); // How do we resolve overloads? We should use the language semantics. // https://github.com/dotnet/roslyn/issues/3720 #if TODO /// <summary> /// Invoke a method declared by the script. /// </summary> public object Invoke(string name, params object[] args) { var func = this.FindMethod(name, args != null ? args.Length : 0); if (func != null) { return func(args); } return null; } private Func<object[], object> FindMethod(string name, int argCount) { for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMethod(type, name, argCount); if (method != null) { return (args) => method.Invoke(sub, args); } } } return null; } private MethodInfo FindMethod(Type type, string name, int argCount) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } /// <summary> /// Create a delegate to a method declared by the script. /// </summary> public TDelegate CreateDelegate<TDelegate>(string name) { var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMatchingMethod(type, name, delegateInvokeMethod); if (method != null) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub); } } } return default(TDelegate); } private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod) { var dprms = delegateInvokeMethod.GetParameters(); foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (mi.Name == name) { var prms = mi.GetParameters(); if (prms.Length == dprms.Length) { // TODO: better matching.. return mi; } } } return null; } #endif } public sealed class ScriptState<T> : ScriptState { public new T ReturnValue { get; } internal override object GetReturnValue() => ReturnValue; internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt) : base(executionState, script, exceptionOpt) { ReturnValue = value; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for code fixes provided by a <see cref="CodeFixProvider"/>. /// </summary> public struct CodeFixContext : ITypeScriptCodeFixContext { private readonly Document _document; private readonly Project _project; private readonly TextSpan _span; private readonly ImmutableArray<Diagnostic> _diagnostics; private readonly CancellationToken _cancellationToken; private readonly Action<CodeAction, ImmutableArray<Diagnostic>> _registerCodeFix; /// <summary> /// Document corresponding to the <see cref="CodeFixContext.Span"/> to fix. /// </summary> public Document Document => _document; /// <summary> /// Project corresponding to the diagnostics to fix. /// </summary> internal Project Project => _project; /// <summary> /// Text span within the <see cref="CodeFixContext.Document"/> to fix. /// </summary> public TextSpan Span => _span; /// <summary> /// Diagnostics to fix. /// NOTE: All the diagnostics in this collection have the same <see cref="CodeFixContext.Span"/>. /// </summary> public ImmutableArray<Diagnostic> Diagnostics => _diagnostics; /// <summary> /// CancellationToken. /// </summary> public CancellationToken CancellationToken => _cancellationToken; private readonly bool _isBlocking; bool ITypeScriptCodeFixContext.IsBlocking => _isBlocking; /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="span">Text span within the <paramref name="document"/> to fix.</param> /// <param name="diagnostics"> /// Diagnostics to fix. /// All the diagnostics must have the same <paramref name="span"/>. /// Additionally, the <see cref="Diagnostic.Id"/> of each diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Throws this exception if the given <paramref name="diagnostics"/> is empty, /// has a null element or has an element whose span is not equal to <paramref name="span"/>. /// </exception> public CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, span, diagnostics, registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="diagnostic"> /// Diagnostic to fix. /// The <see cref="Diagnostic.Id"/> of this diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> public CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking: false, cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking, cancellationToken) { } private CodeFixContext( Document document, Project project, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) { if (verifyArguments) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (registerCodeFix == null) { throw new ArgumentNullException(nameof(registerCodeFix)); } VerifyDiagnosticsArgument(diagnostics, span); } _document = document; _project = project; _span = span; _diagnostics = diagnostics; _registerCodeFix = registerCodeFix; _cancellationToken = cancellationToken; _isBlocking = isBlocking; } internal CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments, cancellationToken) { } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostic">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, Diagnostic diagnostic) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } _registerCodeFix(action, ImmutableArray.Create(diagnostic)); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { throw new ArgumentNullException(nameof(diagnostics)); } RegisterCodeFix(action, diagnostics.ToImmutableArray()); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, ImmutableArray<Diagnostic> diagnostics) { if (action == null) { throw new ArgumentNullException(nameof(action)); } VerifyDiagnosticsArgument(diagnostics, _span); // TODO: // - Check that all diagnostics are unique (no duplicates). // - Check that supplied diagnostics form subset of diagnostics originally // passed to the provider via CodeFixContext.Diagnostics. _registerCodeFix(action, diagnostics); } private static void VerifyDiagnosticsArgument(ImmutableArray<Diagnostic> diagnostics, TextSpan span) { if (diagnostics.IsDefault) { throw new ArgumentException(nameof(diagnostics)); } if (diagnostics.Length == 0) { throw new ArgumentException(WorkspacesResources.At_least_one_diagnostic_must_be_supplied, nameof(diagnostics)); } if (diagnostics.Any(d => d == null)) { throw new ArgumentException(WorkspaceExtensionsResources.Supplied_diagnostic_cannot_be_null, nameof(diagnostics)); } if (diagnostics.Any(d => d.Location.SourceSpan != span)) { throw new ArgumentException(string.Format(WorkspacesResources.Diagnostic_must_have_span_0, span.ToString()), nameof(diagnostics)); } } } internal interface ITypeScriptCodeFixContext { bool IsBlocking { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for code fixes provided by a <see cref="CodeFixProvider"/>. /// </summary> public struct CodeFixContext : ITypeScriptCodeFixContext { private readonly Document _document; private readonly Project _project; private readonly TextSpan _span; private readonly ImmutableArray<Diagnostic> _diagnostics; private readonly CancellationToken _cancellationToken; private readonly Action<CodeAction, ImmutableArray<Diagnostic>> _registerCodeFix; /// <summary> /// Document corresponding to the <see cref="CodeFixContext.Span"/> to fix. /// </summary> public Document Document => _document; /// <summary> /// Project corresponding to the diagnostics to fix. /// </summary> internal Project Project => _project; /// <summary> /// Text span within the <see cref="CodeFixContext.Document"/> to fix. /// </summary> public TextSpan Span => _span; /// <summary> /// Diagnostics to fix. /// NOTE: All the diagnostics in this collection have the same <see cref="CodeFixContext.Span"/>. /// </summary> public ImmutableArray<Diagnostic> Diagnostics => _diagnostics; /// <summary> /// CancellationToken. /// </summary> public CancellationToken CancellationToken => _cancellationToken; private readonly bool _isBlocking; bool ITypeScriptCodeFixContext.IsBlocking => _isBlocking; /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="span">Text span within the <paramref name="document"/> to fix.</param> /// <param name="diagnostics"> /// Diagnostics to fix. /// All the diagnostics must have the same <paramref name="span"/>. /// Additionally, the <see cref="Diagnostic.Id"/> of each diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Throws this exception if the given <paramref name="diagnostics"/> is empty, /// has a null element or has an element whose span is not equal to <paramref name="span"/>. /// </exception> public CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, span, diagnostics, registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="diagnostic"> /// Diagnostic to fix. /// The <see cref="Diagnostic.Id"/> of this diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> public CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking: false, cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking, cancellationToken) { } private CodeFixContext( Document document, Project project, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) { if (verifyArguments) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (registerCodeFix == null) { throw new ArgumentNullException(nameof(registerCodeFix)); } VerifyDiagnosticsArgument(diagnostics, span); } _document = document; _project = project; _span = span; _diagnostics = diagnostics; _registerCodeFix = registerCodeFix; _cancellationToken = cancellationToken; _isBlocking = isBlocking; } internal CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments, cancellationToken) { } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostic">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, Diagnostic diagnostic) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } _registerCodeFix(action, ImmutableArray.Create(diagnostic)); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { throw new ArgumentNullException(nameof(diagnostics)); } RegisterCodeFix(action, diagnostics.ToImmutableArray()); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, ImmutableArray<Diagnostic> diagnostics) { if (action == null) { throw new ArgumentNullException(nameof(action)); } VerifyDiagnosticsArgument(diagnostics, _span); // TODO: // - Check that all diagnostics are unique (no duplicates). // - Check that supplied diagnostics form subset of diagnostics originally // passed to the provider via CodeFixContext.Diagnostics. _registerCodeFix(action, diagnostics); } private static void VerifyDiagnosticsArgument(ImmutableArray<Diagnostic> diagnostics, TextSpan span) { if (diagnostics.IsDefault) { throw new ArgumentException(nameof(diagnostics)); } if (diagnostics.Length == 0) { throw new ArgumentException(WorkspacesResources.At_least_one_diagnostic_must_be_supplied, nameof(diagnostics)); } if (diagnostics.Any(d => d == null)) { throw new ArgumentException(WorkspaceExtensionsResources.Supplied_diagnostic_cannot_be_null, nameof(diagnostics)); } if (diagnostics.Any(d => d.Location.SourceSpan != span)) { throw new ArgumentException(string.Format(WorkspacesResources.Diagnostic_must_have_span_0, span.ToString()), nameof(diagnostics)); } } } internal interface ITypeScriptCodeFixContext { bool IsBlocking { get; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./docs/ide/test-plans/source-generators.md
## Features Opening New Windows 1. Locate a use of a generated symbol in the project, and invoke Go to Definition. - [ ] It works. 2. Locate a use of a generated symbol in the project, and invoke Go to Implementation. - [ ] It works. 3. Locate a use of a generated symbol in the project, and invoke Find References. - [ ] References to the generated symbol in regular code are located. - [ ] References to the generated symbol in generated code are located. ## Features That Are Blocked 1. Locate a use of a generated method in a project, and invoke Rename with Ctrl+R Ctrl+R. - [ ] It should be blocked. 2. Locate a use of a generated method in a project, change the name at the use site. - [ ] **[NOT WORKING YET]** Rename tracking should not trigger. ## Navigating within a Generated Document 1. Invoke Go to Definition on a generated symbol to open a source generated file. - [ ] **[NOT WORKING YET]** The navigation bar on the top of the file shows the project that contains the generated source 2. Invoke Find References on the symbol we navigated to. - [ ] **[NOT WORKING YET]** The original reference should appear in find references. 3. Click on some symbol used more than once in a generated file. - [ ] Highlight references should highlight all uses in the file. ## Window > New Window Support 1. Invoke Go to Definition to open a source-generated file. Then do Window > New Window to ensure that the new window is set up correctly. - [ ] It's read only. - [ ] The title and caption are correct. 2. Remove the source generator from the project. - [ ] Confirm the first window correctly gets an info bar showing the file is no longer valid. - [ ] Confirm the second window correctly gets an info bar showing the file is no longer valid.
## Features Opening New Windows 1. Locate a use of a generated symbol in the project, and invoke Go to Definition. - [ ] It works. 2. Locate a use of a generated symbol in the project, and invoke Go to Implementation. - [ ] It works. 3. Locate a use of a generated symbol in the project, and invoke Find References. - [ ] References to the generated symbol in regular code are located. - [ ] References to the generated symbol in generated code are located. ## Features That Are Blocked 1. Locate a use of a generated method in a project, and invoke Rename with Ctrl+R Ctrl+R. - [ ] It should be blocked. 2. Locate a use of a generated method in a project, change the name at the use site. - [ ] **[NOT WORKING YET]** Rename tracking should not trigger. ## Navigating within a Generated Document 1. Invoke Go to Definition on a generated symbol to open a source generated file. - [ ] **[NOT WORKING YET]** The navigation bar on the top of the file shows the project that contains the generated source 2. Invoke Find References on the symbol we navigated to. - [ ] **[NOT WORKING YET]** The original reference should appear in find references. 3. Click on some symbol used more than once in a generated file. - [ ] Highlight references should highlight all uses in the file. ## Window > New Window Support 1. Invoke Go to Definition to open a source-generated file. Then do Window > New Window to ensure that the new window is set up correctly. - [ ] It's read only. - [ ] The title and caption are correct. 2. Remove the source generator from the project. - [ ] Confirm the first window correctly gets an info bar showing the file is no longer valid. - [ ] Confirm the second window correctly gets an info bar showing the file is no longer valid.
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelNavigationPointServiceFactory.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel <ExportLanguageServiceFactory(GetType(ICodeModelNavigationPointService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicCodeModelNavigationPointServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService ' This interface is implemented by the ICodeModelService as well, so just grab the other one and return it Return provider.GetService(Of ICodeModelService) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel <ExportLanguageServiceFactory(GetType(ICodeModelNavigationPointService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicCodeModelNavigationPointServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService ' This interface is implemented by the ICodeModelService as well, so just grab the other one and return it Return provider.GetService(Of ICodeModelService) End Function End Class End Namespace
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/VisualBasic/Portable/Structure/VisualBasicStructureHelpers.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.Runtime.InteropServices Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Module VisualBasicOutliningHelpers Public Const Ellipsis = "..." Public Const SpaceEllipsis = " " & Ellipsis Public Const MaxXmlDocCommentBannerLength = 120 Private Function GetNodeBannerText(node As SyntaxNode) As String Return node.ConvertToSingleLine().ToString() & SpaceEllipsis End Function Private Function GetCommentBannerText(comment As SyntaxTrivia) As String Return "' " & comment.ToString().Substring(1).Trim() & SpaceEllipsis End Function Private Function CreateCommentsRegion(startComment As SyntaxTrivia, endComment As SyntaxTrivia) As BlockSpan? Dim span = TextSpan.FromBounds(startComment.SpanStart, endComment.Span.End) Return CreateBlockSpan( span, span, GetCommentBannerText(startComment), autoCollapse:=True, type:=BlockTypes.Comment, isCollapsible:=True, isDefaultCollapsed:=False) End Function ' For testing purposes Friend Function CreateCommentsRegions(triviaList As SyntaxTriviaList) As ImmutableArray(Of BlockSpan) Dim spans = TemporaryArray(Of BlockSpan).Empty Try CollectCommentsRegions(triviaList, spans) Return spans.ToImmutableAndClear() Finally spans.Dispose() End Try End Function Friend Sub CollectCommentsRegions(triviaList As SyntaxTriviaList, ByRef spans As TemporaryArray(Of BlockSpan)) If triviaList.Count > 0 Then Dim startComment As SyntaxTrivia? = Nothing Dim endComment As SyntaxTrivia? = Nothing ' Iterate through trivia and collect groups of contiguous single-line comments that are only separated by whitespace For Each trivia In triviaList If trivia.Kind = SyntaxKind.CommentTrivia Then startComment = If(startComment, trivia) endComment = trivia ElseIf trivia.Kind <> SyntaxKind.WhitespaceTrivia AndAlso trivia.Kind <> SyntaxKind.EndOfLineTrivia AndAlso trivia.Kind <> SyntaxKind.EndOfFileToken Then If startComment IsNot Nothing Then spans.AddIfNotNull(CreateCommentsRegion(startComment.Value, endComment.Value)) startComment = Nothing endComment = Nothing End If End If Next ' Add any final span If startComment IsNot Nothing Then spans.AddIfNotNull(CreateCommentsRegion(startComment.Value, endComment.Value)) End If End If End Sub Friend Sub CollectCommentsRegions(node As SyntaxNode, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider) If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim span As BlockSpan = Nothing If optionProvider.IsMetadataAsSource AndAlso TryGetLeadingCollapsibleSpan(node, span) Then spans.Add(span) Else Dim triviaList = node.GetLeadingTrivia() CollectCommentsRegions(triviaList, spans) End If End Sub Private Function TryGetLeadingCollapsibleSpan(node As SyntaxNode, <[Out]> ByRef span As BlockSpan) As Boolean Dim startToken = node.GetFirstToken() Dim endToken = GetEndToken(node) If startToken.IsKind(SyntaxKind.None) OrElse endToken.IsKind(SyntaxKind.None) Then ' if valid tokens can't be found then a meaningful span can't be generated span = Nothing Return False End If Dim firstComment = startToken.LeadingTrivia.FirstOrNull(Function(t) t.Kind = SyntaxKind.CommentTrivia) Dim startPosition = If(firstComment.HasValue, firstComment.Value.SpanStart, startToken.SpanStart) Dim endPosition = endToken.SpanStart ' TODO (tomescht): Mark the regions to be collapsed by default. If startPosition <> endPosition Then Dim hintTextEndToken = GetHintTextEndToken(node) span = New BlockSpan( isCollapsible:=True, type:=BlockTypes.Comment, textSpan:=TextSpan.FromBounds(startPosition, endPosition), hintSpan:=TextSpan.FromBounds(startPosition, hintTextEndToken.Span.End), bannerText:=Ellipsis, autoCollapse:=True) Return True End If span = Nothing Return False End Function Private Function GetEndToken(node As SyntaxNode) As SyntaxToken If node.IsKind(SyntaxKind.SubNewStatement) Then Dim subNewStatement = DirectCast(node, SubNewStatementSyntax) Return If(subNewStatement.Modifiers.FirstOrNull(), subNewStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement) Then Dim delegateStatement = DirectCast(node, DelegateStatementSyntax) Return If(delegateStatement.Modifiers.FirstOrNull(), delegateStatement.DelegateKeyword) ElseIf node.IsKind(SyntaxKind.EnumStatement) Then Dim enumStatement = DirectCast(node, EnumStatementSyntax) Return If(enumStatement.Modifiers.FirstOrNull(), enumStatement.EnumKeyword) ElseIf node.IsKind(SyntaxKind.EnumMemberDeclaration) Then Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax) Return enumMemberDeclaration.Identifier ElseIf node.IsKind(SyntaxKind.EventStatement) Then Dim eventStatement = DirectCast(node, EventStatementSyntax) Return If(eventStatement.Modifiers.FirstOrNull(), If(eventStatement.CustomKeyword.IsKind(SyntaxKind.None), eventStatement.DeclarationKeyword, eventStatement.CustomKeyword)) ElseIf node.IsKind(SyntaxKind.FieldDeclaration) Then Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax) Return If(fieldDeclaration.Modifiers.FirstOrNull(), fieldDeclaration.Declarators.First().GetFirstToken()) ElseIf node.IsKind(SyntaxKind.SubStatement, SyntaxKind.FunctionStatement) Then Dim methodStatement = DirectCast(node, MethodStatementSyntax) Return If(methodStatement.Modifiers.FirstOrNull(), methodStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.OperatorStatement) Then Dim operatorStatement = DirectCast(node, OperatorStatementSyntax) Return If(operatorStatement.Modifiers.FirstOrNull(), operatorStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then Dim propertyStatement = DirectCast(node, PropertyStatementSyntax) Return If(propertyStatement.Modifiers.FirstOrNull(), propertyStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement) Then Dim typeStatement = DirectCast(node, TypeStatementSyntax) Return If(typeStatement.Modifiers.FirstOrNull(), typeStatement.DeclarationKeyword) Else Return Nothing End If End Function Private Function GetHintTextEndToken(node As SyntaxNode) As SyntaxToken Return node.GetLastToken() End Function Friend Function CreateBlockSpan( span As TextSpan, hintSpan As TextSpan, bannerText As String, autoCollapse As Boolean, type As String, isCollapsible As Boolean, isDefaultCollapsed As Boolean) As BlockSpan? Return New BlockSpan( textSpan:=span, hintSpan:=hintSpan, bannerText:=bannerText, autoCollapse:=autoCollapse, isDefaultCollapsed:=isDefaultCollapsed, type:=type, isCollapsible:=isCollapsible) End Function Friend Function CreateBlockSpanFromBlock( blockNode As SyntaxNode, bannerText As String, autoCollapse As Boolean, type As String, isCollapsible As Boolean) As BlockSpan? Return CreateBlockSpan( blockNode.Span, GetHintSpan(blockNode), bannerText, autoCollapse, type, isCollapsible, isDefaultCollapsed:=False) End Function Friend Function CreateBlockSpanFromBlock( blockNode As SyntaxNode, bannerNode As SyntaxNode, autoCollapse As Boolean, type As String, isCollapsible As Boolean) As BlockSpan? Return CreateBlockSpan( blockNode.Span, GetHintSpan(blockNode), GetNodeBannerText(bannerNode), autoCollapse, type, isCollapsible, isDefaultCollapsed:=False) End Function Private Function GetHintSpan(blockNode As SyntaxNode) As TextSpan ' Don't include attributes in the hint-span for a block. We don't want ' the attributes to show up when users hover over indent guide lines. Dim firstToken = blockNode.GetFirstToken() If firstToken.Kind() = SyntaxKind.LessThanToken AndAlso firstToken.Parent.IsKind(SyntaxKind.AttributeList) Then Dim attributeOwner = firstToken.Parent.Parent For Each child In attributeOwner.ChildNodesAndTokens If child.Kind() <> SyntaxKind.AttributeList Then Return TextSpan.FromBounds(child.SpanStart, blockNode.Span.End) End If Next End If Return blockNode.Span 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.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Module VisualBasicOutliningHelpers Public Const Ellipsis = "..." Public Const SpaceEllipsis = " " & Ellipsis Public Const MaxXmlDocCommentBannerLength = 120 Private Function GetNodeBannerText(node As SyntaxNode) As String Return node.ConvertToSingleLine().ToString() & SpaceEllipsis End Function Private Function GetCommentBannerText(comment As SyntaxTrivia) As String Return "' " & comment.ToString().Substring(1).Trim() & SpaceEllipsis End Function Private Function CreateCommentsRegion(startComment As SyntaxTrivia, endComment As SyntaxTrivia) As BlockSpan? Dim span = TextSpan.FromBounds(startComment.SpanStart, endComment.Span.End) Return CreateBlockSpan( span, span, GetCommentBannerText(startComment), autoCollapse:=True, type:=BlockTypes.Comment, isCollapsible:=True, isDefaultCollapsed:=False) End Function ' For testing purposes Friend Function CreateCommentsRegions(triviaList As SyntaxTriviaList) As ImmutableArray(Of BlockSpan) Dim spans = TemporaryArray(Of BlockSpan).Empty Try CollectCommentsRegions(triviaList, spans) Return spans.ToImmutableAndClear() Finally spans.Dispose() End Try End Function Friend Sub CollectCommentsRegions(triviaList As SyntaxTriviaList, ByRef spans As TemporaryArray(Of BlockSpan)) If triviaList.Count > 0 Then Dim startComment As SyntaxTrivia? = Nothing Dim endComment As SyntaxTrivia? = Nothing ' Iterate through trivia and collect groups of contiguous single-line comments that are only separated by whitespace For Each trivia In triviaList If trivia.Kind = SyntaxKind.CommentTrivia Then startComment = If(startComment, trivia) endComment = trivia ElseIf trivia.Kind <> SyntaxKind.WhitespaceTrivia AndAlso trivia.Kind <> SyntaxKind.EndOfLineTrivia AndAlso trivia.Kind <> SyntaxKind.EndOfFileToken Then If startComment IsNot Nothing Then spans.AddIfNotNull(CreateCommentsRegion(startComment.Value, endComment.Value)) startComment = Nothing endComment = Nothing End If End If Next ' Add any final span If startComment IsNot Nothing Then spans.AddIfNotNull(CreateCommentsRegion(startComment.Value, endComment.Value)) End If End If End Sub Friend Sub CollectCommentsRegions(node As SyntaxNode, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider) If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim span As BlockSpan = Nothing If optionProvider.IsMetadataAsSource AndAlso TryGetLeadingCollapsibleSpan(node, span) Then spans.Add(span) Else Dim triviaList = node.GetLeadingTrivia() CollectCommentsRegions(triviaList, spans) End If End Sub Private Function TryGetLeadingCollapsibleSpan(node As SyntaxNode, <[Out]> ByRef span As BlockSpan) As Boolean Dim startToken = node.GetFirstToken() Dim endToken = GetEndToken(node) If startToken.IsKind(SyntaxKind.None) OrElse endToken.IsKind(SyntaxKind.None) Then ' if valid tokens can't be found then a meaningful span can't be generated span = Nothing Return False End If Dim firstComment = startToken.LeadingTrivia.FirstOrNull(Function(t) t.Kind = SyntaxKind.CommentTrivia) Dim startPosition = If(firstComment.HasValue, firstComment.Value.SpanStart, startToken.SpanStart) Dim endPosition = endToken.SpanStart ' TODO (tomescht): Mark the regions to be collapsed by default. If startPosition <> endPosition Then Dim hintTextEndToken = GetHintTextEndToken(node) span = New BlockSpan( isCollapsible:=True, type:=BlockTypes.Comment, textSpan:=TextSpan.FromBounds(startPosition, endPosition), hintSpan:=TextSpan.FromBounds(startPosition, hintTextEndToken.Span.End), bannerText:=Ellipsis, autoCollapse:=True) Return True End If span = Nothing Return False End Function Private Function GetEndToken(node As SyntaxNode) As SyntaxToken If node.IsKind(SyntaxKind.SubNewStatement) Then Dim subNewStatement = DirectCast(node, SubNewStatementSyntax) Return If(subNewStatement.Modifiers.FirstOrNull(), subNewStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement) Then Dim delegateStatement = DirectCast(node, DelegateStatementSyntax) Return If(delegateStatement.Modifiers.FirstOrNull(), delegateStatement.DelegateKeyword) ElseIf node.IsKind(SyntaxKind.EnumStatement) Then Dim enumStatement = DirectCast(node, EnumStatementSyntax) Return If(enumStatement.Modifiers.FirstOrNull(), enumStatement.EnumKeyword) ElseIf node.IsKind(SyntaxKind.EnumMemberDeclaration) Then Dim enumMemberDeclaration = DirectCast(node, EnumMemberDeclarationSyntax) Return enumMemberDeclaration.Identifier ElseIf node.IsKind(SyntaxKind.EventStatement) Then Dim eventStatement = DirectCast(node, EventStatementSyntax) Return If(eventStatement.Modifiers.FirstOrNull(), If(eventStatement.CustomKeyword.IsKind(SyntaxKind.None), eventStatement.DeclarationKeyword, eventStatement.CustomKeyword)) ElseIf node.IsKind(SyntaxKind.FieldDeclaration) Then Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax) Return If(fieldDeclaration.Modifiers.FirstOrNull(), fieldDeclaration.Declarators.First().GetFirstToken()) ElseIf node.IsKind(SyntaxKind.SubStatement, SyntaxKind.FunctionStatement) Then Dim methodStatement = DirectCast(node, MethodStatementSyntax) Return If(methodStatement.Modifiers.FirstOrNull(), methodStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.OperatorStatement) Then Dim operatorStatement = DirectCast(node, OperatorStatementSyntax) Return If(operatorStatement.Modifiers.FirstOrNull(), operatorStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then Dim propertyStatement = DirectCast(node, PropertyStatementSyntax) Return If(propertyStatement.Modifiers.FirstOrNull(), propertyStatement.DeclarationKeyword) ElseIf node.IsKind(SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement) Then Dim typeStatement = DirectCast(node, TypeStatementSyntax) Return If(typeStatement.Modifiers.FirstOrNull(), typeStatement.DeclarationKeyword) Else Return Nothing End If End Function Private Function GetHintTextEndToken(node As SyntaxNode) As SyntaxToken Return node.GetLastToken() End Function Friend Function CreateBlockSpan( span As TextSpan, hintSpan As TextSpan, bannerText As String, autoCollapse As Boolean, type As String, isCollapsible As Boolean, isDefaultCollapsed As Boolean) As BlockSpan? Return New BlockSpan( textSpan:=span, hintSpan:=hintSpan, bannerText:=bannerText, autoCollapse:=autoCollapse, isDefaultCollapsed:=isDefaultCollapsed, type:=type, isCollapsible:=isCollapsible) End Function Friend Function CreateBlockSpanFromBlock( blockNode As SyntaxNode, bannerText As String, autoCollapse As Boolean, type As String, isCollapsible As Boolean) As BlockSpan? Return CreateBlockSpan( blockNode.Span, GetHintSpan(blockNode), bannerText, autoCollapse, type, isCollapsible, isDefaultCollapsed:=False) End Function Friend Function CreateBlockSpanFromBlock( blockNode As SyntaxNode, bannerNode As SyntaxNode, autoCollapse As Boolean, type As String, isCollapsible As Boolean) As BlockSpan? Return CreateBlockSpan( blockNode.Span, GetHintSpan(blockNode), GetNodeBannerText(bannerNode), autoCollapse, type, isCollapsible, isDefaultCollapsed:=False) End Function Private Function GetHintSpan(blockNode As SyntaxNode) As TextSpan ' Don't include attributes in the hint-span for a block. We don't want ' the attributes to show up when users hover over indent guide lines. Dim firstToken = blockNode.GetFirstToken() If firstToken.Kind() = SyntaxKind.LessThanToken AndAlso firstToken.Parent.IsKind(SyntaxKind.AttributeList) Then Dim attributeOwner = firstToken.Parent.Parent For Each child In attributeOwner.ChildNodesAndTokens If child.Kind() <> SyntaxKind.AttributeList Then Return TextSpan.FromBounds(child.SpanStart, blockNode.Span.End) End If Next End If Return blockNode.Span End Function End Module End Namespace
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { /// <summary> /// Base type for legacy C# and VB project system shim implementations. /// These legacy shims are based on legacy project system interfaces defined in csproj/msvbprj. /// </summary> internal abstract partial class AbstractLegacyProject : ForegroundThreadAffinitizedObject { public IVsHierarchy Hierarchy { get; } protected VisualStudioProject VisualStudioProject { get; } internal VisualStudioProjectOptionsProcessor VisualStudioProjectOptionsProcessor { get; set; } protected IProjectCodeModel ProjectCodeModel { get; set; } protected VisualStudioWorkspace Workspace { get; } internal VisualStudioProject Test_VisualStudioProject => VisualStudioProject; /// <summary> /// The path to the directory of the project. Read-only, since although you can rename /// a project in Visual Studio you can't change the folder of a project without an /// unload/reload. /// </summary> private readonly string _projectDirectory = null; /// <summary> /// Whether we should ignore the output path for this project because it's a special project. /// </summary> private readonly bool _ignoreOutputPath; private static readonly char[] PathSeparatorCharacters = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; #region Mutable fields that should only be used from the UI thread private readonly SolutionEventsBatchScopeCreator _batchScopeCreator; #endregion public AbstractLegacyProject( string projectSystemName, IVsHierarchy hierarchy, string language, bool isVsIntellisenseProject, IServiceProvider serviceProvider, IThreadingContext threadingContext, string externalErrorReportingPrefix) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(hierarchy); var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); Workspace = componentModel.GetService<VisualStudioWorkspace>(); var workspaceImpl = (VisualStudioWorkspaceImpl)Workspace; var projectFilePath = hierarchy.TryGetProjectFilePath(); if (projectFilePath != null && !File.Exists(projectFilePath)) { projectFilePath = null; } if (projectFilePath != null) { _projectDirectory = Path.GetDirectoryName(projectFilePath); } if (isVsIntellisenseProject) { // IVsIntellisenseProjects are usually used for contained language cases, which means these projects don't have any real // output path that we should consider. Since those point to the same IVsHierarchy as another project, we end up with two projects // with the same output path, which potentially breaks conversion of metadata references to project references. However they're // also used for database projects and a few other cases where there there isn't a "primary" IVsHierarchy. // As a heuristic here we'll ignore the output path if we already have another project tied to the IVsHierarchy. foreach (var projectId in Workspace.CurrentSolution.ProjectIds) { if (Workspace.GetHierarchy(projectId) == hierarchy) { _ignoreOutputPath = true; break; } } } var projectFactory = componentModel.GetService<VisualStudioProjectFactory>(); VisualStudioProject = threadingContext.JoinableTaskFactory.Run(() => projectFactory.CreateAndAddToWorkspaceAsync( projectSystemName, language, new VisualStudioProjectCreationInfo { // The workspace requires an assembly name so we can make compilations. We'll use // projectSystemName because they'll have a better one eventually. AssemblyName = projectSystemName, FilePath = projectFilePath, Hierarchy = hierarchy, ProjectGuid = GetProjectIDGuid(hierarchy), }, CancellationToken.None)); workspaceImpl.AddProjectRuleSetFileToInternalMaps( VisualStudioProject, () => VisualStudioProjectOptionsProcessor.EffectiveRuleSetFilePath); // Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace // by assigning the value of the project's root namespace to it. So various feature can choose to // use it for their own purpose. // In the future, we might consider officially exposing "default namespace" for VB project // (e.g. through a <defaultnamespace> msbuild property) VisualStudioProject.DefaultNamespace = GetRootNamespacePropertyValue(hierarchy); if (TryGetPropertyValue(hierarchy, AdditionalPropertyNames.MaxSupportedLangVersion, out var maxLangVer)) { VisualStudioProject.MaxLangVersion = maxLangVer; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzers, out var runAnayzers)) { VisualStudioProject.RunAnalyzers = runAnayzers; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, out var runAnayzersDuringLiveAnalysis)) { VisualStudioProject.RunAnalyzersDuringLiveAnalysis = runAnayzersDuringLiveAnalysis; } Hierarchy = hierarchy; ConnectHierarchyEvents(); RefreshBinOutputPath(); workspaceImpl.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); _externalErrorReporter = new ProjectExternalErrorReporter(VisualStudioProject.Id, externalErrorReportingPrefix, language, workspaceImpl); _batchScopeCreator = componentModel.GetService<SolutionEventsBatchScopeCreator>(); _batchScopeCreator.StartTrackingProject(VisualStudioProject, Hierarchy); } public string AssemblyName => VisualStudioProject.AssemblyName; public string GetOutputFileName() => VisualStudioProject.CompilationOutputAssemblyFilePath; public virtual void Disconnect() { _batchScopeCreator.StopTrackingProject(VisualStudioProject); VisualStudioProjectOptionsProcessor?.Dispose(); ProjectCodeModel.OnProjectClosed(); VisualStudioProject.RemoveFromWorkspace(); // Unsubscribe IVsHierarchyEvents DisconnectHierarchyEvents(); } protected void AddFile( string filename, SourceCodeKind sourceCodeKind) { AssertIsForeground(); // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } ImmutableArray<string> folders = default; var itemid = Hierarchy.TryGetItemId(filename); if (itemid != VSConstants.VSITEMID_NIL) { folders = GetFolderNamesForDocument(itemid); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void AddFile( string filename, string linkMetadata, SourceCodeKind sourceCodeKind) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } var folders = ImmutableArray<string>.Empty; if (!string.IsNullOrEmpty(linkMetadata)) { var linkFolderPath = Path.GetDirectoryName(linkMetadata); folders = linkFolderPath.Split(PathSeparatorCharacters, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray(); } else if (!string.IsNullOrEmpty(VisualStudioProject.FilePath)) { var relativePath = PathUtilities.GetRelativePath(_projectDirectory, filename); var relativePathParts = relativePath.Split(PathSeparatorCharacters); folders = ImmutableArray.Create(relativePathParts, start: 0, length: relativePathParts.Length - 1); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void RemoveFile(string filename) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } VisualStudioProject.RemoveSourceFile(filename); ProjectCodeModel.OnSourceFileRemoved(filename); } protected void RefreshBinOutputPath() { // These projects are created against the same hierarchy as the "main" project that // hosts the rest of the code; if we query the IVsHierarchy for the output path // we'll end up with duplicate output paths which can break P2P referencing. Since the output // path doesn't make sense for these, we'll ignore them. if (_ignoreOutputPath) { return; } if (Hierarchy is not IVsBuildPropertyStorage storage) { return; } if (ErrorHandler.Failed(storage.GetPropertyValue("OutDir", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var outputDirectory)) || ErrorHandler.Failed(storage.GetPropertyValue("TargetFileName", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetFileName))) { return; } if (targetFileName == null) { return; } // web app case if (!PathUtilities.IsAbsolute(outputDirectory)) { if (VisualStudioProject.FilePath == null) { return; } outputDirectory = FileUtilities.ResolveRelativePath(outputDirectory, Path.GetDirectoryName(VisualStudioProject.FilePath)); } if (outputDirectory == null) { return; } VisualStudioProject.OutputFilePath = FileUtilities.NormalizeAbsolutePath(Path.Combine(outputDirectory, targetFileName)); if (ErrorHandler.Succeeded(storage.GetPropertyValue("TargetRefPath", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetRefPath)) && !string.IsNullOrEmpty(targetRefPath)) { VisualStudioProject.OutputRefFilePath = targetRefPath; } else { VisualStudioProject.OutputRefFilePath = null; } } private static Guid GetProjectIDGuid(IVsHierarchy hierarchy) { if (hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_ProjectIDGuid, out var guid)) { return guid; } return Guid.Empty; } /// <summary> /// Map of folder item IDs in the workspace to the string version of their path. /// </summary> /// <remarks>Using item IDs as a key like this in a long-lived way is considered unsupported by CPS and other /// IVsHierarchy providers, but this code (which is fairly old) still makes the assumptions anyways.</remarks> private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new(); private ImmutableArray<string> GetFolderNamesForDocument(uint documentItemID) { AssertIsForeground(); if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { return GetFolderNamesForFolder(parentID); } } return ImmutableArray<string>.Empty; } private ImmutableArray<string> GetFolderNamesForFolder(uint folderItemID) { AssertIsForeground(); using var pooledObject = SharedPools.Default<List<string>>().GetPooledObject(); var newFolderNames = pooledObject.Object; if (!_folderNameMap.TryGetValue(folderItemID, out var folderNames)) { ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); folderNames = newFolderNames.ToImmutableArray(); _folderNameMap.Add(folderItemID, folderNames); } else { // verify names, and change map if we get a different set. // this is necessary because we only get document adds/removes from the project system // when a document name or folder name changes. ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); if (!Enumerable.SequenceEqual(folderNames, newFolderNames)) { folderNames = newFolderNames.ToImmutableArray(); _folderNameMap[folderItemID] = folderNames; } } return folderNames; } // Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds. // Technically it should be a uint. However, there's no enforcement of this, and marshalling // from native to managed can end up resulting in boxed ints instead. Handle both here so // we're resilient to however the IVsHierarchy was actually implemented. private static uint UnboxVSItemId(object id) => id is uint ? (uint)id : unchecked((uint)(int)id); private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy) { if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out var nameObj) == VSConstants.S_OK) { // For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>) // as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder // is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders. // Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to // worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for // VSITEMID.Root below already takes care of that. var name = (string)nameObj; if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase)) { names.Insert(0, name); } } if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { ComputeFolderNames(parentID, names, hierarchy); } } } /// <summary> /// Get the value of "rootnamespace" property of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// This property has different meaning between C# and VB, each project type can decide how to interpret the value. /// </remarks>> private static string GetRootNamespacePropertyValue(IVsHierarchy hierarchy) { // While both csproj and vbproj might define <rootnamespace> property in the project file, // they are very different things. // // In C#, it's called default namespace (even though we got the value from rootnamespace property), // and it doesn't affect the semantic of the code in anyway, just something used by VS. // For example, when you create a new class, the namespace for the new class is based on it. // Therefore, we can't get this info from compiler. // // However, in VB, it's actually called root namespace, and that info is part of the VB compilation // (parsed from arguments), because VB compiler needs it to determine the root of all the namespace // declared in the compilation. // // Unfortunately, although being different concepts, default namespace and root namespace are almost // used interchangeably in VS. For example, (1) the value is define in "rootnamespace" property in project // files and, (2) the property name we use to call into hierarchy below to retrieve the value is // called "DefaultNamespace". if (hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_DefaultNamespace, out string value)) { return value; } return null; } private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, out string propertyValue) { if (hierarchy is not IVsBuildPropertyStorage storage) { propertyValue = null; return false; } return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue)); } private static bool TryGetBoolPropertyValue(IVsHierarchy hierarchy, string propertyName, out bool? propertyValue) { if (!TryGetPropertyValue(hierarchy, propertyName, out var stringPropertyValue)) { propertyValue = null; return false; } propertyValue = bool.TryParse(stringPropertyValue, out var parsedBoolValue) ? parsedBoolValue : (bool?)null; 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.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { /// <summary> /// Base type for legacy C# and VB project system shim implementations. /// These legacy shims are based on legacy project system interfaces defined in csproj/msvbprj. /// </summary> internal abstract partial class AbstractLegacyProject : ForegroundThreadAffinitizedObject { public IVsHierarchy Hierarchy { get; } protected VisualStudioProject VisualStudioProject { get; } internal VisualStudioProjectOptionsProcessor VisualStudioProjectOptionsProcessor { get; set; } protected IProjectCodeModel ProjectCodeModel { get; set; } protected VisualStudioWorkspace Workspace { get; } internal VisualStudioProject Test_VisualStudioProject => VisualStudioProject; /// <summary> /// The path to the directory of the project. Read-only, since although you can rename /// a project in Visual Studio you can't change the folder of a project without an /// unload/reload. /// </summary> private readonly string _projectDirectory = null; /// <summary> /// Whether we should ignore the output path for this project because it's a special project. /// </summary> private readonly bool _ignoreOutputPath; private static readonly char[] PathSeparatorCharacters = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; #region Mutable fields that should only be used from the UI thread private readonly SolutionEventsBatchScopeCreator _batchScopeCreator; #endregion public AbstractLegacyProject( string projectSystemName, IVsHierarchy hierarchy, string language, bool isVsIntellisenseProject, IServiceProvider serviceProvider, IThreadingContext threadingContext, string externalErrorReportingPrefix) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(hierarchy); var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); Workspace = componentModel.GetService<VisualStudioWorkspace>(); var workspaceImpl = (VisualStudioWorkspaceImpl)Workspace; var projectFilePath = hierarchy.TryGetProjectFilePath(); if (projectFilePath != null && !File.Exists(projectFilePath)) { projectFilePath = null; } if (projectFilePath != null) { _projectDirectory = Path.GetDirectoryName(projectFilePath); } if (isVsIntellisenseProject) { // IVsIntellisenseProjects are usually used for contained language cases, which means these projects don't have any real // output path that we should consider. Since those point to the same IVsHierarchy as another project, we end up with two projects // with the same output path, which potentially breaks conversion of metadata references to project references. However they're // also used for database projects and a few other cases where there there isn't a "primary" IVsHierarchy. // As a heuristic here we'll ignore the output path if we already have another project tied to the IVsHierarchy. foreach (var projectId in Workspace.CurrentSolution.ProjectIds) { if (Workspace.GetHierarchy(projectId) == hierarchy) { _ignoreOutputPath = true; break; } } } var projectFactory = componentModel.GetService<VisualStudioProjectFactory>(); VisualStudioProject = threadingContext.JoinableTaskFactory.Run(() => projectFactory.CreateAndAddToWorkspaceAsync( projectSystemName, language, new VisualStudioProjectCreationInfo { // The workspace requires an assembly name so we can make compilations. We'll use // projectSystemName because they'll have a better one eventually. AssemblyName = projectSystemName, FilePath = projectFilePath, Hierarchy = hierarchy, ProjectGuid = GetProjectIDGuid(hierarchy), }, CancellationToken.None)); workspaceImpl.AddProjectRuleSetFileToInternalMaps( VisualStudioProject, () => VisualStudioProjectOptionsProcessor.EffectiveRuleSetFilePath); // Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace // by assigning the value of the project's root namespace to it. So various feature can choose to // use it for their own purpose. // In the future, we might consider officially exposing "default namespace" for VB project // (e.g. through a <defaultnamespace> msbuild property) VisualStudioProject.DefaultNamespace = GetRootNamespacePropertyValue(hierarchy); if (TryGetPropertyValue(hierarchy, AdditionalPropertyNames.MaxSupportedLangVersion, out var maxLangVer)) { VisualStudioProject.MaxLangVersion = maxLangVer; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzers, out var runAnayzers)) { VisualStudioProject.RunAnalyzers = runAnayzers; } if (TryGetBoolPropertyValue(hierarchy, AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis, out var runAnayzersDuringLiveAnalysis)) { VisualStudioProject.RunAnalyzersDuringLiveAnalysis = runAnayzersDuringLiveAnalysis; } Hierarchy = hierarchy; ConnectHierarchyEvents(); RefreshBinOutputPath(); workspaceImpl.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents(); _externalErrorReporter = new ProjectExternalErrorReporter(VisualStudioProject.Id, externalErrorReportingPrefix, language, workspaceImpl); _batchScopeCreator = componentModel.GetService<SolutionEventsBatchScopeCreator>(); _batchScopeCreator.StartTrackingProject(VisualStudioProject, Hierarchy); } public string AssemblyName => VisualStudioProject.AssemblyName; public string GetOutputFileName() => VisualStudioProject.CompilationOutputAssemblyFilePath; public virtual void Disconnect() { _batchScopeCreator.StopTrackingProject(VisualStudioProject); VisualStudioProjectOptionsProcessor?.Dispose(); ProjectCodeModel.OnProjectClosed(); VisualStudioProject.RemoveFromWorkspace(); // Unsubscribe IVsHierarchyEvents DisconnectHierarchyEvents(); } protected void AddFile( string filename, SourceCodeKind sourceCodeKind) { AssertIsForeground(); // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } ImmutableArray<string> folders = default; var itemid = Hierarchy.TryGetItemId(filename); if (itemid != VSConstants.VSITEMID_NIL) { folders = GetFolderNamesForDocument(itemid); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void AddFile( string filename, string linkMetadata, SourceCodeKind sourceCodeKind) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } var folders = ImmutableArray<string>.Empty; if (!string.IsNullOrEmpty(linkMetadata)) { var linkFolderPath = Path.GetDirectoryName(linkMetadata); folders = linkFolderPath.Split(PathSeparatorCharacters, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray(); } else if (!string.IsNullOrEmpty(VisualStudioProject.FilePath)) { var relativePath = PathUtilities.GetRelativePath(_projectDirectory, filename); var relativePathParts = relativePath.Split(PathSeparatorCharacters); folders = ImmutableArray.Create(relativePathParts, start: 0, length: relativePathParts.Length - 1); } VisualStudioProject.AddSourceFile(filename, sourceCodeKind, folders); } protected void RemoveFile(string filename) { // We have tests that assert that XOML files should not get added; this was similar // behavior to how ASP.NET projects would add .aspx files even though we ultimately ignored // them. XOML support is planned to go away for Dev16, but for now leave the logic there. if (filename.EndsWith(".xoml")) { return; } VisualStudioProject.RemoveSourceFile(filename); ProjectCodeModel.OnSourceFileRemoved(filename); } protected void RefreshBinOutputPath() { // These projects are created against the same hierarchy as the "main" project that // hosts the rest of the code; if we query the IVsHierarchy for the output path // we'll end up with duplicate output paths which can break P2P referencing. Since the output // path doesn't make sense for these, we'll ignore them. if (_ignoreOutputPath) { return; } if (Hierarchy is not IVsBuildPropertyStorage storage) { return; } if (ErrorHandler.Failed(storage.GetPropertyValue("OutDir", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var outputDirectory)) || ErrorHandler.Failed(storage.GetPropertyValue("TargetFileName", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetFileName))) { return; } if (targetFileName == null) { return; } // web app case if (!PathUtilities.IsAbsolute(outputDirectory)) { if (VisualStudioProject.FilePath == null) { return; } outputDirectory = FileUtilities.ResolveRelativePath(outputDirectory, Path.GetDirectoryName(VisualStudioProject.FilePath)); } if (outputDirectory == null) { return; } VisualStudioProject.OutputFilePath = FileUtilities.NormalizeAbsolutePath(Path.Combine(outputDirectory, targetFileName)); if (ErrorHandler.Succeeded(storage.GetPropertyValue("TargetRefPath", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out var targetRefPath)) && !string.IsNullOrEmpty(targetRefPath)) { VisualStudioProject.OutputRefFilePath = targetRefPath; } else { VisualStudioProject.OutputRefFilePath = null; } } private static Guid GetProjectIDGuid(IVsHierarchy hierarchy) { if (hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_ProjectIDGuid, out var guid)) { return guid; } return Guid.Empty; } /// <summary> /// Map of folder item IDs in the workspace to the string version of their path. /// </summary> /// <remarks>Using item IDs as a key like this in a long-lived way is considered unsupported by CPS and other /// IVsHierarchy providers, but this code (which is fairly old) still makes the assumptions anyways.</remarks> private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new(); private ImmutableArray<string> GetFolderNamesForDocument(uint documentItemID) { AssertIsForeground(); if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { return GetFolderNamesForFolder(parentID); } } return ImmutableArray<string>.Empty; } private ImmutableArray<string> GetFolderNamesForFolder(uint folderItemID) { AssertIsForeground(); using var pooledObject = SharedPools.Default<List<string>>().GetPooledObject(); var newFolderNames = pooledObject.Object; if (!_folderNameMap.TryGetValue(folderItemID, out var folderNames)) { ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); folderNames = newFolderNames.ToImmutableArray(); _folderNameMap.Add(folderItemID, folderNames); } else { // verify names, and change map if we get a different set. // this is necessary because we only get document adds/removes from the project system // when a document name or folder name changes. ComputeFolderNames(folderItemID, newFolderNames, Hierarchy); if (!Enumerable.SequenceEqual(folderNames, newFolderNames)) { folderNames = newFolderNames.ToImmutableArray(); _folderNameMap[folderItemID] = folderNames; } } return folderNames; } // Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds. // Technically it should be a uint. However, there's no enforcement of this, and marshalling // from native to managed can end up resulting in boxed ints instead. Handle both here so // we're resilient to however the IVsHierarchy was actually implemented. private static uint UnboxVSItemId(object id) => id is uint ? (uint)id : unchecked((uint)(int)id); private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy) { if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out var nameObj) == VSConstants.S_OK) { // For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>) // as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder // is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders. // Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to // worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for // VSITEMID.Root below already takes care of that. var name = (string)nameObj; if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase)) { names.Insert(0, name); } } if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out var parentObj) == VSConstants.S_OK) { var parentID = UnboxVSItemId(parentObj); if (parentID is not ((uint)VSConstants.VSITEMID.Nil) and not ((uint)VSConstants.VSITEMID.Root)) { ComputeFolderNames(parentID, names, hierarchy); } } } /// <summary> /// Get the value of "rootnamespace" property of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// This property has different meaning between C# and VB, each project type can decide how to interpret the value. /// </remarks>> private static string GetRootNamespacePropertyValue(IVsHierarchy hierarchy) { // While both csproj and vbproj might define <rootnamespace> property in the project file, // they are very different things. // // In C#, it's called default namespace (even though we got the value from rootnamespace property), // and it doesn't affect the semantic of the code in anyway, just something used by VS. // For example, when you create a new class, the namespace for the new class is based on it. // Therefore, we can't get this info from compiler. // // However, in VB, it's actually called root namespace, and that info is part of the VB compilation // (parsed from arguments), because VB compiler needs it to determine the root of all the namespace // declared in the compilation. // // Unfortunately, although being different concepts, default namespace and root namespace are almost // used interchangeably in VS. For example, (1) the value is define in "rootnamespace" property in project // files and, (2) the property name we use to call into hierarchy below to retrieve the value is // called "DefaultNamespace". if (hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_DefaultNamespace, out string value)) { return value; } return null; } private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, out string propertyValue) { if (hierarchy is not IVsBuildPropertyStorage storage) { propertyValue = null; return false; } return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue)); } private static bool TryGetBoolPropertyValue(IVsHierarchy hierarchy, string propertyName, out bool? propertyValue) { if (!TryGetPropertyValue(hierarchy, propertyName, out var stringPropertyValue)) { propertyValue = null; return false; } propertyValue = bool.TryParse(stringPropertyValue, out var parsedBoolValue) ? parsedBoolValue : (bool?)null; return true; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Core/CodeAnalysisTest/CommonCommandLineParserTests.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.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonCommandLineParserTests : TestBase { private void VerifyCommandLineSplitter(string commandLine, string[] expected, bool removeHashComments = false) { var actual = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments).ToArray(); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < actual.Length; ++i) { Assert.Equal(expected[i], actual[i]); } } private RuleSet ParseRuleSet(string source, params string[] otherSources) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); for (int i = 1; i <= otherSources.Length; i++) { var newFile = dir.CreateFile("file" + i + ".ruleset"); newFile.WriteAllText(otherSources[i - 1]); } if (otherSources.Length != 0) { return RuleSet.LoadEffectiveRuleSetFromFile(file.Path); } return RuleSetProcessor.LoadFromFile(file.Path); } private void VerifyRuleSetError(string source, Func<string> messageFormatter, bool locSpecific = true, params string[] otherSources) { CultureInfo saveUICulture = Thread.CurrentThread.CurrentUICulture; if (locSpecific) { var preferred = EnsureEnglishUICulture.PreferredOrNull; if (preferred == null) { locSpecific = false; } else { Thread.CurrentThread.CurrentUICulture = preferred; } } try { ParseRuleSet(source, otherSources); } catch (Exception e) { Assert.Equal(messageFormatter(), e.Message); return; } finally { if (locSpecific) { Thread.CurrentThread.CurrentUICulture = saveUICulture; } } Assert.True(false, "Didn't return an error"); } [Fact] public void TestCommandLineSplitter() { VerifyCommandLineSplitter("", new string[0]); VerifyCommandLineSplitter(" \t ", new string[0]); VerifyCommandLineSplitter(" abc\tdef baz quuz ", new[] { "abc", "def", "baz", "quuz" }); VerifyCommandLineSplitter(@" ""abc def"" fi""ddle dee de""e ""hi there ""dude he""llo there"" ", new string[] { @"abc def", @"fi""ddle dee de""e", @"""hi there ""dude", @"he""llo there""" }); VerifyCommandLineSplitter(@" ""abc def \"" baz quuz"" ""\""straw berry"" fi\""zz \""buzz fizzbuzz", new string[] { @"abc def \"" baz quuz", @"\""straw berry", @"fi\""zz", @"\""buzz", @"fizzbuzz" }); VerifyCommandLineSplitter(@" \\""abc def"" \\\""abc def"" ", new string[] { @"\\""abc def""", @"\\\""abc", @"def"" " }); VerifyCommandLineSplitter(@" \\\\""abc def"" \\\\\""abc def"" ", new string[] { @"\\\\""abc def""", @"\\\\\""abc", @"def"" " }); VerifyCommandLineSplitter(@" \\\\""abc def"" \\\\\""abc def"" q a r ", new string[] { @"\\\\""abc def""", @"\\\\\""abc", @"def"" q a r " }); VerifyCommandLineSplitter(@"abc #Comment ignored", new string[] { @"abc" }, removeHashComments: true); VerifyCommandLineSplitter(@"""goo bar"";""baz"" ""tree""", new string[] { @"""goo bar"";""baz""", "tree" }); VerifyCommandLineSplitter(@"/reference:""a, b"" ""test""", new string[] { @"/reference:""a, b""", "test" }); VerifyCommandLineSplitter(@"fo""o ba""r", new string[] { @"fo""o ba""r" }); } [Fact] public void TestRuleSetParsingDuplicateRule() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1012"" Action=""Warning"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet>"; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetHasDuplicateRules, "CA1012", "Error", "Warn")); } [Fact] public void TestRuleSetParsingDuplicateRule2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet>"; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetHasDuplicateRules, "CA1012", "Error", "Warn"), locSpecific: false); } [Fact] public void TestRuleSetParsingDuplicateRule3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet>"; var ruleSet = ParseRuleSet(source); Assert.Equal(expected: ReportDiagnostic.Error, actual: ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetParsingDuplicateRuleSet() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> <RuleSet Name=""Ruleset2"" Description=""Test""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => "There are multiple root elements. Line 8, position 2."); } [Fact] public void TestRuleSetParsingIncludeAll1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetParsingIncludeAll2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetParsingWithIncludeOfSameFile() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""a.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, new string[] { "" }); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(1, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingWithMutualIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""a.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(2, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingWithSiblingIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(3, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingIncludeAll3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", "Default")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rule", "Id")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rule", "Action")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rules", "AnalyzerId")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute4() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rules", "RuleNamespace")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute5() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "RuleSet", "ToolsVersion")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute6() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "RuleSet", "Name")); } [Fact] public void TestRuleSetParsingRules() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> <Rule Id=""CA1015"" Action=""Info"" /> <Rule Id=""CA1016"" Action=""Hidden"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA1014"]); Assert.Contains("CA1015", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Info, ruleSet.SpecificDiagnosticOptions["CA1015"]); Assert.Contains("CA1016", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Hidden, ruleSet.SpecificDiagnosticOptions["CA1016"]); } [Fact] public void TestRuleSetParsingRules2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Default"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", "Default")); } [Fact] public void TestRuleSetInclude() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""goo.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.True(ruleSet.Includes.Count() == 1); Assert.Equal(ReportDiagnostic.Default, ruleSet.Includes.First().Action); Assert.Equal("goo.ruleset", ruleSet.Includes.First().IncludePath); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(1184500, "DevDiv 1184500")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact] public void TestRuleSetInclude1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""goo.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var ruleSet = RuleSet.LoadEffectiveRuleSetFromFile(file.Path); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetInclude2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Hidden"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Hidden, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Info"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Info, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeRecursiveIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1014"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1014"]); } [Fact] public void TestRuleSetIncludeSpecificStrict1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); // CA1012's value in source wins. Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetIncludeSpecificStrict2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); // CA1012's value in source still wins. Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetIncludeSpecificStrict3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); // CA1013's value in source2 wins. Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeEffectiveAction() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""None"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.DoesNotContain("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); } [Fact] public void TestRuleSetIncludeEffectiveAction1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionGlobal1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionGlobal2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionSpecific1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeEffectiveActionSpecific2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestAllCombinations() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>"; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1000"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1001"]); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA2100"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2104"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2105"]); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2111"]); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2119"]); } [Fact] public void TestRuleSetIncludeError() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Default"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var newFile = dir.CreateFile("file1.ruleset"); newFile.WriteAllText(source1); using (new EnsureEnglishUICulture()) { try { RuleSet.LoadEffectiveRuleSetFromFile(file.Path); Assert.True(false, "Didn't throw an exception"); } catch (InvalidRuleSetException e) { Assert.Contains(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, newFile.Path, string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", "Default")), e.Message, StringComparison.Ordinal); } } } [Fact] public void GetEffectiveIncludes_NoIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 1, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); } [Fact] public void GetEffectiveIncludes_OneLevel() { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string includeSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(ruleSetSource); var include = dir.CreateFile("file1.ruleset"); include.WriteAllText(includeSource); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 2, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); Assert.Equal(expected: include.Path, actual: includePaths[1]); } [Fact] public void GetEffectiveIncludes_TwoLevels() { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string includeSource1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; string includeSource2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(ruleSetSource); var include1 = dir.CreateFile("file1.ruleset"); include1.WriteAllText(includeSource1); var include2 = dir.CreateFile("file2.ruleset"); include2.WriteAllText(includeSource2); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 3, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); Assert.Equal(expected: include1.Path, actual: includePaths[1]); Assert.Equal(expected: include2.Path, actual: includePaths[2]); } private string[] ParseSeparatedStrings(string arg, char[] separators, bool removeEmptyEntries = true) { var builder = ArrayBuilder<ReadOnlyMemory<char>>.GetInstance(); CommandLineParser.ParseSeparatedStrings(arg.AsMemory(), separators, removeEmptyEntries, builder); return builder.Select(x => x.ToString()).ToArray(); } [Fact] public void ParseSeparatedStrings_ExcludeSeparatorChar() { Assert.Equal( ParseSeparatedStrings(@"a,b", new[] { ',' }), new[] { "a", "b" }); Assert.Equal( ParseSeparatedStrings(@"a,,b", new[] { ',' }), new[] { "a", "b" }); } /// <summary> /// This function considers quotes when splitting out the strings. Ensure they are properly /// preserved in the final string. /// </summary> [Fact] public void ParseSeparatedStrings_IncludeQuotes() { Assert.Equal( ParseSeparatedStrings(@"""a"",b", new[] { ',' }), new[] { @"""a""", "b" }); Assert.Equal( ParseSeparatedStrings(@"""a,b""", new[] { ',' }), new[] { @"""a,b""" }); Assert.Equal( ParseSeparatedStrings(@"""a"",""b", new[] { ',' }), new[] { @"""a""", @"""b" }); } /// <summary> /// This function should always preserve the slashes as they exist in the original command /// line. The only serve to decide whether quotes should count as grouping constructors /// or not. /// </summary> [Fact] public void SplitCommandLineIntoArguments_Slashes() { Assert.Equal( new[] { @"\\test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\test", removeHashComments: false)); // Even though there are an even number of slashes here that doesn't factor into the // output. It just means the quote is a grouping construct. Assert.Equal( new[] { @"\\""test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\""test", removeHashComments: false)); Assert.Equal( new[] { @"\\\""test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\\""test", removeHashComments: false)); Assert.Equal( new[] { @"\\\test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\\test", removeHashComments: false)); Assert.Equal( new[] { @"\\\\\test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\\\\test", removeHashComments: false)); } /// <summary> /// Quotes are used as grouping constructs unless they are escaped by an odd number of slashes. /// </summary> [Fact] public void SplitCommandLineIntoArguments_Quotes() { Assert.Equal( new[] { @"a", @"b" }, CommandLineParser.SplitCommandLineIntoArguments(@"a b", removeHashComments: false)); Assert.Equal( new[] { @"a b" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a b""", removeHashComments: false)); Assert.Equal( new[] { @"a ", @"b""" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a "" b""", removeHashComments: false)); // In this case the inner quote is escaped so it doesn't count as a real quote. Strings which have // outer quotes with no real inner quotes have the outer quotes removed. Assert.Equal( new[] { @"a \"" b" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a \"" b""", removeHashComments: false)); Assert.Equal( new[] { @"\a", @"b" }, CommandLineParser.SplitCommandLineIntoArguments(@"\a b", removeHashComments: false)); // Escaped quote is not a grouping construct Assert.Equal( new[] { @"\""a", @"b\""" }, CommandLineParser.SplitCommandLineIntoArguments(@"\""a b\""", removeHashComments: false)); // Unescaped quote is a grouping construct. Assert.Equal( new[] { @"\\""a b\\""" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\""a b\\""", removeHashComments: false)); Assert.Equal( new[] { @"""a""m""b""" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a""m""b""", removeHashComments: false)); } /// <summary> /// Test all of the cases around slashes in the RemoveQuotes function. /// </summary> /// <remarks> /// It's important to remember this is testing slash behavior on the strings as they /// are passed to RemoveQuotes, not as they are passed to the command line. Command /// line arguments have already gone through an initial round of processing. So a /// string that appears here as "\\test.cs" actually came through the command line /// as \"\\test.cs\". /// </remarks> [Fact] public void RemoveQuotesAndSlashes() { Assert.Equal(@"\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\test.cs")); Assert.Equal(@"\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"""\\test.cs""")); Assert.Equal(@"\\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\\test.cs")); Assert.Equal(@"\\\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\\\test.cs")); Assert.Equal(@"\\test\a\b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\test\a\b.cs")); Assert.Equal(@"\\\\test\\a\\b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\\\test\\a\\b.cs")); Assert.Equal(@"a""b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"a\""b.cs")); Assert.Equal(@"a"" mid ""b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"a\"" mid \""b.cs")); Assert.Equal(@"a mid b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"a"" mid ""b.cs")); Assert.Equal(@"a.cs", CommandLineParser.RemoveQuotesAndSlashes(@"""a.cs""")); Assert.Equal(@"C:""My Folder\MyBinary.xml", CommandLineParser.RemoveQuotesAndSlashes(@"C:\""My Folder""\MyBinary.xml")); } /// <summary> /// Verify that for the standard cases we do not allocate new memory but instead /// return a <see cref="ReadOnlyMemory{T}"/> to the existing string /// </summary> [Fact] public void RemoveQuotesAndSlashes_NoAllocation() { assertSame(@"c:\test.cs"); assertSame(@"""c:\test.cs"""); assertSame(@"""c:\\\\\\\\\test.cs"""); assertSame(@"""c:\\\\\\\\\test.cs"""); void assertSame(string arg) { var memory = CommandLineParser.RemoveQuotesAndSlashesEx(arg.AsMemory()); Assert.True(MemoryMarshal.TryGetString(memory, out var memoryString, out _, out _)); Assert.Same(arg, memoryString); } } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonCommandLineParserTests : TestBase { private void VerifyCommandLineSplitter(string commandLine, string[] expected, bool removeHashComments = false) { var actual = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments).ToArray(); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < actual.Length; ++i) { Assert.Equal(expected[i], actual[i]); } } private RuleSet ParseRuleSet(string source, params string[] otherSources) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); for (int i = 1; i <= otherSources.Length; i++) { var newFile = dir.CreateFile("file" + i + ".ruleset"); newFile.WriteAllText(otherSources[i - 1]); } if (otherSources.Length != 0) { return RuleSet.LoadEffectiveRuleSetFromFile(file.Path); } return RuleSetProcessor.LoadFromFile(file.Path); } private void VerifyRuleSetError(string source, Func<string> messageFormatter, bool locSpecific = true, params string[] otherSources) { CultureInfo saveUICulture = Thread.CurrentThread.CurrentUICulture; if (locSpecific) { var preferred = EnsureEnglishUICulture.PreferredOrNull; if (preferred == null) { locSpecific = false; } else { Thread.CurrentThread.CurrentUICulture = preferred; } } try { ParseRuleSet(source, otherSources); } catch (Exception e) { Assert.Equal(messageFormatter(), e.Message); return; } finally { if (locSpecific) { Thread.CurrentThread.CurrentUICulture = saveUICulture; } } Assert.True(false, "Didn't return an error"); } [Fact] public void TestCommandLineSplitter() { VerifyCommandLineSplitter("", new string[0]); VerifyCommandLineSplitter(" \t ", new string[0]); VerifyCommandLineSplitter(" abc\tdef baz quuz ", new[] { "abc", "def", "baz", "quuz" }); VerifyCommandLineSplitter(@" ""abc def"" fi""ddle dee de""e ""hi there ""dude he""llo there"" ", new string[] { @"abc def", @"fi""ddle dee de""e", @"""hi there ""dude", @"he""llo there""" }); VerifyCommandLineSplitter(@" ""abc def \"" baz quuz"" ""\""straw berry"" fi\""zz \""buzz fizzbuzz", new string[] { @"abc def \"" baz quuz", @"\""straw berry", @"fi\""zz", @"\""buzz", @"fizzbuzz" }); VerifyCommandLineSplitter(@" \\""abc def"" \\\""abc def"" ", new string[] { @"\\""abc def""", @"\\\""abc", @"def"" " }); VerifyCommandLineSplitter(@" \\\\""abc def"" \\\\\""abc def"" ", new string[] { @"\\\\""abc def""", @"\\\\\""abc", @"def"" " }); VerifyCommandLineSplitter(@" \\\\""abc def"" \\\\\""abc def"" q a r ", new string[] { @"\\\\""abc def""", @"\\\\\""abc", @"def"" q a r " }); VerifyCommandLineSplitter(@"abc #Comment ignored", new string[] { @"abc" }, removeHashComments: true); VerifyCommandLineSplitter(@"""goo bar"";""baz"" ""tree""", new string[] { @"""goo bar"";""baz""", "tree" }); VerifyCommandLineSplitter(@"/reference:""a, b"" ""test""", new string[] { @"/reference:""a, b""", "test" }); VerifyCommandLineSplitter(@"fo""o ba""r", new string[] { @"fo""o ba""r" }); } [Fact] public void TestRuleSetParsingDuplicateRule() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1012"" Action=""Warning"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet>"; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetHasDuplicateRules, "CA1012", "Error", "Warn")); } [Fact] public void TestRuleSetParsingDuplicateRule2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet>"; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetHasDuplicateRules, "CA1012", "Error", "Warn"), locSpecific: false); } [Fact] public void TestRuleSetParsingDuplicateRule3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet>"; var ruleSet = ParseRuleSet(source); Assert.Equal(expected: ReportDiagnostic.Error, actual: ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetParsingDuplicateRuleSet() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> <RuleSet Name=""Ruleset2"" Description=""Test""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => "There are multiple root elements. Line 8, position 2."); } [Fact] public void TestRuleSetParsingIncludeAll1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetParsingIncludeAll2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetParsingWithIncludeOfSameFile() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""a.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, new string[] { "" }); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(1, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingWithMutualIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""a.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(2, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingWithSiblingIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Equal(3, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count()); } [Fact] public void TestRuleSetParsingIncludeAll3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", "Default")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rule", "Id")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rule", "Action")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rules", "AnalyzerId")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute4() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "Rules", "RuleNamespace")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute5() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "RuleSet", "ToolsVersion")); } [Fact] public void TestRuleSetParsingRulesMissingAttribute6() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetMissingAttribute, "RuleSet", "Name")); } [Fact] public void TestRuleSetParsingRules() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> <Rule Id=""CA1015"" Action=""Info"" /> <Rule Id=""CA1016"" Action=""Hidden"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA1014"]); Assert.Contains("CA1015", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Info, ruleSet.SpecificDiagnosticOptions["CA1015"]); Assert.Contains("CA1016", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Hidden, ruleSet.SpecificDiagnosticOptions["CA1016"]); } [Fact] public void TestRuleSetParsingRules2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Default"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", "Default")); } [Fact] public void TestRuleSetInclude() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""goo.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source); Assert.True(ruleSet.Includes.Count() == 1); Assert.Equal(ReportDiagnostic.Default, ruleSet.Includes.First().Action); Assert.Equal("goo.ruleset", ruleSet.Includes.First().IncludePath); } #pragma warning disable CA2243 // Attribute string literals should parse correctly [WorkItem(1184500, "DevDiv 1184500")] #pragma warning restore CA2243 // Attribute string literals should parse correctly [Fact] public void TestRuleSetInclude1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""goo.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var ruleSet = RuleSet.LoadEffectiveRuleSetFromFile(file.Path); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetInclude2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Hidden"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Hidden, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Info"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Info, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeGlobalStrict3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeRecursiveIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1014"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1014"]); } [Fact] public void TestRuleSetIncludeSpecificStrict1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); // CA1012's value in source wins. Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetIncludeSpecificStrict2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); // CA1012's value in source still wins. Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); } [Fact] public void TestRuleSetIncludeSpecificStrict3() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Default"" /> <Include Path=""file2.ruleset"" Action=""Default"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); // CA1013's value in source2 wins. Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeEffectiveAction() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""None"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.DoesNotContain("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); } [Fact] public void TestRuleSetIncludeEffectiveAction1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionGlobal1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionGlobal2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <IncludeAll Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption); } [Fact] public void TestRuleSetIncludeEffectiveActionSpecific1() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""None"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestRuleSetIncludeEffectiveActionSpecific2() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSet = ParseRuleSet(source, source1); Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]); Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]); } [Fact] public void TestAllCombinations() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>"; var ruleSet = ParseRuleSet(source, source1, source2); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1000"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1001"]); Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA2100"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2104"]); Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2105"]); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2111"]); Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2119"]); } [Fact] public void TestRuleSetIncludeError() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1013"" Action=""Default"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var newFile = dir.CreateFile("file1.ruleset"); newFile.WriteAllText(source1); using (new EnsureEnglishUICulture()) { try { RuleSet.LoadEffectiveRuleSetFromFile(file.Path); Assert.True(false, "Didn't throw an exception"); } catch (InvalidRuleSetException e) { Assert.Contains(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, newFile.Path, string.Format(CodeAnalysisResources.RuleSetBadAttributeValue, "Action", "Default")), e.Message, StringComparison.Ordinal); } } } [Fact] public void GetEffectiveIncludes_NoIncludes() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" > <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 1, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); } [Fact] public void GetEffectiveIncludes_OneLevel() { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string includeSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(ruleSetSource); var include = dir.CreateFile("file1.ruleset"); include.WriteAllText(includeSource); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 2, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); Assert.Equal(expected: include.Path, actual: includePaths[1]); } [Fact] public void GetEffectiveIncludes_TwoLevels() { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file1.ruleset"" Action=""Error"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1000"" Action=""Warning"" /> <Rule Id=""CA1001"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""None"" /> </Rules> </RuleSet> "; string includeSource1 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0""> <Include Path=""file2.ruleset"" Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> </Rules> </RuleSet> "; string includeSource2 = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA2100"" Action=""Warning"" /> <Rule Id=""CA2111"" Action=""Warning"" /> <Rule Id=""CA2119"" Action=""None"" /> <Rule Id=""CA2104"" Action=""Error"" /> <Rule Id=""CA2105"" Action=""Warning"" /> </Rules> </RuleSet>"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(ruleSetSource); var include1 = dir.CreateFile("file1.ruleset"); include1.WriteAllText(includeSource1); var include2 = dir.CreateFile("file2.ruleset"); include2.WriteAllText(includeSource2); var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path); Assert.Equal(expected: 3, actual: includePaths.Length); Assert.Equal(expected: file.Path, actual: includePaths[0]); Assert.Equal(expected: include1.Path, actual: includePaths[1]); Assert.Equal(expected: include2.Path, actual: includePaths[2]); } private string[] ParseSeparatedStrings(string arg, char[] separators, bool removeEmptyEntries = true) { var builder = ArrayBuilder<ReadOnlyMemory<char>>.GetInstance(); CommandLineParser.ParseSeparatedStrings(arg.AsMemory(), separators, removeEmptyEntries, builder); return builder.Select(x => x.ToString()).ToArray(); } [Fact] public void ParseSeparatedStrings_ExcludeSeparatorChar() { Assert.Equal( ParseSeparatedStrings(@"a,b", new[] { ',' }), new[] { "a", "b" }); Assert.Equal( ParseSeparatedStrings(@"a,,b", new[] { ',' }), new[] { "a", "b" }); } /// <summary> /// This function considers quotes when splitting out the strings. Ensure they are properly /// preserved in the final string. /// </summary> [Fact] public void ParseSeparatedStrings_IncludeQuotes() { Assert.Equal( ParseSeparatedStrings(@"""a"",b", new[] { ',' }), new[] { @"""a""", "b" }); Assert.Equal( ParseSeparatedStrings(@"""a,b""", new[] { ',' }), new[] { @"""a,b""" }); Assert.Equal( ParseSeparatedStrings(@"""a"",""b", new[] { ',' }), new[] { @"""a""", @"""b" }); } /// <summary> /// This function should always preserve the slashes as they exist in the original command /// line. The only serve to decide whether quotes should count as grouping constructors /// or not. /// </summary> [Fact] public void SplitCommandLineIntoArguments_Slashes() { Assert.Equal( new[] { @"\\test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\test", removeHashComments: false)); // Even though there are an even number of slashes here that doesn't factor into the // output. It just means the quote is a grouping construct. Assert.Equal( new[] { @"\\""test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\""test", removeHashComments: false)); Assert.Equal( new[] { @"\\\""test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\\""test", removeHashComments: false)); Assert.Equal( new[] { @"\\\test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\\test", removeHashComments: false)); Assert.Equal( new[] { @"\\\\\test" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\\\\test", removeHashComments: false)); } /// <summary> /// Quotes are used as grouping constructs unless they are escaped by an odd number of slashes. /// </summary> [Fact] public void SplitCommandLineIntoArguments_Quotes() { Assert.Equal( new[] { @"a", @"b" }, CommandLineParser.SplitCommandLineIntoArguments(@"a b", removeHashComments: false)); Assert.Equal( new[] { @"a b" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a b""", removeHashComments: false)); Assert.Equal( new[] { @"a ", @"b""" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a "" b""", removeHashComments: false)); // In this case the inner quote is escaped so it doesn't count as a real quote. Strings which have // outer quotes with no real inner quotes have the outer quotes removed. Assert.Equal( new[] { @"a \"" b" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a \"" b""", removeHashComments: false)); Assert.Equal( new[] { @"\a", @"b" }, CommandLineParser.SplitCommandLineIntoArguments(@"\a b", removeHashComments: false)); // Escaped quote is not a grouping construct Assert.Equal( new[] { @"\""a", @"b\""" }, CommandLineParser.SplitCommandLineIntoArguments(@"\""a b\""", removeHashComments: false)); // Unescaped quote is a grouping construct. Assert.Equal( new[] { @"\\""a b\\""" }, CommandLineParser.SplitCommandLineIntoArguments(@"\\""a b\\""", removeHashComments: false)); Assert.Equal( new[] { @"""a""m""b""" }, CommandLineParser.SplitCommandLineIntoArguments(@"""a""m""b""", removeHashComments: false)); } /// <summary> /// Test all of the cases around slashes in the RemoveQuotes function. /// </summary> /// <remarks> /// It's important to remember this is testing slash behavior on the strings as they /// are passed to RemoveQuotes, not as they are passed to the command line. Command /// line arguments have already gone through an initial round of processing. So a /// string that appears here as "\\test.cs" actually came through the command line /// as \"\\test.cs\". /// </remarks> [Fact] public void RemoveQuotesAndSlashes() { Assert.Equal(@"\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\test.cs")); Assert.Equal(@"\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"""\\test.cs""")); Assert.Equal(@"\\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\\test.cs")); Assert.Equal(@"\\\\test.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\\\test.cs")); Assert.Equal(@"\\test\a\b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\test\a\b.cs")); Assert.Equal(@"\\\\test\\a\\b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"\\\\test\\a\\b.cs")); Assert.Equal(@"a""b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"a\""b.cs")); Assert.Equal(@"a"" mid ""b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"a\"" mid \""b.cs")); Assert.Equal(@"a mid b.cs", CommandLineParser.RemoveQuotesAndSlashes(@"a"" mid ""b.cs")); Assert.Equal(@"a.cs", CommandLineParser.RemoveQuotesAndSlashes(@"""a.cs""")); Assert.Equal(@"C:""My Folder\MyBinary.xml", CommandLineParser.RemoveQuotesAndSlashes(@"C:\""My Folder""\MyBinary.xml")); } /// <summary> /// Verify that for the standard cases we do not allocate new memory but instead /// return a <see cref="ReadOnlyMemory{T}"/> to the existing string /// </summary> [Fact] public void RemoveQuotesAndSlashes_NoAllocation() { assertSame(@"c:\test.cs"); assertSame(@"""c:\test.cs"""); assertSame(@"""c:\\\\\\\\\test.cs"""); assertSame(@"""c:\\\\\\\\\test.cs"""); void assertSame(string arg) { var memory = CommandLineParser.RemoveQuotesAndSlashesEx(arg.AsMemory()); Assert.True(MemoryMarshal.TryGetString(memory, out var memoryString, out _, out _)); Assert.Same(arg, memoryString); } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActionSet.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.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to SuggestedActionSet, but in a location that can be used /// by both local Roslyn and LSP. /// </summary> internal class UnifiedSuggestedActionSet { public string? CategoryName { get; } public IEnumerable<IUnifiedSuggestedAction> Actions { get; } public object? Title { get; } public UnifiedSuggestedActionSetPriority Priority { get; } public TextSpan? ApplicableToSpan { get; } public UnifiedSuggestedActionSet( string? categoryName, IEnumerable<IUnifiedSuggestedAction> actions, object? title, UnifiedSuggestedActionSetPriority priority, TextSpan? applicableToSpan) { CategoryName = categoryName; Actions = actions; Title = title; Priority = priority; ApplicableToSpan = applicableToSpan; } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to SuggestedActionSet, but in a location that can be used /// by both local Roslyn and LSP. /// </summary> internal class UnifiedSuggestedActionSet { public string? CategoryName { get; } public IEnumerable<IUnifiedSuggestedAction> Actions { get; } public object? Title { get; } public UnifiedSuggestedActionSetPriority Priority { get; } public TextSpan? ApplicableToSpan { get; } public UnifiedSuggestedActionSet( string? categoryName, IEnumerable<IUnifiedSuggestedAction> actions, object? title, UnifiedSuggestedActionSetPriority priority, TextSpan? applicableToSpan) { CategoryName = categoryName; Actions = actions; Title = title; Priority = priority; ApplicableToSpan = applicableToSpan; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/CSharp/Impl/EditorConfigSettings/BinaryOperatorSpacingOptionsViewModelFactory.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.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings { [Export(typeof(IEnumSettingViewModelFactory)), Shared] internal class BinaryOperatorSpacingOptionsViewModelFactory : IEnumSettingViewModelFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BinaryOperatorSpacingOptionsViewModelFactory() { } public IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting) { return new BinaryOperatorSpacingOptionsViewModel(setting); } public bool IsSupported(OptionKey2 key) => key.Option.Type == typeof(BinaryOperatorSpacingOptions); } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings { [Export(typeof(IEnumSettingViewModelFactory)), Shared] internal class BinaryOperatorSpacingOptionsViewModelFactory : IEnumSettingViewModelFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BinaryOperatorSpacingOptionsViewModelFactory() { } public IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting) { return new BinaryOperatorSpacingOptionsViewModel(setting); } public bool IsSupported(OptionKey2 key) => key.Option.Type == typeof(BinaryOperatorSpacingOptions); } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/CSharp/Portable/Completion/CompletionProviders/ExplicitInterfaceTypeCompletionProvider.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 System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExplicitInterfaceTypeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ExplicitInterfaceMemberCompletionProvider))] [Shared] internal partial class ExplicitInterfaceTypeCompletionProvider : AbstractSymbolCompletionProvider<CSharpSyntaxContext> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExplicitInterfaceTypeCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) => CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, insertedCharacterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var completionCount = context.Items.Count; await base.ProvideCompletionsAsync(context).ConfigureAwait(false); if (completionCount < context.Items.Count) { // If we added any items, then add a suggestion mode item as this is a location // where a member name could be written, and we should not interfere with that. context.SuggestionModeItem = CreateSuggestionModeItem( CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_member_declaration); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } protected override Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeNode = targetToken.Parent as TypeSyntax; while (typeNode != null) { if (typeNode.Parent is TypeSyntax parentType && parentType.Span.End < position) { typeNode = parentType; } else { break; } } if (typeNode == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeDeclaration = typeNode.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); var semanticModel = context.SemanticModel; var namedType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); Contract.ThrowIfNull(namedType); using var _ = PooledHashSet<ISymbol>.GetInstance(out var interfaceSet); foreach (var directInterface in namedType.Interfaces) { interfaceSet.Add(directInterface); interfaceSet.AddRange(directInterface.AllInterfaces); } return Task.FromResult(interfaceSet.SelectAsArray(t => (t, preselect: false))); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) { if (tokenBeforeType.Kind() == SyntaxKind.AsyncKeyword) { tokenBeforeType = tokenBeforeType.GetPreviousToken(); } if (tokenBeforeType.Kind() == SyntaxKind.OpenBraceToken) { // Show us after the open brace for a class/struct/interface return IsClassOrStructOrInterfaceOrRecord(tokenBeforeType.GetRequiredParent()); } if (tokenBeforeType.Kind() is SyntaxKind.CloseBraceToken or SyntaxKind.SemicolonToken) { // Check that we're after a class/struct/interface member. var memberDeclaration = tokenBeforeType.GetAncestor<MemberDeclarationSyntax>(); return memberDeclaration?.GetLastToken() == tokenBeforeType && IsClassOrStructOrInterfaceOrRecord(memberDeclaration.GetRequiredParent()); } return false; } private static bool IsClassOrStructOrInterfaceOrRecord(SyntaxNode node) => node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration; } }
// Licensed to the .NET Foundation under one or more 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 System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExplicitInterfaceTypeCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ExplicitInterfaceMemberCompletionProvider))] [Shared] internal partial class ExplicitInterfaceTypeCompletionProvider : AbstractSymbolCompletionProvider<CSharpSyntaxContext> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExplicitInterfaceTypeCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) => CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, insertedCharacterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var completionCount = context.Items.Count; await base.ProvideCompletionsAsync(context).ConfigureAwait(false); if (completionCount < context.Items.Count) { // If we added any items, then add a suggestion mode item as this is a location // where a member name could be written, and we should not interfere with that. context.SuggestionModeItem = CreateSuggestionModeItem( CSharpFeaturesResources.member_name, CSharpFeaturesResources.Autoselect_disabled_due_to_member_declaration); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } protected override Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync( CompletionContext? completionContext, CSharpSyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken) { var targetToken = context.TargetToken; // Don't want to offer this after "async" (even though the compiler may parse that as a type). if (SyntaxFacts.GetContextualKeywordKind(targetToken.ValueText) == SyntaxKind.AsyncKeyword) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeNode = targetToken.Parent as TypeSyntax; while (typeNode != null) { if (typeNode.Parent is TypeSyntax parentType && parentType.Span.End < position) { typeNode = parentType; } else { break; } } if (typeNode == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // We weren't after something that looked like a type. var tokenBeforeType = typeNode.GetFirstToken().GetPreviousToken(); if (!IsPreviousTokenValid(tokenBeforeType)) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); var typeDeclaration = typeNode.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration == null) return SpecializedTasks.EmptyImmutableArray<(ISymbol symbol, bool preselect)>(); // Looks syntactically good. See what interfaces our containing class/struct/interface has Debug.Assert(IsClassOrStructOrInterfaceOrRecord(typeDeclaration)); var semanticModel = context.SemanticModel; var namedType = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); Contract.ThrowIfNull(namedType); using var _ = PooledHashSet<ISymbol>.GetInstance(out var interfaceSet); foreach (var directInterface in namedType.Interfaces) { interfaceSet.Add(directInterface); interfaceSet.AddRange(directInterface.AllInterfaces); } return Task.FromResult(interfaceSet.SelectAsArray(t => (t, preselect: false))); } private static bool IsPreviousTokenValid(SyntaxToken tokenBeforeType) { if (tokenBeforeType.Kind() == SyntaxKind.AsyncKeyword) { tokenBeforeType = tokenBeforeType.GetPreviousToken(); } if (tokenBeforeType.Kind() == SyntaxKind.OpenBraceToken) { // Show us after the open brace for a class/struct/interface return IsClassOrStructOrInterfaceOrRecord(tokenBeforeType.GetRequiredParent()); } if (tokenBeforeType.Kind() is SyntaxKind.CloseBraceToken or SyntaxKind.SemicolonToken) { // Check that we're after a class/struct/interface member. var memberDeclaration = tokenBeforeType.GetAncestor<MemberDeclarationSyntax>(); return memberDeclaration?.GetLastToken() == tokenBeforeType && IsClassOrStructOrInterfaceOrRecord(memberDeclaration.GetRequiredParent()); } return false; } private static bool IsClassOrStructOrInterfaceOrRecord(SyntaxNode node) => node.Kind() is SyntaxKind.ClassDeclaration or SyntaxKind.StructDeclaration or SyntaxKind.InterfaceDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration; } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/CompletionListTagCompletionProviderTests.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.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class CompletionListTagCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_EnumTypeDotMemberAlways() As Task Dim markup = <Text><![CDATA[ Class P Sub S() Dim d As Color = $$ End Sub End Class</a> ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ ''' <completionlist cref="Color"/> Public Class Color <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Shared X as Integer = 3 Public Shared Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_EnumTypeDotMemberNever() As Task Dim markup = <Text><![CDATA[ Class P Sub S() Dim d As Color = $$ End Sub End Class</a> ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ ''' <completionlist cref="Color"/> Public Class Color <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Shared X as Integer = 3 Public Shared Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_EnumTypeDotMemberAdvanced() As Task Dim markup = <Text><![CDATA[ Class P Sub S() Dim d As Color = $$ End Sub End Class</a> ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ ''' <completionlist cref="Color"/> Public Class Color <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Shared X as Integer = 3 Public Shared Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTriggeredOnOpenParen() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) ' type after this line Bar($$ End Sub Sub Bar(f As Color) End Sub End Module ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True) Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRightSideOfAssignment() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x as Color x = $$ End Sub End Module ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True) Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotCrashInObjectInitializer() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim z = New Goo() With {.z$$ } End Sub Class Goo Property A As Integer Get End Get Set(value As Integer) End Set End Property End Class End Module ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInYieldReturn() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class Class C Iterator Function M() As IEnumerable(Of Color) Yield $$ End Function End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInAsyncMethodReturnStatement() As Task Dim markup = <Text><![CDATA[ Imports System.Threading.Tasks ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class Class C Async Function M() As Task(Of Color) Await Task.Delay(1) Return $$ End Function End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInIndexedProperty() As Task Dim markup = <Text><![CDATA[ Module Module1 ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class Public Class MyClass1 Public WriteOnly Property MyProperty(ByVal val1 As Color) As Boolean Set(ByVal value As Boolean) End Set End Property Public Sub MyMethod(ByVal val1 As Color) End Sub End Class Sub Main() Dim var As MyClass1 = New MyClass1 ' MARKER var.MyMethod(Color.X) var.MyProperty($$Color.Y) = True End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.Y") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFullyQualified() As Task Dim markup = <Text><![CDATA[ Namespace ColorNamespace ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class End Namespace Class C Public Sub M(day As ColorNamespace.Color) M($$) End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.X", glyph:=CType(Glyph.FieldPublic, Integer)) Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.Y", glyph:=CType(Glyph.PropertyPublic, Integer)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTriggeredForNamedArgument() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(day As Color) M(day:=$$) End Sub ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotInObjectCreation() As Task Dim markup = <Text><![CDATA[ ''' <completionlist cref="Program"/> Class Program Public Shared Goo As Integer Sub Main(args As String()) Dim p As Program = New $$ End Sub End Class ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "Program.Goo") End Function <WorkItem(954694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954694")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAnyAccessibleMember() As Task Dim markup = <Text><![CDATA[ Public Class Program Private Shared field1 As Integer ''' <summary> ''' </summary> ''' <completionList cref="Program"></completionList> Public Class Program2 Public Async Function TestM() As Task Dim obj As Program2 =$$ End Sub End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Program.field1") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(815963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/815963")> Public Async Function TestLocalNoAs() As Task Dim markup = <Text><![CDATA[ Enum E A End Enum Class C Sub M() Const e As E = e$$ End Sub End Class ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "e As E") End Function <WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotInTrivia() As Task Dim markup = <Text><![CDATA[ Class C Sub Test() M(Type2.A) ' $$ End Sub Private Sub M(a As Type1) Throw New NotImplementedException() End Sub End Class ''' <completionlist cref="Type2"/> Public Class Type1 End Class Public Class Type2 Public Shared A As Type1 Public Shared B As Type1 End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAfterInvocationWithCompletionListTagTypeAsFirstParameter() As Task Dim markup = <Text><![CDATA[ Class C Sub Test() M(Type2.A) $$ End Sub Private Sub M(a As Type1) Throw New NotImplementedException() End Sub End Class ''' <completionlist cref="Type2"/> Public Class Type1 End Class Public Class Type2 Public Shared A As Type1 Public Shared B As Type1 End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <WorkItem(18787, "https://github.com/dotnet/roslyn/issues/18787")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotAfterDot() As Task Dim markup = <Text><![CDATA[ Public Class Program Private Shared field1 As Integer ''' <summary> ''' </summary> ''' <completionList cref="Program"></completionList> Public Class Program2 Public Async Function TestM() As Task Dim obj As Program2 = Program.$$ End Sub End Class End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function Friend Overrides Function GetCompletionProviderType() As Type Return GetType(CompletionListTagCompletionProvider) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class CompletionListTagCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_EnumTypeDotMemberAlways() As Task Dim markup = <Text><![CDATA[ Class P Sub S() Dim d As Color = $$ End Sub End Class</a> ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ ''' <completionlist cref="Color"/> Public Class Color <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Shared X as Integer = 3 Public Shared Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_EnumTypeDotMemberNever() As Task Dim markup = <Text><![CDATA[ Class P Sub S() Dim d As Color = $$ End Sub End Class</a> ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ ''' <completionlist cref="Color"/> Public Class Color <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Shared X as Integer = 3 Public Shared Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_EnumTypeDotMemberAdvanced() As Task Dim markup = <Text><![CDATA[ Class P Sub S() Dim d As Color = $$ End Sub End Class</a> ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ ''' <completionlist cref="Color"/> Public Class Color <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Shared X as Integer = 3 Public Shared Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Color.X", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTriggeredOnOpenParen() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) ' type after this line Bar($$ End Sub Sub Bar(f As Color) End Sub End Module ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True) Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRightSideOfAssignment() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x as Color x = $$ End Sub End Module ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True) Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDoNotCrashInObjectInitializer() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim z = New Goo() With {.z$$ } End Sub Class Goo Property A As Integer Get End Get Set(value As Integer) End Set End Property End Class End Module ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInYieldReturn() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class Class C Iterator Function M() As IEnumerable(Of Color) Yield $$ End Function End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInAsyncMethodReturnStatement() As Task Dim markup = <Text><![CDATA[ Imports System.Threading.Tasks ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class Class C Async Function M() As Task(Of Color) Await Task.Delay(1) Return $$ End Function End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInIndexedProperty() As Task Dim markup = <Text><![CDATA[ Module Module1 ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class Public Class MyClass1 Public WriteOnly Property MyProperty(ByVal val1 As Color) As Boolean Set(ByVal value As Boolean) End Set End Property Public Sub MyMethod(ByVal val1 As Color) End Sub End Class Sub Main() Dim var As MyClass1 = New MyClass1 ' MARKER var.MyMethod(Color.X) var.MyProperty($$Color.Y) = True End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.Y") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFullyQualified() As Task Dim markup = <Text><![CDATA[ Namespace ColorNamespace ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class End Namespace Class C Public Sub M(day As ColorNamespace.Color) M($$) End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.X", glyph:=CType(Glyph.FieldPublic, Integer)) Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.Y", glyph:=CType(Glyph.PropertyPublic, Integer)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTriggeredForNamedArgument() As Task Dim markup = <Text><![CDATA[ Class C Public Sub M(day As Color) M(day:=$$) End Sub ''' <completionlist cref="Color"/> Public Class Color Public Shared X as Integer = 3 Public Shared Property Y as Integer = 4 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotInObjectCreation() As Task Dim markup = <Text><![CDATA[ ''' <completionlist cref="Program"/> Class Program Public Shared Goo As Integer Sub Main(args As String()) Dim p As Program = New $$ End Sub End Class ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "Program.Goo") End Function <WorkItem(954694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954694")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAnyAccessibleMember() As Task Dim markup = <Text><![CDATA[ Public Class Program Private Shared field1 As Integer ''' <summary> ''' </summary> ''' <completionList cref="Program"></completionList> Public Class Program2 Public Async Function TestM() As Task Dim obj As Program2 =$$ End Sub End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Program.field1") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(815963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/815963")> Public Async Function TestLocalNoAs() As Task Dim markup = <Text><![CDATA[ Enum E A End Enum Class C Sub M() Const e As E = e$$ End Sub End Class ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "e As E") End Function <WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotInTrivia() As Task Dim markup = <Text><![CDATA[ Class C Sub Test() M(Type2.A) ' $$ End Sub Private Sub M(a As Type1) Throw New NotImplementedException() End Sub End Class ''' <completionlist cref="Type2"/> Public Class Type1 End Class Public Class Type2 Public Shared A As Type1 Public Shared B As Type1 End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotAfterInvocationWithCompletionListTagTypeAsFirstParameter() As Task Dim markup = <Text><![CDATA[ Class C Sub Test() M(Type2.A) $$ End Sub Private Sub M(a As Type1) Throw New NotImplementedException() End Sub End Class ''' <completionlist cref="Type2"/> Public Class Type1 End Class Public Class Type2 Public Shared A As Type1 Public Shared B As Type1 End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <WorkItem(18787, "https://github.com/dotnet/roslyn/issues/18787")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NotAfterDot() As Task Dim markup = <Text><![CDATA[ Public Class Program Private Shared field1 As Integer ''' <summary> ''' </summary> ''' <completionList cref="Program"></completionList> Public Class Program2 Public Async Function TestM() As Task Dim obj As Program2 = Program.$$ End Sub End Class End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function Friend Overrides Function GetCompletionProviderType() As Type Return GetType(CompletionListTagCompletionProvider) End Function End Class End Namespace
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IProjectCodeModelProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { internal sealed partial class CPSProject { public EnvDTE.CodeModel GetCodeModel(EnvDTE.Project parent) => _projectCodeModel.GetOrCreateRootCodeModel(parent); public EnvDTE.FileCodeModel GetFileCodeModel(EnvDTE.ProjectItem item) { if (!item.TryGetFullPath(out var filePath)) { return null; } return _projectCodeModel.GetOrCreateFileCodeModel(filePath, item); } private class CPSCodeModelInstanceFactory : ICodeModelInstanceFactory { private readonly CPSProject _project; public CPSCodeModelInstanceFactory(CPSProject project) => _project = project; EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath) { var projectItem = GetProjectItem(filePath); if (projectItem == null) { return null; } return _project._projectCodeModel.GetOrCreateFileCodeModel(filePath, projectItem); } private EnvDTE.ProjectItem GetProjectItem(string filePath) { var dteProject = _project._visualStudioWorkspace.TryGetDTEProject(_project._visualStudioProject.Id); if (dteProject == null) { return null; } return dteProject.FindItemByPath(filePath, StringComparer.OrdinalIgnoreCase); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { internal sealed partial class CPSProject { public EnvDTE.CodeModel GetCodeModel(EnvDTE.Project parent) => _projectCodeModel.GetOrCreateRootCodeModel(parent); public EnvDTE.FileCodeModel GetFileCodeModel(EnvDTE.ProjectItem item) { if (!item.TryGetFullPath(out var filePath)) { return null; } return _projectCodeModel.GetOrCreateFileCodeModel(filePath, item); } private class CPSCodeModelInstanceFactory : ICodeModelInstanceFactory { private readonly CPSProject _project; public CPSCodeModelInstanceFactory(CPSProject project) => _project = project; EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath) { var projectItem = GetProjectItem(filePath); if (projectItem == null) { return null; } return _project._projectCodeModel.GetOrCreateFileCodeModel(filePath, projectItem); } private EnvDTE.ProjectItem GetProjectItem(string filePath) { var dteProject = _project._visualStudioWorkspace.TryGetDTEProject(_project._visualStudioProject.Id); if (dteProject == null) { return null; } return dteProject.FindItemByPath(filePath, StringComparer.OrdinalIgnoreCase); } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState> { // TODO: Need to estimate amount of elements for this map and pass that value to the constructor. protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>(); private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything); private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>(); private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt; public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt => _embeddedTypesManagerOpt; // Gives the name of this module (may not reflect the name of the underlying symbol). // See Assembly.MetadataName. private readonly string _metadataName; private ImmutableArray<Cci.ExportedType> _lazyExportedTypes; /// <summary> /// The compiler-generated implementation type for each fixed-size buffer. /// </summary> private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return GetNeedsGeneratedAttributesInternal(); } private EmbeddableAttributes GetNeedsGeneratedAttributesInternal() { return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes(); } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal PEModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, new ModuleCompilationState()) { var specifiedName = sourceModule.MetadataName; _metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ? specifiedName : emitOptions.OutputNameOverride ?? specifiedName; AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this); if (sourceModule.AnyReferencedAssembliesAreLinked) { _embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this); } } public override string Name { get { return _metadataName; } } internal sealed override string ModuleName { get { return _metadataName; } } internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor) { return Compilation.TrySynthesizeAttribute(attributeConstructor); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly) { return SourceModule.ContainingSourceAssembly .GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule()); } public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes() { return SourceModule.ContainingSourceAssembly.GetSecurityAttributes(); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes() { return SourceModule.GetCustomAttributesToEmit(this); } internal sealed override AssemblySymbol CorLibrary { get { return SourceModule.ContainingSourceAssembly.CorLibrary; } } public sealed override bool GenerateVisualBasicStylePdb => false; // C# doesn't emit linked assembly names into PDBs. public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>(); // C# currently doesn't emit compilation level imports (TODO: scripting). public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty; // C# doesn't allow to define default namespace for compilation. public sealed override string DefaultNamespace => null; protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules; for (int i = 1; i < modules.Length; i++) { foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols()) { yield return Translate(aRef, diagnostics); } } } private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics) { AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity; AssemblyIdentity refIdentity = asmRef.Identity; if (asmIdentity.IsStrongName && !refIdentity.IsStrongName && asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime) { // Dev12 reported error, we have changed it to a warning to allow referencing libraries // built for platforms that don't support strong names. diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton); } if (OutputKind != OutputKind.NetModule && !string.IsNullOrEmpty(refIdentity.CultureName) && !string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton); } var refMachine = assembly.Machine; // If other assembly is agnostic this is always safe // Also, if no mscorlib was specified for back compat we add a reference to mscorlib // that resolves to the current framework directory. If the compiler is 64-bit // this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is // specified. A reference to the default mscorlib should always succeed without // warning so we ignore it here. if ((object)assembly != (object)assembly.CorLibrary && !(refMachine == Machine.I386 && !assembly.Bit32Required)) { var machine = SourceModule.Machine; if (!(machine == Machine.I386 && !SourceModule.Bit32Required) && machine != refMachine) { // Different machine types, and neither is agnostic diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton); } } if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen) { _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics); } } internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container) { return null; } public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap() { var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>(); var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>(); namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace); Location location = null; while (namespacesAndTypesToProcess.Count > 0) { NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop(); switch (symbol.Kind) { case SymbolKind.Namespace: location = GetSmallestSourceLocationOrNull(symbol); // filtering out synthesized symbols not having real source // locations such as anonymous types, etc... if (location != null) { foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; case SymbolKind.NamedType: location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { // add this named type location AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; case SymbolKind.Method: // NOTE: Dev11 does not add synthesized static constructors to this map, // but adds synthesized instance constructors, Roslyn adds both var method = (MethodSymbol)member; if (!method.ShouldEmit()) { break; } AddSymbolLocation(result, member); break; case SymbolKind.Property: AddSymbolLocation(result, member); break; case SymbolKind.Field: if (member is TupleErrorFieldSymbol) { break; } // NOTE: Dev11 does not add synthesized backing fields for properties, // but adds backing fields for events, Roslyn adds both AddSymbolLocation(result, member); break; case SymbolKind.Event: AddSymbolLocation(result, member); // event backing fields do not show up in GetMembers { FieldSymbol field = ((EventSymbol)member).AssociatedField; if ((object)field != null) { AddSymbolLocation(result, field); } } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } return result; } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol) { var location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); } } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition) { FileLinePositionSpan span = location.GetLineSpan(); Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath); if (doc != null) { result.Add(doc, new Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)); } } private Location GetSmallestSourceLocationOrNull(Symbol symbol) { CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?"); Location result = null; foreach (var loc in symbol.Locations) { if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0)) { result = loc; } } return result; } /// <summary> /// Ignore accessibility when resolving well-known type /// members, in particular for generic type arguments /// (e.g.: binding to internal types in the EE). /// </summary> internal virtual bool IgnoreAccessibility => false; /// <summary> /// Override the dynamic operation context type for all dynamic calls in the module. /// </summary> internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType) { return contextType; } internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return null; } internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray<AnonymousTypeKey>.Empty; } internal virtual ImmutableArray<SynthesizedDelegateKey> GetPreviousSynthesizedDelegates() { return ImmutableArray<SynthesizedDelegateKey>.Empty; } internal virtual int GetNextAnonymousTypeIndex() { return 0; } internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index) { Debug.Assert(Compilation == template.DeclaringCompilation); name = null; index = -1; return false; } public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context) { if (context.MetadataOnly) { return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>(); } return Compilation.AnonymousTypeManager.GetAllCreatedTemplates() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { var namespacesToProcess = new Stack<NamespaceSymbol>(); namespacesToProcess.Push(SourceModule.GlobalNamespace); while (namespacesToProcess.Count > 0) { var ns = namespacesToProcess.Pop(); foreach (var member in ns.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { namespacesToProcess.Push((NamespaceSymbol)member); } else { yield return ((NamedTypeSymbol)member).GetCciAdapter(); } } } } private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder) { int index; if (symbol.Kind == SymbolKind.NamedType) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return; } Debug.Assert(symbol.IsDefinition); index = builder.Count; builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false)); } else { index = -1; } foreach (var member in symbol.GetMembers()) { var namespaceOrType = member as NamespaceOrTypeSymbol; if ((object)namespaceOrType != null) { GetExportedTypes(namespaceOrType, index, builder); } } } public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics) { Debug.Assert(HaveDeterminedTopLevelTypes); if (_lazyExportedTypes.IsDefault) { _lazyExportedTypes = CalculateExportedTypes(); if (_lazyExportedTypes.Length > 0) { ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics); } } return _lazyExportedTypes; } /// <summary> /// Builds an array of public type symbols defined in netmodules included in the compilation /// and type forwarders defined in this compilation or any included netmodule (in this order). /// </summary> private ImmutableArray<Cci.ExportedType> CalculateExportedTypes() { SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly; var builder = ArrayBuilder<Cci.ExportedType>.GetInstance(); if (!OutputKind.IsNetModule()) { var modules = sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0] { GetExportedTypes(modules[i].GlobalNamespace, -1, builder); } } Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()); GetForwardedTypes(sourceAssembly, builder); return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Returns a set of top-level forwarded types /// </summary> internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder) { var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>(); GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder); if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) { GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder); } return seenTopLevelForwardedTypes; } #nullable disable private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics) { var sourceAssembly = SourceModule.ContainingSourceAssembly; var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (var exportedType in exportedTypes) { var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol(); Debug.Assert(type.IsDefinition); if (!type.IsTopLevelType()) { continue; } // exported types are not emitted in EnC deltas (hence generation 0): string fullEmittedName = MetadataHelpers.BuildQualifiedName( ((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName, Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0)); // First check against types declared in the primary module if (ContainsTopLevelType(fullEmittedName)) { if ((object)type.ContainingAssembly == sourceAssembly) { diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule); } else { diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type); } continue; } NamedTypeSymbol contender; // Now check against other exported types if (exportedNamesMap.TryGetValue(fullEmittedName, out contender)) { if ((object)type.ContainingAssembly == sourceAssembly) { // all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly == sourceAssembly); diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule); } else if ((object)contender.ContainingAssembly == sourceAssembly) { // Forwarded type conflicts with exported type diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule); } else { // Forwarded type conflicts with another forwarded type diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly); } continue; } exportedNamesMap.Add(fullEmittedName, type); } } #nullable enable private static void GetForwardedTypes( HashSet<NamedTypeSymbol> seenTopLevelTypes, CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData, ArrayBuilder<Cci.ExportedType>? builder) { if (wellKnownAttributeData?.ForwardedTypes?.Count > 0) { // (type, index of the parent exported type in builder, or -1 if the type is a top-level type) var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance(); // Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes; if (builder is object) { orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); } foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions before emitting. if (!seenTopLevelTypes.Add(originalDefinition)) continue; if (builder is object) { // Return all nested types. // Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count == 0); stack.Push((originalDefinition, -1)); while (stack.Count > 0) { var (type, parentIndex) = stack.Pop(); // In general, we don't want private types to appear in the ExportedTypes table. // BREAK: dev11 emits these types. The problem was discovered in dev10, but failed // to meet the bar Bug: Dev10/258038 and was left as-is. if (type.DeclaredAccessibility == Accessibility.Private) { // NOTE: this will also exclude nested types of type continue; } // NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. int index = builder.Count; builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true)); // Iterate backwards so they get popped in forward order. ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered. for (int i = nested.Length - 1; i >= 0; i--) { stack.Push((nested[i], index)); } } } } stack.Free(); } } #nullable disable internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar() { foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols()) { if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a)) { yield return a; } } } private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType); DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo; if (info != null) { Symbol.ReportUseSiteDiagnostic(info, diagnostics, syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton); } return typeSymbol; } internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), diagnostics: diagnostics, syntaxNodeOpt: syntaxNodeOpt, needDeclaration: true); } public sealed override Cci.IMethodReference GetInitArrayHelper() { return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter(); } public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType) { var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol; if ((object)namedType != null) { if (platformType == Cci.PlatformType.SystemType) { return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type); } return namedType.SpecialType == (SpecialType)platformType; } return false; } protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context) { AssemblySymbol corLibrary = CorLibrary; if (!corLibrary.IsMissing && !corLibrary.IsLinked && !ReferenceEquals(corLibrary, SourceModule.ContainingAssembly)) { return Translate(corLibrary, context.Diagnostics); } return null; } internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule.ContainingAssembly, assembly)) { return (Cci.IAssemblyReference)this; } Cci.IModuleReference reference; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference)) { return (Cci.IAssemblyReference)reference; } AssemblyReference asmRef = new AssemblyReference(assembly); AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef); if (cachedAsmRef == asmRef) { ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics); } // TryAdd because whatever is associated with assembly should be associated with Modules[0] AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef); return cachedAsmRef; } internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule, module)) { return this; } if ((object)module == null) { return null; } Cci.IModuleReference moduleRef; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef)) { return moduleRef; } moduleRef = TranslateModule(module, diagnostics); moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef); return moduleRef; } protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics) { AssemblySymbol container = module.ContainingAssembly; if ((object)container != null && ReferenceEquals(container.Modules[0], module)) { Cci.IModuleReference moduleRef = new AssemblyReference(container); Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef); if (cachedModuleRef == moduleRef) { ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics); } else { moduleRef = cachedModuleRef; } return moduleRef; } else { return new ModuleReference(this, module); } } internal Cci.INamedTypeReference Translate( NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool fromImplements = false, bool needDeclaration = false) { Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct()); Debug.Assert(diagnostics != null); // Anonymous type being translated if (namedTypeSymbol.IsAnonymousType) { Debug.Assert(!needDeclaration); namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol); } else if (namedTypeSymbol.IsTupleType) { CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics); } // Substitute error types with a special singleton object. // Unreported bad types can come through NoPia embedding, for example. if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType) { ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition; DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType) { errorType = (ErrorTypeSymbol)namedTypeSymbol; diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; } // Try to decrease noise by not complaining about the same type over and over again. if (_reportedErrorTypesMap.Add(errorType)) { diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location)); } return CodeAnalysis.Emit.ErrorType.Singleton; } if (!namedTypeSymbol.IsDefinition) { // generic instantiation for sure Debug.Assert(!needDeclaration); if (namedTypeSymbol.IsUnboundGenericType) { namedTypeSymbol = namedTypeSymbol.OriginalDefinition; } else { return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol); } } else if (!needDeclaration) { object reference; Cci.INamedTypeReference typeRef; NamedTypeSymbol container = namedTypeSymbol.ContainingType; if (namedTypeSymbol.Arity > 0) { if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } if ((object)container != null) { if (IsGenericType(container)) { // Container is a generic instance too. typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol); } else { typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol); } } else { typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol); } typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (IsGenericType(container)) { Debug.Assert((object)container != null); if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } typeRef = new SpecializedNestedTypeReference(namedTypeSymbol); typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType) { namedTypeSymbol = underlyingType; } } // NoPia: See if this is a type, which definition we should copy into our assembly. Debug.Assert(namedTypeSymbol.IsDefinition); return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter(); } private object GetCciAdapter(Symbol symbol) { return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter()); } private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // check that underlying type of a ValueTuple is indeed a value type (or error) // this should never happen, in theory, // but if it does happen we should make it a failure. // NOTE: declaredBase could be null for interfaces var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType) { return; } // Try to decrease noise by not complaining about the same type over and over again. if (!_reportedErrorTypesMap.Add(namedTypeSymbol)) { return; } var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location; if ((object)declaredBase != null) { var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo; if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(diagnosticInfo, location); return; } } diagnostics.Add( new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName), location)); } public static bool IsGenericType(NamedTypeSymbol toCheck) { while ((object)toCheck != null) { if (toCheck.Arity > 0) { return true; } toCheck = toCheck.ContainingType; } return false; } internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param) { if (!param.IsDefinition) throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name)); return param.GetCciAdapter(); } internal sealed override Cci.ITypeReference Translate( TypeSymbol typeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); switch (typeSymbol.Kind) { case SymbolKind.DynamicType: return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.ArrayType: return Translate((ArrayTypeSymbol)typeSymbol); case SymbolKind.ErrorType: case SymbolKind.NamedType: return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.PointerType: return Translate((PointerTypeSymbol)typeSymbol); case SymbolKind.TypeParameter: return Translate((TypeParameterSymbol)typeSymbol); case SymbolKind.FunctionPointerType: return Translate((FunctionPointerTypeSymbol)typeSymbol); } throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind); } internal Cci.IFieldReference Translate( FieldSymbol fieldSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration = false) { Debug.Assert(fieldSymbol.IsDefinitionOrDistinct()); Debug.Assert(!fieldSymbol.IsVirtualTupleField && (object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol && fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now"); if (!fieldSymbol.IsDefinition) { Debug.Assert(!needDeclaration); return (Cci.IFieldReference)GetCciAdapter(fieldSymbol); } else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType)) { object reference; Cci.IFieldReference fieldRef; if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference)) { return (Cci.IFieldReference)reference; } fieldRef = new SpecializedFieldReference(fieldSymbol); fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef); return fieldRef; } return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter(); } public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol) { // // We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies. // // Top-level: // private -> public // protected -> public (compiles with a warning) // public // internal -> public // // In a nested class: // // private // protected // public // internal -> public // switch (symbol.DeclaredAccessibility) { case Accessibility.Public: return Cci.TypeMemberVisibility.Public; case Accessibility.Private: if (symbol.ContainingType?.TypeKind == TypeKind.Submission) { // top-level private member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Private; } case Accessibility.Internal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Assembly; } case Accessibility.Protected: if (symbol.ContainingType.TypeKind == TypeKind.Submission) { // top-level protected member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Family; } case Accessibility.ProtectedAndInternal: Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission); return Cci.TypeMemberVisibility.FamilyAndAssembly; case Accessibility.ProtectedOrInternal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested protected internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.FamilyOrAssembly; } default: throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility); } } internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate(symbol, null, diagnostics, null, needDeclaration); } internal Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, BoundArgListOperator optArgList = null, bool needDeclaration = false) { Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true)); Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration)); Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration); if (optArgList != null && optArgList.Arguments.Length > 0) { Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length]; int ordinal = methodSymbol.ParameterCount; for (int i = 0; i < @params.Length; i++) { @params[i] = new ArgListParameterTypeInformation(ordinal, !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None, Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics)); ordinal++; } return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull()); } else { return unexpandedMethodRef; } } private Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration) { object reference; Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; // Method of anonymous type being translated if (container.IsAnonymousType) { Debug.Assert(!needDeclaration); methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol); } Debug.Assert(methodSymbol.IsDefinitionOrDistinct()); if (!methodSymbol.IsDefinition) { Debug.Assert(!needDeclaration); Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol)); Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol)); return (Cci.IMethodReference)GetCciAdapter(methodSymbol); } else if (!needDeclaration) { bool methodIsGeneric = methodSymbol.IsGenericMethod; bool typeIsGeneric = IsGenericType(container); if (methodIsGeneric || typeIsGeneric) { if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { return (Cci.IMethodReference)reference; } if (methodIsGeneric) { if (typeIsGeneric) { // Specialized and generic instance at the same time. methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol); } else { methodRef = new GenericMethodInstanceReference(methodSymbol); } } else { Debug.Assert(typeIsGeneric); methodRef = new SpecializedMethodReference(methodSymbol); } methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); return methodRef; } else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod }) { methodSymbol = underlyingMethod; } } if (_embeddedTypesManagerOpt != null) { return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } return methodSymbol.GetCciAdapter(); } internal Cci.IMethodReference TranslateOverriddenMethodReference( MethodSymbol methodSymbol, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; if (IsGenericType(container)) { if (methodSymbol.IsDefinition) { object reference; if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { methodRef = (Cci.IMethodReference)reference; } else { methodRef = new SpecializedMethodReference(methodSymbol); methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); } } else { methodRef = new SpecializedMethodReference(methodSymbol); } } else { Debug.Assert(methodSymbol.IsDefinition); if (_embeddedTypesManagerOpt != null) { methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } else { methodRef = methodSymbol.GetCciAdapter(); } } return methodRef; } internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params) { Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct())); bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First()); Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating"); if (!mustBeTranslated) { #if DEBUG return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter()); #else return StaticCast<Cci.IParameterTypeInformation>.From(@params); #endif } return TranslateAll(@params); } private static bool MustBeWrapped(ParameterSymbol param) { // we represent parameters of generic methods as definitions // CCI wants them represented as IParameterTypeInformation // so we need to create a wrapper of parameters iff // 1) parameters are definitions and // 2) container is generic // NOTE: all parameters must always agree on whether they need wrapping if (param.IsDefinition) { var container = param.ContainingSymbol; if (ContainerIsGeneric(container)) { return true; } } return false; } private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params) { var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance(); foreach (var param in @params) { builder.Add(CreateParameterTypeInformationWrapper(param)); } return builder.ToImmutableAndFree(); } private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param) { object reference; Cci.IParameterTypeInformation paramRef; if (_genericInstanceMap.TryGetValue(param, out reference)) { return (Cci.IParameterTypeInformation)reference; } paramRef = new ParameterTypeInformation(param); paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef); return paramRef; } private static bool ContainerIsGeneric(Symbol container) { return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod || IsGenericType(container.ContainingType); } internal Cci.ITypeReference Translate( DynamicTypeSymbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table. // We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter // masquerades the TypeRef as System.Object when used to encode signatures. return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics); } internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol) { return (Cci.IArrayTypeReference)GetCciAdapter(symbol); } internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol) { return (Cci.IPointerTypeReference)GetCciAdapter(symbol); } internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol) { return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol); } /// <summary> /// Set the underlying implementation type for a given fixed-size buffer field. /// </summary> public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field) { if (_fixedImplementationTypes == null) { Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null); } lock (_fixedImplementationTypes) { NamedTypeSymbol result; if (_fixedImplementationTypes.TryGetValue(field, out result)) { return result; } result = new FixedFieldImplementationType(field); _fixedImplementationTypes.Add(field, result); AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter()); return result; } } internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field) { // Note that this method is called only after ALL fixed buffer types have been placed in the map. // At that point the map is all filled in and will not change further. Therefore it is safe to // pull values from the map without locking. NamedTypeSymbol result; var found = _fixedImplementationTypes.TryGetValue(field, out result); Debug.Assert(found); return result; } protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics) { return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter(); } internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute(); internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsReadOnlyAttribute(); } internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsUnmanagedAttribute(); } internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsByRefLikeAttribute(); } /// <summary> /// Given a type <paramref name="type"/>, which is either a nullable reference type OR /// is a constructed type with a nullable reference type present in its type argument tree, /// returns a synthesized NullableAttribute with encoded nullable transforms array. /// </summary> internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var flagsBuilder = ArrayBuilder<byte>.GetInstance(); type.AddNullableTransforms(flagsBuilder); SynthesizedAttributeData attribute; if (!flagsBuilder.Any()) { attribute = null; } else { Debug.Assert(flagsBuilder.All(f => f <= 2)); byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder); if (commonValue != null) { attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault()); } else { NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType)); var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType); attribute = SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, ImmutableArray.Create(new TypedConstant(byteArrayType, value))); } } flagsBuilder.Free(); return attribute; } internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue) { if (nullableValue == nullableContextValue || (nullableContextValue == null && nullableValue == 0)) { return null; } NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); return SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue))); } internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value) { var module = Compilation.SourceModule; if ((object)module != symbol && (object)module != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return SynthesizeNullableContextAttribute( ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value))); } internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute() { return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.ContainsNativeInteger()); if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type); Debug.Assert(builder.Any()); Debug.Assert(builder.Contains(true)); SynthesizedAttributeData attribute; if (builder.Count == 1 && builder[0]) { attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty); } else { NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert((object)booleanType != null); var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments); } builder.Free(); return attribute; } internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal bool ShouldEmitNullablePublicOnlyAttribute() { // No need to look at this.GetNeedsGeneratedAttributes() since those bits are // only set for members generated by the rewriter which are not public. return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly; } internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments); } protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0) { return; } // Don't report any errors. They should be reported during binding. if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null)) { SetNeedsGeneratedAttributes(attribute); } } internal void EnsureIsReadOnlyAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute); } internal void EnsureIsUnmanagedAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute); } internal void EnsureNullableAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute); } internal void EnsureNullableContextAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute); } internal void EnsureNativeIntegerAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute); } public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context) { return GetAdditionalTopLevelTypes() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context) { return GetEmbeddedTypes(context.Diagnostics) #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) { return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics)); } internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { return base.GetEmbeddedTypes(diagnostics.DiagnosticBag); } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState> { // TODO: Need to estimate amount of elements for this map and pass that value to the constructor. protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>(); private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything); private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>(); private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt; public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt => _embeddedTypesManagerOpt; // Gives the name of this module (may not reflect the name of the underlying symbol). // See Assembly.MetadataName. private readonly string _metadataName; private ImmutableArray<Cci.ExportedType> _lazyExportedTypes; /// <summary> /// The compiler-generated implementation type for each fixed-size buffer. /// </summary> private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return GetNeedsGeneratedAttributesInternal(); } private EmbeddableAttributes GetNeedsGeneratedAttributesInternal() { return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes(); } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal PEModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, new ModuleCompilationState()) { var specifiedName = sourceModule.MetadataName; _metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ? specifiedName : emitOptions.OutputNameOverride ?? specifiedName; AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this); if (sourceModule.AnyReferencedAssembliesAreLinked) { _embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this); } } public override string Name { get { return _metadataName; } } internal sealed override string ModuleName { get { return _metadataName; } } internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor) { return Compilation.TrySynthesizeAttribute(attributeConstructor); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly) { return SourceModule.ContainingSourceAssembly .GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule()); } public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes() { return SourceModule.ContainingSourceAssembly.GetSecurityAttributes(); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes() { return SourceModule.GetCustomAttributesToEmit(this); } internal sealed override AssemblySymbol CorLibrary { get { return SourceModule.ContainingSourceAssembly.CorLibrary; } } public sealed override bool GenerateVisualBasicStylePdb => false; // C# doesn't emit linked assembly names into PDBs. public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>(); // C# currently doesn't emit compilation level imports (TODO: scripting). public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty; // C# doesn't allow to define default namespace for compilation. public sealed override string DefaultNamespace => null; protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules; for (int i = 1; i < modules.Length; i++) { foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols()) { yield return Translate(aRef, diagnostics); } } } private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics) { AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity; AssemblyIdentity refIdentity = asmRef.Identity; if (asmIdentity.IsStrongName && !refIdentity.IsStrongName && asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime) { // Dev12 reported error, we have changed it to a warning to allow referencing libraries // built for platforms that don't support strong names. diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton); } if (OutputKind != OutputKind.NetModule && !string.IsNullOrEmpty(refIdentity.CultureName) && !string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton); } var refMachine = assembly.Machine; // If other assembly is agnostic this is always safe // Also, if no mscorlib was specified for back compat we add a reference to mscorlib // that resolves to the current framework directory. If the compiler is 64-bit // this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is // specified. A reference to the default mscorlib should always succeed without // warning so we ignore it here. if ((object)assembly != (object)assembly.CorLibrary && !(refMachine == Machine.I386 && !assembly.Bit32Required)) { var machine = SourceModule.Machine; if (!(machine == Machine.I386 && !SourceModule.Bit32Required) && machine != refMachine) { // Different machine types, and neither is agnostic diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton); } } if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen) { _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics); } } internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container) { return null; } public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap() { var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>(); var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>(); namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace); Location location = null; while (namespacesAndTypesToProcess.Count > 0) { NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop(); switch (symbol.Kind) { case SymbolKind.Namespace: location = GetSmallestSourceLocationOrNull(symbol); // filtering out synthesized symbols not having real source // locations such as anonymous types, etc... if (location != null) { foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; case SymbolKind.NamedType: location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { // add this named type location AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; case SymbolKind.Method: // NOTE: Dev11 does not add synthesized static constructors to this map, // but adds synthesized instance constructors, Roslyn adds both var method = (MethodSymbol)member; if (!method.ShouldEmit()) { break; } AddSymbolLocation(result, member); break; case SymbolKind.Property: AddSymbolLocation(result, member); break; case SymbolKind.Field: if (member is TupleErrorFieldSymbol) { break; } // NOTE: Dev11 does not add synthesized backing fields for properties, // but adds backing fields for events, Roslyn adds both AddSymbolLocation(result, member); break; case SymbolKind.Event: AddSymbolLocation(result, member); // event backing fields do not show up in GetMembers { FieldSymbol field = ((EventSymbol)member).AssociatedField; if ((object)field != null) { AddSymbolLocation(result, field); } } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } return result; } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol) { var location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); } } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition) { FileLinePositionSpan span = location.GetLineSpan(); Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath); if (doc != null) { result.Add(doc, new Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)); } } private Location GetSmallestSourceLocationOrNull(Symbol symbol) { CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?"); Location result = null; foreach (var loc in symbol.Locations) { if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0)) { result = loc; } } return result; } /// <summary> /// Ignore accessibility when resolving well-known type /// members, in particular for generic type arguments /// (e.g.: binding to internal types in the EE). /// </summary> internal virtual bool IgnoreAccessibility => false; /// <summary> /// Override the dynamic operation context type for all dynamic calls in the module. /// </summary> internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType) { return contextType; } internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return null; } internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray<AnonymousTypeKey>.Empty; } internal virtual ImmutableArray<SynthesizedDelegateKey> GetPreviousSynthesizedDelegates() { return ImmutableArray<SynthesizedDelegateKey>.Empty; } internal virtual int GetNextAnonymousTypeIndex() { return 0; } internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index) { Debug.Assert(Compilation == template.DeclaringCompilation); name = null; index = -1; return false; } public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context) { if (context.MetadataOnly) { return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>(); } return Compilation.AnonymousTypeManager.GetAllCreatedTemplates() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { var namespacesToProcess = new Stack<NamespaceSymbol>(); namespacesToProcess.Push(SourceModule.GlobalNamespace); while (namespacesToProcess.Count > 0) { var ns = namespacesToProcess.Pop(); foreach (var member in ns.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { namespacesToProcess.Push((NamespaceSymbol)member); } else { yield return ((NamedTypeSymbol)member).GetCciAdapter(); } } } } private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder) { int index; if (symbol.Kind == SymbolKind.NamedType) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return; } Debug.Assert(symbol.IsDefinition); index = builder.Count; builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false)); } else { index = -1; } foreach (var member in symbol.GetMembers()) { var namespaceOrType = member as NamespaceOrTypeSymbol; if ((object)namespaceOrType != null) { GetExportedTypes(namespaceOrType, index, builder); } } } public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics) { Debug.Assert(HaveDeterminedTopLevelTypes); if (_lazyExportedTypes.IsDefault) { _lazyExportedTypes = CalculateExportedTypes(); if (_lazyExportedTypes.Length > 0) { ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics); } } return _lazyExportedTypes; } /// <summary> /// Builds an array of public type symbols defined in netmodules included in the compilation /// and type forwarders defined in this compilation or any included netmodule (in this order). /// </summary> private ImmutableArray<Cci.ExportedType> CalculateExportedTypes() { SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly; var builder = ArrayBuilder<Cci.ExportedType>.GetInstance(); if (!OutputKind.IsNetModule()) { var modules = sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0] { GetExportedTypes(modules[i].GlobalNamespace, -1, builder); } } Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()); GetForwardedTypes(sourceAssembly, builder); return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Returns a set of top-level forwarded types /// </summary> internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder) { var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>(); GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder); if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) { GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder); } return seenTopLevelForwardedTypes; } #nullable disable private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics) { var sourceAssembly = SourceModule.ContainingSourceAssembly; var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (var exportedType in exportedTypes) { var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol(); Debug.Assert(type.IsDefinition); if (!type.IsTopLevelType()) { continue; } // exported types are not emitted in EnC deltas (hence generation 0): string fullEmittedName = MetadataHelpers.BuildQualifiedName( ((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName, Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0)); // First check against types declared in the primary module if (ContainsTopLevelType(fullEmittedName)) { if ((object)type.ContainingAssembly == sourceAssembly) { diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule); } else { diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type); } continue; } NamedTypeSymbol contender; // Now check against other exported types if (exportedNamesMap.TryGetValue(fullEmittedName, out contender)) { if ((object)type.ContainingAssembly == sourceAssembly) { // all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly == sourceAssembly); diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule); } else if ((object)contender.ContainingAssembly == sourceAssembly) { // Forwarded type conflicts with exported type diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule); } else { // Forwarded type conflicts with another forwarded type diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly); } continue; } exportedNamesMap.Add(fullEmittedName, type); } } #nullable enable private static void GetForwardedTypes( HashSet<NamedTypeSymbol> seenTopLevelTypes, CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData, ArrayBuilder<Cci.ExportedType>? builder) { if (wellKnownAttributeData?.ForwardedTypes?.Count > 0) { // (type, index of the parent exported type in builder, or -1 if the type is a top-level type) var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance(); // Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes; if (builder is object) { orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); } foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions before emitting. if (!seenTopLevelTypes.Add(originalDefinition)) continue; if (builder is object) { // Return all nested types. // Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count == 0); stack.Push((originalDefinition, -1)); while (stack.Count > 0) { var (type, parentIndex) = stack.Pop(); // In general, we don't want private types to appear in the ExportedTypes table. // BREAK: dev11 emits these types. The problem was discovered in dev10, but failed // to meet the bar Bug: Dev10/258038 and was left as-is. if (type.DeclaredAccessibility == Accessibility.Private) { // NOTE: this will also exclude nested types of type continue; } // NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. int index = builder.Count; builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true)); // Iterate backwards so they get popped in forward order. ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered. for (int i = nested.Length - 1; i >= 0; i--) { stack.Push((nested[i], index)); } } } } stack.Free(); } } #nullable disable internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar() { foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols()) { if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a)) { yield return a; } } } private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType); DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo; if (info != null) { Symbol.ReportUseSiteDiagnostic(info, diagnostics, syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton); } return typeSymbol; } internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), diagnostics: diagnostics, syntaxNodeOpt: syntaxNodeOpt, needDeclaration: true); } public sealed override Cci.IMethodReference GetInitArrayHelper() { return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter(); } public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType) { var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol; if ((object)namedType != null) { if (platformType == Cci.PlatformType.SystemType) { return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type); } return namedType.SpecialType == (SpecialType)platformType; } return false; } protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context) { AssemblySymbol corLibrary = CorLibrary; if (!corLibrary.IsMissing && !corLibrary.IsLinked && !ReferenceEquals(corLibrary, SourceModule.ContainingAssembly)) { return Translate(corLibrary, context.Diagnostics); } return null; } internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule.ContainingAssembly, assembly)) { return (Cci.IAssemblyReference)this; } Cci.IModuleReference reference; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference)) { return (Cci.IAssemblyReference)reference; } AssemblyReference asmRef = new AssemblyReference(assembly); AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef); if (cachedAsmRef == asmRef) { ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics); } // TryAdd because whatever is associated with assembly should be associated with Modules[0] AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef); return cachedAsmRef; } internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule, module)) { return this; } if ((object)module == null) { return null; } Cci.IModuleReference moduleRef; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef)) { return moduleRef; } moduleRef = TranslateModule(module, diagnostics); moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef); return moduleRef; } protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics) { AssemblySymbol container = module.ContainingAssembly; if ((object)container != null && ReferenceEquals(container.Modules[0], module)) { Cci.IModuleReference moduleRef = new AssemblyReference(container); Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef); if (cachedModuleRef == moduleRef) { ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics); } else { moduleRef = cachedModuleRef; } return moduleRef; } else { return new ModuleReference(this, module); } } internal Cci.INamedTypeReference Translate( NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool fromImplements = false, bool needDeclaration = false) { Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct()); Debug.Assert(diagnostics != null); // Anonymous type being translated if (namedTypeSymbol.IsAnonymousType) { Debug.Assert(!needDeclaration); namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol); } else if (namedTypeSymbol.IsTupleType) { CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics); } // Substitute error types with a special singleton object. // Unreported bad types can come through NoPia embedding, for example. if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType) { ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition; DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType) { errorType = (ErrorTypeSymbol)namedTypeSymbol; diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; } // Try to decrease noise by not complaining about the same type over and over again. if (_reportedErrorTypesMap.Add(errorType)) { diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location)); } return CodeAnalysis.Emit.ErrorType.Singleton; } if (!namedTypeSymbol.IsDefinition) { // generic instantiation for sure Debug.Assert(!needDeclaration); if (namedTypeSymbol.IsUnboundGenericType) { namedTypeSymbol = namedTypeSymbol.OriginalDefinition; } else { return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol); } } else if (!needDeclaration) { object reference; Cci.INamedTypeReference typeRef; NamedTypeSymbol container = namedTypeSymbol.ContainingType; if (namedTypeSymbol.Arity > 0) { if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } if ((object)container != null) { if (IsGenericType(container)) { // Container is a generic instance too. typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol); } else { typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol); } } else { typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol); } typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (IsGenericType(container)) { Debug.Assert((object)container != null); if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } typeRef = new SpecializedNestedTypeReference(namedTypeSymbol); typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType) { namedTypeSymbol = underlyingType; } } // NoPia: See if this is a type, which definition we should copy into our assembly. Debug.Assert(namedTypeSymbol.IsDefinition); return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter(); } private object GetCciAdapter(Symbol symbol) { return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter()); } private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // check that underlying type of a ValueTuple is indeed a value type (or error) // this should never happen, in theory, // but if it does happen we should make it a failure. // NOTE: declaredBase could be null for interfaces var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType) { return; } // Try to decrease noise by not complaining about the same type over and over again. if (!_reportedErrorTypesMap.Add(namedTypeSymbol)) { return; } var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location; if ((object)declaredBase != null) { var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo; if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(diagnosticInfo, location); return; } } diagnostics.Add( new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName), location)); } public static bool IsGenericType(NamedTypeSymbol toCheck) { while ((object)toCheck != null) { if (toCheck.Arity > 0) { return true; } toCheck = toCheck.ContainingType; } return false; } internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param) { if (!param.IsDefinition) throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name)); return param.GetCciAdapter(); } internal sealed override Cci.ITypeReference Translate( TypeSymbol typeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); switch (typeSymbol.Kind) { case SymbolKind.DynamicType: return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.ArrayType: return Translate((ArrayTypeSymbol)typeSymbol); case SymbolKind.ErrorType: case SymbolKind.NamedType: return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.PointerType: return Translate((PointerTypeSymbol)typeSymbol); case SymbolKind.TypeParameter: return Translate((TypeParameterSymbol)typeSymbol); case SymbolKind.FunctionPointerType: return Translate((FunctionPointerTypeSymbol)typeSymbol); } throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind); } internal Cci.IFieldReference Translate( FieldSymbol fieldSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration = false) { Debug.Assert(fieldSymbol.IsDefinitionOrDistinct()); Debug.Assert(!fieldSymbol.IsVirtualTupleField && (object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol && fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now"); if (!fieldSymbol.IsDefinition) { Debug.Assert(!needDeclaration); return (Cci.IFieldReference)GetCciAdapter(fieldSymbol); } else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType)) { object reference; Cci.IFieldReference fieldRef; if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference)) { return (Cci.IFieldReference)reference; } fieldRef = new SpecializedFieldReference(fieldSymbol); fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef); return fieldRef; } return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter(); } public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol) { // // We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies. // // Top-level: // private -> public // protected -> public (compiles with a warning) // public // internal -> public // // In a nested class: // // private // protected // public // internal -> public // switch (symbol.DeclaredAccessibility) { case Accessibility.Public: return Cci.TypeMemberVisibility.Public; case Accessibility.Private: if (symbol.ContainingType?.TypeKind == TypeKind.Submission) { // top-level private member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Private; } case Accessibility.Internal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Assembly; } case Accessibility.Protected: if (symbol.ContainingType.TypeKind == TypeKind.Submission) { // top-level protected member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Family; } case Accessibility.ProtectedAndInternal: Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission); return Cci.TypeMemberVisibility.FamilyAndAssembly; case Accessibility.ProtectedOrInternal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested protected internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.FamilyOrAssembly; } default: throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility); } } internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate(symbol, null, diagnostics, null, needDeclaration); } internal Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, BoundArgListOperator optArgList = null, bool needDeclaration = false) { Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true)); Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration)); Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration); if (optArgList != null && optArgList.Arguments.Length > 0) { Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length]; int ordinal = methodSymbol.ParameterCount; for (int i = 0; i < @params.Length; i++) { @params[i] = new ArgListParameterTypeInformation(ordinal, !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None, Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics)); ordinal++; } return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull()); } else { return unexpandedMethodRef; } } private Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration) { object reference; Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; // Method of anonymous type being translated if (container.IsAnonymousType) { Debug.Assert(!needDeclaration); methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol); } Debug.Assert(methodSymbol.IsDefinitionOrDistinct()); if (!methodSymbol.IsDefinition) { Debug.Assert(!needDeclaration); Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol)); Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol)); return (Cci.IMethodReference)GetCciAdapter(methodSymbol); } else if (!needDeclaration) { bool methodIsGeneric = methodSymbol.IsGenericMethod; bool typeIsGeneric = IsGenericType(container); if (methodIsGeneric || typeIsGeneric) { if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { return (Cci.IMethodReference)reference; } if (methodIsGeneric) { if (typeIsGeneric) { // Specialized and generic instance at the same time. methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol); } else { methodRef = new GenericMethodInstanceReference(methodSymbol); } } else { Debug.Assert(typeIsGeneric); methodRef = new SpecializedMethodReference(methodSymbol); } methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); return methodRef; } else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod }) { methodSymbol = underlyingMethod; } } if (_embeddedTypesManagerOpt != null) { return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } return methodSymbol.GetCciAdapter(); } internal Cci.IMethodReference TranslateOverriddenMethodReference( MethodSymbol methodSymbol, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; if (IsGenericType(container)) { if (methodSymbol.IsDefinition) { object reference; if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { methodRef = (Cci.IMethodReference)reference; } else { methodRef = new SpecializedMethodReference(methodSymbol); methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); } } else { methodRef = new SpecializedMethodReference(methodSymbol); } } else { Debug.Assert(methodSymbol.IsDefinition); if (_embeddedTypesManagerOpt != null) { methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } else { methodRef = methodSymbol.GetCciAdapter(); } } return methodRef; } internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params) { Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct())); bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First()); Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating"); if (!mustBeTranslated) { #if DEBUG return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter()); #else return StaticCast<Cci.IParameterTypeInformation>.From(@params); #endif } return TranslateAll(@params); } private static bool MustBeWrapped(ParameterSymbol param) { // we represent parameters of generic methods as definitions // CCI wants them represented as IParameterTypeInformation // so we need to create a wrapper of parameters iff // 1) parameters are definitions and // 2) container is generic // NOTE: all parameters must always agree on whether they need wrapping if (param.IsDefinition) { var container = param.ContainingSymbol; if (ContainerIsGeneric(container)) { return true; } } return false; } private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params) { var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance(); foreach (var param in @params) { builder.Add(CreateParameterTypeInformationWrapper(param)); } return builder.ToImmutableAndFree(); } private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param) { object reference; Cci.IParameterTypeInformation paramRef; if (_genericInstanceMap.TryGetValue(param, out reference)) { return (Cci.IParameterTypeInformation)reference; } paramRef = new ParameterTypeInformation(param); paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef); return paramRef; } private static bool ContainerIsGeneric(Symbol container) { return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod || IsGenericType(container.ContainingType); } internal Cci.ITypeReference Translate( DynamicTypeSymbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table. // We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter // masquerades the TypeRef as System.Object when used to encode signatures. return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics); } internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol) { return (Cci.IArrayTypeReference)GetCciAdapter(symbol); } internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol) { return (Cci.IPointerTypeReference)GetCciAdapter(symbol); } internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol) { return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol); } /// <summary> /// Set the underlying implementation type for a given fixed-size buffer field. /// </summary> public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field) { if (_fixedImplementationTypes == null) { Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null); } lock (_fixedImplementationTypes) { NamedTypeSymbol result; if (_fixedImplementationTypes.TryGetValue(field, out result)) { return result; } result = new FixedFieldImplementationType(field); _fixedImplementationTypes.Add(field, result); AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter()); return result; } } internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field) { // Note that this method is called only after ALL fixed buffer types have been placed in the map. // At that point the map is all filled in and will not change further. Therefore it is safe to // pull values from the map without locking. NamedTypeSymbol result; var found = _fixedImplementationTypes.TryGetValue(field, out result); Debug.Assert(found); return result; } protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics) { return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter(); } internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute(); internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsReadOnlyAttribute(); } internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsUnmanagedAttribute(); } internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsByRefLikeAttribute(); } /// <summary> /// Given a type <paramref name="type"/>, which is either a nullable reference type OR /// is a constructed type with a nullable reference type present in its type argument tree, /// returns a synthesized NullableAttribute with encoded nullable transforms array. /// </summary> internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var flagsBuilder = ArrayBuilder<byte>.GetInstance(); type.AddNullableTransforms(flagsBuilder); SynthesizedAttributeData attribute; if (!flagsBuilder.Any()) { attribute = null; } else { Debug.Assert(flagsBuilder.All(f => f <= 2)); byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder); if (commonValue != null) { attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault()); } else { NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType)); var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType); attribute = SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, ImmutableArray.Create(new TypedConstant(byteArrayType, value))); } } flagsBuilder.Free(); return attribute; } internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue) { if (nullableValue == nullableContextValue || (nullableContextValue == null && nullableValue == 0)) { return null; } NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); return SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue))); } internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value) { var module = Compilation.SourceModule; if ((object)module != symbol && (object)module != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return SynthesizeNullableContextAttribute( ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value))); } internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute() { return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.ContainsNativeInteger()); if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type); Debug.Assert(builder.Any()); Debug.Assert(builder.Contains(true)); SynthesizedAttributeData attribute; if (builder.Count == 1 && builder[0]) { attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty); } else { NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert((object)booleanType != null); var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments); } builder.Free(); return attribute; } internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal bool ShouldEmitNullablePublicOnlyAttribute() { // No need to look at this.GetNeedsGeneratedAttributes() since those bits are // only set for members generated by the rewriter which are not public. return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly; } internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments); } protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0) { return; } // Don't report any errors. They should be reported during binding. if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null)) { SetNeedsGeneratedAttributes(attribute); } } internal void EnsureIsReadOnlyAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute); } internal void EnsureIsUnmanagedAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute); } internal void EnsureNullableAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute); } internal void EnsureNullableContextAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute); } internal void EnsureNativeIntegerAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute); } public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context) { return GetAdditionalTopLevelTypes() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context) { return GetEmbeddedTypes(context.Diagnostics) #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) { return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics)); } internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { return base.GetEmbeddedTypes(diagnostics.DiagnosticBag); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface { internal abstract class AbstractExtractInterfaceService : ILanguageService { protected abstract Task<SyntaxNode> GetTypeDeclarationAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken); protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList<DocumentId> documentId, INamedTypeSymbol extractedInterfaceSymbol, INamedTypeSymbol typeToExtractFrom, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken); internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions); internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode); public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false); return typeAnalysisResult.CanExtractInterface ? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult)) : ImmutableArray<ExtractInterfaceCodeAction>.Empty; } public async Task<ExtractInterfaceResult> ExtractInterfaceAsync( Document documentWithTypeToExtractFrom, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync( documentWithTypeToExtractFrom, position, TypeDiscoveryRule.TypeDeclaration, cancellationToken).ConfigureAwait(false); if (!typeAnalysisResult.CanExtractInterface) { errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error); return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false); if (typeNode == null) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken) { var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace ? string.Empty : refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString(); var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync( refactoringResult.DocumentToExtractFrom, refactoringResult.TypeToExtractFrom, refactoringResult.ExtractableMembers, containingNamespaceDisplay, cancellationToken).ConfigureAwait(false); if (extractInterfaceOptions.IsCancelled) { return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync( ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var solution = refactoringResult.DocumentToExtractFrom.Project.Solution; var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers)); switch (extractInterfaceOptions.Location) { case ExtractInterfaceOptionsResult.ExtractLocation.NewFile: var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions); return await ExtractInterfaceToNewFileAsync( solution, containingNamespaceDisplay, extractedInterfaceSymbol, refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); case ExtractInterfaceOptionsResult.ExtractLocation.SameFile: return await ExtractInterfaceToSameFileAsync( solution, refactoringResult, extractedInterfaceSymbol, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}"); } } private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync( Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync( symbolMapping.AnnotatedSolution, containingNamespaceDisplay, extractInterfaceOptions.FileName, refactoringResult.DocumentToExtractFrom.Project.Id, refactoringResult.DocumentToExtractFrom.Folders, extractedInterfaceSymbol, refactoringResult.DocumentToExtractFrom, cancellationToken).ConfigureAwait(false); var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedInterfaceDocument.Project.Solution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( completedUnformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: unformattedInterfaceDocument.Id); } private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync( Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { // Track all of the symbols we need to modify, which includes the original type declaration being modified var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id); var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync( document, extractedInterfaceSymbol, symbolMapping, cancellationToken).ConfigureAwait(false); var unformattedSolution = documentWithInterface.Project.Solution; // After the interface is inserted, update the original type to show it implements the new interface var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( unformattedSolutionWithUpdatedType, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id); } internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers, string containingNamespace, CancellationToken cancellationToken) { var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name; var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name)); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers); var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); return service.GetExtractInterfaceOptionsAsync( syntaxFactsService, notificationService, extractableMembers.ToList(), defaultInterfaceName, conflictingTypeNames.ToList(), containingNamespace, generatedNameTypeParameterSuffix, document.Project.Language); } private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken) { // Since code action performs formatting and simplification on a single document, // this ensures that anything marked with formatter or simplifier annotations gets // correctly handled as long as it it's in the listed documents var formattedSolution = unformattedSolution; foreach (var documentId in documentIds) { var document = formattedSolution.GetDocument(documentId); var formattedDocument = await Formatter.FormatAsync( document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var simplifiedDocument = await Simplifier.ReduceAsync( formattedDocument, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); formattedSolution = simplifiedDocument.Project.Solution; } return formattedSolution; } private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync( Solution solution, ImmutableArray<DocumentId> documentIds, SyntaxAnnotation typeNodeAnnotation, INamedTypeSymbol typeToExtractFrom, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken) { // If an interface "INewInterface" is extracted from an interface "IExistingInterface", // then "INewInterface" is not marked as implementing "IExistingInterface" and its // extracted members are also not updated. if (typeToExtractFrom.TypeKind == TypeKind.Interface) { return solution; } var unformattedSolution = solution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(currentRoot, solution.Workspace); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol); var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault(); if (typeDeclaration == null) { continue; } var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration); unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution; // Only update the first instance of the typedeclaration, // since it's not needed in all declarations break; } var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync( unformattedSolution, documentIds, extractedInterfaceSymbol, typeToExtractFrom, includedMembers, symbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); return updatedUnformattedSolution; } private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers); foreach (var member in includedMembers) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true), type: @event.Type, explicitInterfaceImplementations: default, name: @event.Name)); break; case SymbolKind.Method: var method = member as IMethodSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()), returnType: method.ReturnType, refKind: method.RefKind, explicitInterfaceImplementations: default, name: method.Name, typeParameters: method.TypeParameters, parameters: method.Parameters, isInitOnly: method.IsInitOnly)); break; case SymbolKind.Property: var property = member as IPropertySymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()), type: property.Type, refKind: property.RefKind, explicitInterfaceImplementations: default, name: property.Name, parameters: property.Parameters, getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null), setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null), isIndexer: property.IsIndexer)); break; default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); break; } } return interfaceMembers.ToImmutable(); } internal virtual bool IsExtractableMember(ISymbol m) { if (m.IsStatic || m.DeclaredAccessibility != Accessibility.Public || m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public. { return false; } if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod()) { return true; } if (m.Kind == SymbolKind.Property) { var prop = m as IPropertySymbol; return !prop.IsWithEvents && ((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) || (prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public)); } 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface { internal abstract class AbstractExtractInterfaceService : ILanguageService { protected abstract Task<SyntaxNode> GetTypeDeclarationAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken); protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList<DocumentId> documentId, INamedTypeSymbol extractedInterfaceSymbol, INamedTypeSymbol typeToExtractFrom, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken); internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions); internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode); public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false); return typeAnalysisResult.CanExtractInterface ? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult)) : ImmutableArray<ExtractInterfaceCodeAction>.Empty; } public async Task<ExtractInterfaceResult> ExtractInterfaceAsync( Document documentWithTypeToExtractFrom, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync( documentWithTypeToExtractFrom, position, TypeDiscoveryRule.TypeDeclaration, cancellationToken).ConfigureAwait(false); if (!typeAnalysisResult.CanExtractInterface) { errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error); return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false); if (typeNode == null) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken) { var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace ? string.Empty : refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString(); var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync( refactoringResult.DocumentToExtractFrom, refactoringResult.TypeToExtractFrom, refactoringResult.ExtractableMembers, containingNamespaceDisplay, cancellationToken).ConfigureAwait(false); if (extractInterfaceOptions.IsCancelled) { return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync( ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var solution = refactoringResult.DocumentToExtractFrom.Project.Solution; var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers)); switch (extractInterfaceOptions.Location) { case ExtractInterfaceOptionsResult.ExtractLocation.NewFile: var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions); return await ExtractInterfaceToNewFileAsync( solution, containingNamespaceDisplay, extractedInterfaceSymbol, refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); case ExtractInterfaceOptionsResult.ExtractLocation.SameFile: return await ExtractInterfaceToSameFileAsync( solution, refactoringResult, extractedInterfaceSymbol, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}"); } } private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync( Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync( symbolMapping.AnnotatedSolution, containingNamespaceDisplay, extractInterfaceOptions.FileName, refactoringResult.DocumentToExtractFrom.Project.Id, refactoringResult.DocumentToExtractFrom.Folders, extractedInterfaceSymbol, refactoringResult.DocumentToExtractFrom, cancellationToken).ConfigureAwait(false); var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedInterfaceDocument.Project.Solution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( completedUnformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: unformattedInterfaceDocument.Id); } private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync( Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { // Track all of the symbols we need to modify, which includes the original type declaration being modified var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id); var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync( document, extractedInterfaceSymbol, symbolMapping, cancellationToken).ConfigureAwait(false); var unformattedSolution = documentWithInterface.Project.Solution; // After the interface is inserted, update the original type to show it implements the new interface var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( unformattedSolutionWithUpdatedType, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id); } internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers, string containingNamespace, CancellationToken cancellationToken) { var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name; var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name)); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers); var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); return service.GetExtractInterfaceOptionsAsync( syntaxFactsService, notificationService, extractableMembers.ToList(), defaultInterfaceName, conflictingTypeNames.ToList(), containingNamespace, generatedNameTypeParameterSuffix, document.Project.Language); } private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken) { // Since code action performs formatting and simplification on a single document, // this ensures that anything marked with formatter or simplifier annotations gets // correctly handled as long as it it's in the listed documents var formattedSolution = unformattedSolution; foreach (var documentId in documentIds) { var document = formattedSolution.GetDocument(documentId); var formattedDocument = await Formatter.FormatAsync( document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var simplifiedDocument = await Simplifier.ReduceAsync( formattedDocument, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); formattedSolution = simplifiedDocument.Project.Solution; } return formattedSolution; } private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync( Solution solution, ImmutableArray<DocumentId> documentIds, SyntaxAnnotation typeNodeAnnotation, INamedTypeSymbol typeToExtractFrom, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken) { // If an interface "INewInterface" is extracted from an interface "IExistingInterface", // then "INewInterface" is not marked as implementing "IExistingInterface" and its // extracted members are also not updated. if (typeToExtractFrom.TypeKind == TypeKind.Interface) { return solution; } var unformattedSolution = solution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(currentRoot, solution.Workspace); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol); var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault(); if (typeDeclaration == null) { continue; } var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration); unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution; // Only update the first instance of the typedeclaration, // since it's not needed in all declarations break; } var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync( unformattedSolution, documentIds, extractedInterfaceSymbol, typeToExtractFrom, includedMembers, symbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); return updatedUnformattedSolution; } private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers); foreach (var member in includedMembers) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true), type: @event.Type, explicitInterfaceImplementations: default, name: @event.Name)); break; case SymbolKind.Method: var method = member as IMethodSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()), returnType: method.ReturnType, refKind: method.RefKind, explicitInterfaceImplementations: default, name: method.Name, typeParameters: method.TypeParameters, parameters: method.Parameters, isInitOnly: method.IsInitOnly)); break; case SymbolKind.Property: var property = member as IPropertySymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()), type: property.Type, refKind: property.RefKind, explicitInterfaceImplementations: default, name: property.Name, parameters: property.Parameters, getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null), setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null), isIndexer: property.IsIndexer)); break; default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); break; } } return interfaceMembers.ToImmutable(); } internal virtual bool IsExtractableMember(ISymbol m) { if (m.IsStatic || m.DeclaredAccessibility != Accessibility.Public || m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public. { return false; } if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod()) { return true; } if (m.Kind == SymbolKind.Property) { var prop = m as IPropertySymbol; return !prop.IsWithEvents && ((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) || (prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public)); } return false; } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/Core/Extensibility/SignatureHelp/PredefinedSignatureHelpPresenterNames.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.Editor { internal static class PredefinedSignatureHelpPresenterNames { public const string RoslynSignatureHelpPresenter = "Roslyn Signature Help Presenter"; } }
// Licensed to the .NET Foundation under one or more 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.Editor { internal static class PredefinedSignatureHelpPresenterNames { public const string RoslynSignatureHelpPresenter = "Roslyn Signature Help Presenter"; } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Dependencies/Collections/Internal/xlf/Strings.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="../Strings.resx"> <body> <trans-unit id="Arg_ArrayPlusOffTooSmall"> <source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source> <target state="translated">Длина конечного массива недостаточна для копирования всех элементов коллекции. Проверьте индекс и длину массива.</target> <note /> </trans-unit> <trans-unit id="Arg_BogusIComparer"> <source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source> <target state="translated">Не удалось выполнить сортировку, поскольку метод IComparer.Compare() вернул несовместимые результаты. Значение не равно самому себе при сравнении, либо многократное сравнение одного значения с другим значением дает разные результаты. IComparer: "{0}".</target> <note /> </trans-unit> <trans-unit id="Arg_HTCapacityOverflow"> <source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source> <target state="translated">Хэш-таблица переполнена и ее емкость стала отрицательной. Проверьте коэффициент загрузки, емкость и текущий размер таблицы.</target> <note /> </trans-unit> <trans-unit id="Arg_KeyNotFoundWithKey"> <source>The given key '{0}' was not present in the dictionary.</source> <target state="translated">Указанный ключ "{0}" отсутствует в словаре.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanDestArray"> <source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source> <target state="translated">Длина результирующего массива недостаточна. Проверьте индекс, длину и нижние границы результирующего массива.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanSrcArray"> <source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source> <target state="translated">Длина исходного массива недостаточна. Проверьте индекс, длину и нижние границы исходного массива.</target> <note /> </trans-unit> <trans-unit id="Arg_NonZeroLowerBound"> <source>The lower bound of target array must be zero.</source> <target state="translated">Нижняя граница целевого массива должна равняться нулю.</target> <note /> </trans-unit> <trans-unit id="Arg_RankMultiDimNotSupported"> <source>Only single dimensional arrays are supported for the requested action.</source> <target state="translated">Для запрашиваемого действия поддерживаются только одномерные массивы.</target> <note /> </trans-unit> <trans-unit id="Arg_WrongType"> <source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source> <target state="translated">Типом значения "{0}" не является "{1}", поэтому оно не может быть использовано в данной базовой коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength"> <source>Object is not a array with the same number of elements as the array to compare it to.</source> <target state="translated">Объект не является массивом с тем же количество элементов, как сравниваемый массив.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ArrayLB"> <source>Number was less than the array's lower bound in the first dimension.</source> <target state="translated">Число было меньше нижней границы массива в первом измерении.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_BiggerThanCollection"> <source>Larger than collection size.</source> <target state="translated">Больше размера коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Count"> <source>Count must be positive and count must refer to a location within the string/array/collection.</source> <target state="translated">Номер должен быть положительным и указывать на местоположение внутри строки/массива/коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Index"> <source>Index was out of range. Must be non-negative and less than the size of the collection.</source> <target state="translated">Индекс за пределами диапазона. Индекс должен быть положительным числом, а его размер не должен превышать размер коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ListInsert"> <source>Index must be within the bounds of the List.</source> <target state="translated">Индекс должен находиться в границах этого списка.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_NeedNonNegNum"> <source>Non-negative number required.</source> <target state="translated">Требуется неотрицательное число.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_SmallCapacity"> <source>capacity was less than the current size.</source> <target state="translated">емкость меньше текущего размера.</target> <note /> </trans-unit> <trans-unit id="Argument_AddingDuplicateWithKey"> <source>An item with the same key has already been added. Key: {0}</source> <target state="translated">Элемент с таким же ключом уже добавлен. Ключ: {0}</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidArrayType"> <source>Target array type is not compatible with the type of items in the collection.</source> <target state="translated">Тип целевого массива несовместим с типом элементов в коллекции.</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidOffLen"> <source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source> <target state="translated">Смещение и длина вышли за границы массива или значение счетчика превышает количество элементов от указателя до конца исходной коллекции.</target> <note /> </trans-unit> <trans-unit id="CannotFindOldValue"> <source>Cannot find the old value</source> <target state="translated">Не удается найти старое значение</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported"> <source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source> <target state="translated">Операции, которые изменяют коллекции, не обрабатываемые параллельно, должны иметь монопольный доступ. В этой коллекции было выполнено параллельное обновление, и ее состояние повреждено. Состояние коллекции больше не является достоверным.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumFailedVersion"> <source>Collection was modified; enumeration operation may not execute.</source> <target state="translated">Коллекция была изменена; невозможно выполнить операцию перечисления.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumOpCantHappen"> <source>Enumeration has either not started or has already finished.</source> <target state="translated">Перечисление не запущено или уже завершено.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_IComparerFailed"> <source>Failed to compare two elements in the array.</source> <target state="translated">Сбой при сравнении двух элементов массива.</target> <note /> </trans-unit> <trans-unit id="NotSupported_FixedSizeCollection"> <source>Collection was of a fixed size.</source> <target state="translated">Коллекция имела фиксированный размер.</target> <note /> </trans-unit> <trans-unit id="NotSupported_KeyCollectionSet"> <source>Mutating a key collection derived from a dictionary is not allowed.</source> <target state="translated">Изменение коллекции ключей, полученных из словаря, запрещено.</target> <note /> </trans-unit> <trans-unit id="NotSupported_ValueCollectionSet"> <source>Mutating a value collection derived from a dictionary is not allowed.</source> <target state="translated">Изменение коллекции значений, полученных из словаря, запрещено.</target> <note /> </trans-unit> <trans-unit id="Rank_MustMatch"> <source>The specified arrays must have the same number of dimensions.</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="../Strings.resx"> <body> <trans-unit id="Arg_ArrayPlusOffTooSmall"> <source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source> <target state="translated">Длина конечного массива недостаточна для копирования всех элементов коллекции. Проверьте индекс и длину массива.</target> <note /> </trans-unit> <trans-unit id="Arg_BogusIComparer"> <source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source> <target state="translated">Не удалось выполнить сортировку, поскольку метод IComparer.Compare() вернул несовместимые результаты. Значение не равно самому себе при сравнении, либо многократное сравнение одного значения с другим значением дает разные результаты. IComparer: "{0}".</target> <note /> </trans-unit> <trans-unit id="Arg_HTCapacityOverflow"> <source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source> <target state="translated">Хэш-таблица переполнена и ее емкость стала отрицательной. Проверьте коэффициент загрузки, емкость и текущий размер таблицы.</target> <note /> </trans-unit> <trans-unit id="Arg_KeyNotFoundWithKey"> <source>The given key '{0}' was not present in the dictionary.</source> <target state="translated">Указанный ключ "{0}" отсутствует в словаре.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanDestArray"> <source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source> <target state="translated">Длина результирующего массива недостаточна. Проверьте индекс, длину и нижние границы результирующего массива.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanSrcArray"> <source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source> <target state="translated">Длина исходного массива недостаточна. Проверьте индекс, длину и нижние границы исходного массива.</target> <note /> </trans-unit> <trans-unit id="Arg_NonZeroLowerBound"> <source>The lower bound of target array must be zero.</source> <target state="translated">Нижняя граница целевого массива должна равняться нулю.</target> <note /> </trans-unit> <trans-unit id="Arg_RankMultiDimNotSupported"> <source>Only single dimensional arrays are supported for the requested action.</source> <target state="translated">Для запрашиваемого действия поддерживаются только одномерные массивы.</target> <note /> </trans-unit> <trans-unit id="Arg_WrongType"> <source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source> <target state="translated">Типом значения "{0}" не является "{1}", поэтому оно не может быть использовано в данной базовой коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength"> <source>Object is not a array with the same number of elements as the array to compare it to.</source> <target state="translated">Объект не является массивом с тем же количество элементов, как сравниваемый массив.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ArrayLB"> <source>Number was less than the array's lower bound in the first dimension.</source> <target state="translated">Число было меньше нижней границы массива в первом измерении.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_BiggerThanCollection"> <source>Larger than collection size.</source> <target state="translated">Больше размера коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Count"> <source>Count must be positive and count must refer to a location within the string/array/collection.</source> <target state="translated">Номер должен быть положительным и указывать на местоположение внутри строки/массива/коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Index"> <source>Index was out of range. Must be non-negative and less than the size of the collection.</source> <target state="translated">Индекс за пределами диапазона. Индекс должен быть положительным числом, а его размер не должен превышать размер коллекции.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ListInsert"> <source>Index must be within the bounds of the List.</source> <target state="translated">Индекс должен находиться в границах этого списка.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_NeedNonNegNum"> <source>Non-negative number required.</source> <target state="translated">Требуется неотрицательное число.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_SmallCapacity"> <source>capacity was less than the current size.</source> <target state="translated">емкость меньше текущего размера.</target> <note /> </trans-unit> <trans-unit id="Argument_AddingDuplicateWithKey"> <source>An item with the same key has already been added. Key: {0}</source> <target state="translated">Элемент с таким же ключом уже добавлен. Ключ: {0}</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidArrayType"> <source>Target array type is not compatible with the type of items in the collection.</source> <target state="translated">Тип целевого массива несовместим с типом элементов в коллекции.</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidOffLen"> <source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source> <target state="translated">Смещение и длина вышли за границы массива или значение счетчика превышает количество элементов от указателя до конца исходной коллекции.</target> <note /> </trans-unit> <trans-unit id="CannotFindOldValue"> <source>Cannot find the old value</source> <target state="translated">Не удается найти старое значение</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported"> <source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source> <target state="translated">Операции, которые изменяют коллекции, не обрабатываемые параллельно, должны иметь монопольный доступ. В этой коллекции было выполнено параллельное обновление, и ее состояние повреждено. Состояние коллекции больше не является достоверным.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumFailedVersion"> <source>Collection was modified; enumeration operation may not execute.</source> <target state="translated">Коллекция была изменена; невозможно выполнить операцию перечисления.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumOpCantHappen"> <source>Enumeration has either not started or has already finished.</source> <target state="translated">Перечисление не запущено или уже завершено.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_IComparerFailed"> <source>Failed to compare two elements in the array.</source> <target state="translated">Сбой при сравнении двух элементов массива.</target> <note /> </trans-unit> <trans-unit id="NotSupported_FixedSizeCollection"> <source>Collection was of a fixed size.</source> <target state="translated">Коллекция имела фиксированный размер.</target> <note /> </trans-unit> <trans-unit id="NotSupported_KeyCollectionSet"> <source>Mutating a key collection derived from a dictionary is not allowed.</source> <target state="translated">Изменение коллекции ключей, полученных из словаря, запрещено.</target> <note /> </trans-unit> <trans-unit id="NotSupported_ValueCollectionSet"> <source>Mutating a value collection derived from a dictionary is not allowed.</source> <target state="translated">Изменение коллекции значений, полученных из словаря, запрещено.</target> <note /> </trans-unit> <trans-unit id="Rank_MustMatch"> <source>The specified arrays must have the same number of dimensions.</source> <target state="translated">Число измерений заданных массивов должно совпадать.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Symbols/ParameterSymbol.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.Runtime.InteropServices; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a parameter of a method or indexer. /// </summary> internal abstract partial class ParameterSymbol : Symbol, IParameterSymbolInternal { internal const string ValueParameterName = "value"; internal ParameterSymbol() { } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual ParameterSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Gets the type of the parameter along with its annotations. /// </summary> public abstract TypeWithAnnotations TypeWithAnnotations { get; } /// <summary> /// Gets the type of the parameter. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; /// <summary> /// Determines if the parameter ref, out or neither. /// </summary> public abstract RefKind RefKind { get; } /// <summary> /// Returns true if the parameter is a discard parameter. /// </summary> public abstract bool IsDiscard { get; } /// <summary> /// Custom modifiers associated with the ref modifier, or an empty array if there are none. /// </summary> public abstract ImmutableArray<CustomModifier> RefCustomModifiers { get; } /// <summary> /// Describes how the parameter is marshalled when passed to native code. /// Null if no specific marshalling information is available for the parameter. /// </summary> /// <remarks>PE symbols don't provide this information and always return null.</remarks> internal abstract MarshalPseudoCustomAttributeData MarshallingInformation { get; } /// <summary> /// Returns the marshalling type of this parameter, or 0 if marshalling information isn't available. /// </summary> /// <remarks> /// By default this information is extracted from <see cref="MarshallingInformation"/> if available. /// Since the compiler does only need to know the marshalling type of symbols that aren't emitted /// PE symbols just decode the type from metadata and don't provide full marshalling information. /// </remarks> internal virtual UnmanagedType MarshallingType { get { var info = MarshallingInformation; return info != null ? info.UnmanagedType : 0; } } internal bool IsMarshalAsObject { get { switch (this.MarshallingType) { case UnmanagedType.Interface: case UnmanagedType.IUnknown: case Cci.Constants.UnmanagedType_IDispatch: return true; } return false; } } /// <summary> /// Gets the ordinal position of the parameter. The first parameter has ordinal zero. /// The "'this' parameter has ordinal -1. /// </summary> public abstract int Ordinal { get; } /// <summary> /// Returns true if the parameter was declared as a parameter array. /// Note: it is possible for any parameter to have the [ParamArray] attribute (for instance, in IL), /// even if it is not the last parameter. So check for that. /// </summary> public abstract bool IsParams { get; } /// <summary> /// Returns true if the parameter is semantically optional. /// </summary> /// <remarks> /// True if and only if the parameter has a default argument syntax, /// or the parameter is not a params-array and Optional metadata flag is set. /// </remarks> public bool IsOptional { get { // DEV10 COMPATIBILITY: Special handling for ParameterArray params // // Ideally we should not need the additional "isParams" check below // as a ParameterArray param cannot have a default value. // However, for certain cases of overriding this is not true. // See test "CodeGenTests.NoDefaultForParams_Dev10781558" for an example. // See Roslyn bug 10753 and Dev10 bug 781558 for details. // // To maintain compatibility with Dev10, we allow such code to compile but explicitly // classify a ParameterArray param as a required parameter. // // Also when we call f() where signature of f is void([Optional]params int[] args) // an empty array is created and passed to f. // // We also do not consider ref/out parameters as optional, unless in COM interop scenarios // and only for ref. RefKind refKind; return !IsParams && IsMetadataOptional && ((refKind = RefKind) == RefKind.None || (refKind == RefKind.In) || (refKind == RefKind.Ref && ContainingSymbol.ContainingType.IsComImport)); } } /// <summary> /// True if Optional flag is set in metadata. /// </summary> internal abstract bool IsMetadataOptional { get; } /// <summary> /// True if In flag is set in metadata. /// </summary> internal abstract bool IsMetadataIn { get; } /// <summary> /// True if Out flag is set in metadata. /// </summary> internal abstract bool IsMetadataOut { get; } /// <summary> /// Returns true if the parameter explicitly specifies a default value to be passed /// when no value is provided as an argument to a call. /// </summary> /// <remarks> /// True if the parameter has a default argument syntax, /// or the parameter is from source and <see cref="DefaultParameterValueAttribute"/> is applied, /// or the parameter is from metadata and HasDefault metadata flag is set. See /// <see cref="IsOptional"/> to determine if the parameter will be considered optional by /// overload resolution. /// /// The default value can be obtained with <see cref="ExplicitDefaultValue"/> property. /// </remarks> public bool HasExplicitDefaultValue { get { // In the symbol model, only optional parameters have default values. // Internally, however, non-optional parameters may also have default // values (accessible via DefaultConstantValue). For example, if the // DefaultParameterValue attribute is applied to a non-optional parameter // we still want to emit a default parameter value, even if it isn't // recognized by the language. // Special Case: params parameters are never optional, but can have // default values (e.g. if the params-ness is inherited from an // overridden method, but the current method declares the parameter // as optional). In such cases, dev11 emits the default value. return IsOptional && ExplicitDefaultConstantValue != null; } } /// <summary> /// Returns the default value of the parameter. If <see cref="HasExplicitDefaultValue"/> /// returns false then DefaultValue throws an InvalidOperationException. /// </summary> /// <remarks> /// If the parameter type is a struct and the default value of the parameter /// is the default value of the struct type or of type parameter type which is /// not known to be a referenced type, then this property will return null. /// </remarks> /// <exception cref="InvalidOperationException">The parameter has no default value.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object ExplicitDefaultValue { get { if (HasExplicitDefaultValue) { return ExplicitDefaultConstantValue.Value; } throw new InvalidOperationException(); } } #nullable enable /// <summary> /// Returns the default value constant of the parameter, /// or null if the parameter doesn't have a default value or /// the parameter type is a struct and the default value of the parameter /// is the default value of the struct type or of type parameter type which is /// not known to be a referenced type. /// </summary> /// <remarks> /// This is used for emitting. It does not reflect the language semantics /// (i.e. even non-optional parameters can have default values). /// </remarks> internal abstract ConstantValue? ExplicitDefaultConstantValue { get; } #nullable disable /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Parameter; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitParameter(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitParameter(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitParameter(this); } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <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 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 override bool IsSealed { get { return false; } } /// <summary> /// Returns true if this symbol is "virtual", has an implementation, and does not override a /// base class member; i.e., declared with the "virtual" modifier. Does not return true for /// members declared as abstract or override. /// </summary> public override bool IsVirtual { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member; i.e., declared /// with the "override" modifier. Still returns true if member was declared to override /// something, but (erroneously) no member to override exists. /// </summary> public override bool IsOverride { get { return false; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public override bool IsStatic { get { return false; } } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// "extern" modifier. /// </summary> public override bool IsExtern { get { return false; } } /// <summary> /// Returns true if the parameter is the hidden 'this' parameter. /// </summary> public virtual bool IsThis { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } internal abstract bool IsIDispatchConstant { get; } internal abstract bool IsIUnknownConstant { get; } internal abstract bool IsCallerFilePath { get; } internal abstract bool IsCallerLineNumber { get; } internal abstract bool IsCallerMemberName { get; } internal abstract int CallerArgumentExpressionParameterIndex { get; } internal abstract FlowAnalysisAnnotations FlowAnalysisAnnotations { get; } internal abstract ImmutableHashSet<string> NotNullIfParameterNotNull { get; } /// <summary> /// Indexes of the parameters that will be passed to the constructor of the interpolated string handler type /// when an interpolated string handler conversion occurs. These indexes are ordered in the order to be passed /// to the constructor. /// <para/> /// Indexes greater than or equal to 0 are references to parameters defined on the containing method or indexer. /// Indexes less than 0 are constants defined on <see cref="BoundInterpolatedStringArgumentPlaceholder"/>. /// </summary> internal abstract ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes { get; } /// <summary> /// True if the parameter is attributed with <c>InterpolatedStringHandlerArgumentAttribute</c> and the attribute /// has some error (such as invalid names). /// </summary> internal abstract bool HasInterpolatedStringHandlerArgumentError { get; } protected sealed override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { UseSiteInfo<AssemblySymbol> info = default; DeriveUseSiteInfoFromParameter(ref info, this); return info.DiagnosticInfo?.Code == (int)ErrorCode.ERR_BogusType; } } protected override ISymbol CreateISymbol() { return new PublicModel.ParameterSymbol(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a parameter of a method or indexer. /// </summary> internal abstract partial class ParameterSymbol : Symbol, IParameterSymbolInternal { internal const string ValueParameterName = "value"; internal ParameterSymbol() { } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual ParameterSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Gets the type of the parameter along with its annotations. /// </summary> public abstract TypeWithAnnotations TypeWithAnnotations { get; } /// <summary> /// Gets the type of the parameter. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; /// <summary> /// Determines if the parameter ref, out or neither. /// </summary> public abstract RefKind RefKind { get; } /// <summary> /// Returns true if the parameter is a discard parameter. /// </summary> public abstract bool IsDiscard { get; } /// <summary> /// Custom modifiers associated with the ref modifier, or an empty array if there are none. /// </summary> public abstract ImmutableArray<CustomModifier> RefCustomModifiers { get; } /// <summary> /// Describes how the parameter is marshalled when passed to native code. /// Null if no specific marshalling information is available for the parameter. /// </summary> /// <remarks>PE symbols don't provide this information and always return null.</remarks> internal abstract MarshalPseudoCustomAttributeData MarshallingInformation { get; } /// <summary> /// Returns the marshalling type of this parameter, or 0 if marshalling information isn't available. /// </summary> /// <remarks> /// By default this information is extracted from <see cref="MarshallingInformation"/> if available. /// Since the compiler does only need to know the marshalling type of symbols that aren't emitted /// PE symbols just decode the type from metadata and don't provide full marshalling information. /// </remarks> internal virtual UnmanagedType MarshallingType { get { var info = MarshallingInformation; return info != null ? info.UnmanagedType : 0; } } internal bool IsMarshalAsObject { get { switch (this.MarshallingType) { case UnmanagedType.Interface: case UnmanagedType.IUnknown: case Cci.Constants.UnmanagedType_IDispatch: return true; } return false; } } /// <summary> /// Gets the ordinal position of the parameter. The first parameter has ordinal zero. /// The "'this' parameter has ordinal -1. /// </summary> public abstract int Ordinal { get; } /// <summary> /// Returns true if the parameter was declared as a parameter array. /// Note: it is possible for any parameter to have the [ParamArray] attribute (for instance, in IL), /// even if it is not the last parameter. So check for that. /// </summary> public abstract bool IsParams { get; } /// <summary> /// Returns true if the parameter is semantically optional. /// </summary> /// <remarks> /// True if and only if the parameter has a default argument syntax, /// or the parameter is not a params-array and Optional metadata flag is set. /// </remarks> public bool IsOptional { get { // DEV10 COMPATIBILITY: Special handling for ParameterArray params // // Ideally we should not need the additional "isParams" check below // as a ParameterArray param cannot have a default value. // However, for certain cases of overriding this is not true. // See test "CodeGenTests.NoDefaultForParams_Dev10781558" for an example. // See Roslyn bug 10753 and Dev10 bug 781558 for details. // // To maintain compatibility with Dev10, we allow such code to compile but explicitly // classify a ParameterArray param as a required parameter. // // Also when we call f() where signature of f is void([Optional]params int[] args) // an empty array is created and passed to f. // // We also do not consider ref/out parameters as optional, unless in COM interop scenarios // and only for ref. RefKind refKind; return !IsParams && IsMetadataOptional && ((refKind = RefKind) == RefKind.None || (refKind == RefKind.In) || (refKind == RefKind.Ref && ContainingSymbol.ContainingType.IsComImport)); } } /// <summary> /// True if Optional flag is set in metadata. /// </summary> internal abstract bool IsMetadataOptional { get; } /// <summary> /// True if In flag is set in metadata. /// </summary> internal abstract bool IsMetadataIn { get; } /// <summary> /// True if Out flag is set in metadata. /// </summary> internal abstract bool IsMetadataOut { get; } /// <summary> /// Returns true if the parameter explicitly specifies a default value to be passed /// when no value is provided as an argument to a call. /// </summary> /// <remarks> /// True if the parameter has a default argument syntax, /// or the parameter is from source and <see cref="DefaultParameterValueAttribute"/> is applied, /// or the parameter is from metadata and HasDefault metadata flag is set. See /// <see cref="IsOptional"/> to determine if the parameter will be considered optional by /// overload resolution. /// /// The default value can be obtained with <see cref="ExplicitDefaultValue"/> property. /// </remarks> public bool HasExplicitDefaultValue { get { // In the symbol model, only optional parameters have default values. // Internally, however, non-optional parameters may also have default // values (accessible via DefaultConstantValue). For example, if the // DefaultParameterValue attribute is applied to a non-optional parameter // we still want to emit a default parameter value, even if it isn't // recognized by the language. // Special Case: params parameters are never optional, but can have // default values (e.g. if the params-ness is inherited from an // overridden method, but the current method declares the parameter // as optional). In such cases, dev11 emits the default value. return IsOptional && ExplicitDefaultConstantValue != null; } } /// <summary> /// Returns the default value of the parameter. If <see cref="HasExplicitDefaultValue"/> /// returns false then DefaultValue throws an InvalidOperationException. /// </summary> /// <remarks> /// If the parameter type is a struct and the default value of the parameter /// is the default value of the struct type or of type parameter type which is /// not known to be a referenced type, then this property will return null. /// </remarks> /// <exception cref="InvalidOperationException">The parameter has no default value.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object ExplicitDefaultValue { get { if (HasExplicitDefaultValue) { return ExplicitDefaultConstantValue.Value; } throw new InvalidOperationException(); } } #nullable enable /// <summary> /// Returns the default value constant of the parameter, /// or null if the parameter doesn't have a default value or /// the parameter type is a struct and the default value of the parameter /// is the default value of the struct type or of type parameter type which is /// not known to be a referenced type. /// </summary> /// <remarks> /// This is used for emitting. It does not reflect the language semantics /// (i.e. even non-optional parameters can have default values). /// </remarks> internal abstract ConstantValue? ExplicitDefaultConstantValue { get; } #nullable disable /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Parameter; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitParameter(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitParameter(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitParameter(this); } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <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 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 override bool IsSealed { get { return false; } } /// <summary> /// Returns true if this symbol is "virtual", has an implementation, and does not override a /// base class member; i.e., declared with the "virtual" modifier. Does not return true for /// members declared as abstract or override. /// </summary> public override bool IsVirtual { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member; i.e., declared /// with the "override" modifier. Still returns true if member was declared to override /// something, but (erroneously) no member to override exists. /// </summary> public override bool IsOverride { get { return false; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public override bool IsStatic { get { return false; } } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// "extern" modifier. /// </summary> public override bool IsExtern { get { return false; } } /// <summary> /// Returns true if the parameter is the hidden 'this' parameter. /// </summary> public virtual bool IsThis { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } internal abstract bool IsIDispatchConstant { get; } internal abstract bool IsIUnknownConstant { get; } internal abstract bool IsCallerFilePath { get; } internal abstract bool IsCallerLineNumber { get; } internal abstract bool IsCallerMemberName { get; } internal abstract int CallerArgumentExpressionParameterIndex { get; } internal abstract FlowAnalysisAnnotations FlowAnalysisAnnotations { get; } internal abstract ImmutableHashSet<string> NotNullIfParameterNotNull { get; } /// <summary> /// Indexes of the parameters that will be passed to the constructor of the interpolated string handler type /// when an interpolated string handler conversion occurs. These indexes are ordered in the order to be passed /// to the constructor. /// <para/> /// Indexes greater than or equal to 0 are references to parameters defined on the containing method or indexer. /// Indexes less than 0 are constants defined on <see cref="BoundInterpolatedStringArgumentPlaceholder"/>. /// </summary> internal abstract ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes { get; } /// <summary> /// True if the parameter is attributed with <c>InterpolatedStringHandlerArgumentAttribute</c> and the attribute /// has some error (such as invalid names). /// </summary> internal abstract bool HasInterpolatedStringHandlerArgumentError { get; } protected sealed override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { UseSiteInfo<AssemblySymbol> info = default; DeriveUseSiteInfoFromParameter(ref info, this); return info.DiagnosticInfo?.Code == (int)ErrorCode.ERR_BogusType; } } protected override ISymbol CreateISymbol() { return new PublicModel.ParameterSymbol(this); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.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="cs" original="../AnalyzersResources.resx"> <body> <trans-unit id="A_source_file_contains_a_header_that_does_not_match_the_required_text"> <source>A source file contains a header that does not match the required text</source> <target state="translated">Zdrojový soubor obsahuje hlavičku, která neodpovídá požadovanému textu.</target> <note /> </trans-unit> <trans-unit id="A_source_file_is_missing_a_required_header"> <source>A source file is missing a required header.</source> <target state="translated">Ve zdrojovém souboru chybí požadovaná hlavička.</target> <note /> </trans-unit> <trans-unit id="Accessibility_modifiers_required"> <source>Accessibility modifiers required</source> <target state="translated">Vyžadují se modifikátory dostupnosti.</target> <note /> </trans-unit> <trans-unit id="Add_accessibility_modifiers"> <source>Add accessibility modifiers</source> <target state="translated">Přidat Modifikátory dostupnosti</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_for_clarity"> <source>Add parentheses for clarity</source> <target state="translated">Přidat závorky kvůli srozumitelnosti</target> <note /> </trans-unit> <trans-unit id="Add_readonly_modifier"> <source>Add readonly modifier</source> <target state="translated">Přidat modifikátor jen pro čtení</target> <note /> </trans-unit> <trans-unit id="Add_this_or_Me_qualification"> <source>Add 'this' or 'Me' qualification.</source> <target state="translated">Přidat kvalifikaci „this“ nebo „Me“</target> <note /> </trans-unit> <trans-unit id="Avoid_legacy_format_target_0_in_SuppressMessageAttribute"> <source>Avoid legacy format target '{0}' in 'SuppressMessageAttribute'</source> <target state="translated">Vyhněte se starému cíli formátu {0} v SuppressMessageAttribute.</target> <note /> </trans-unit> <trans-unit id="Avoid_legacy_format_target_in_SuppressMessageAttribute"> <source>Avoid legacy format target in 'SuppressMessageAttribute'</source> <target state="translated">Vyhněte se starému cíli formátu v SuppressMessageAttribute.</target> <note /> </trans-unit> <trans-unit id="Avoid_multiple_blank_lines"> <source>Avoid multiple blank lines</source> <target state="translated">Nepoužívejte několik prázdných řádků.</target> <note /> </trans-unit> <trans-unit id="Avoid_unnecessary_value_assignments_in_your_code_as_these_likely_indicate_redundant_value_computations_If_the_value_computation_is_not_redundant_and_you_intend_to_retain_the_assignmentcomma_then_change_the_assignment_target_to_a_local_variable_whose_name_starts_with_an_underscore_and_is_optionally_followed_by_an_integercomma_such_as___comma__1_comma__2_comma_etc"> <source>Avoid unnecessary value assignments in your code, as these likely indicate redundant value computations. If the value computation is not redundant and you intend to retain the assignment, then change the assignment target to a local variable whose name starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source> <target state="translated">Vyhněte se v kódu přiřazením nepotřebných hodnot, protože ta pravděpodobně indikují nadbytečné výpočty hodnot. Pokud výpočet hodnoty není nadbytečný a chcete dané přiřazení zachovat, změňte cíl přiřazení na místní proměnnou, jejíž název začíná podtržítkem, za kterým volitelně následuje celé číslo, například _, _1, _2 atd. Tyto řetězce se považují za názvy speciálních symbolů pro vyřazení.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters_in_your_code_If_the_parameter_cannot_be_removed_then_change_its_name_so_it_starts_with_an_underscore_and_is_optionally_followed_by_an_integer_such_as__comma__1_comma__2_etc_These_are_treated_as_special_discard_symbol_names"> <source>Avoid unused parameters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source> <target state="translated">Vyhněte se v kódu nepoužitým parametrům. Pokud parametr nelze odebrat, změňte jeho název tak, aby začínal podtržítkem, za kterým volitelně následuje celé číslo, například _, _1, _2 atd. Tyto řetězce se považují za názvy speciálních symbolů pro vyřazení.</target> <note /> </trans-unit> <trans-unit id="Blank_line_required_between_block_and_subsequent_statement"> <source>Blank line required between block and subsequent statement</source> <target state="translated">Mezi blokem a následným příkazem se vyžaduje prázdný řádek.</target> <note /> </trans-unit> <trans-unit id="Change_namespace_to_match_folder_structure"> <source>Change namespace to match folder structure</source> <target state="translated">Změnit namespace tak, aby odpovídal struktuře složek</target> <note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note> </trans-unit> <trans-unit id="Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime"> <source>Changes to expression trees may result in behavior changes at runtime</source> <target state="translated">Změny ve stromech výrazů můžou způsobit změny chování za běhu.</target> <note /> </trans-unit> <trans-unit id="Conditional_expression_can_be_simplified"> <source>Conditional expression can be simplified</source> <target state="translated">Podmínka může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Convert_to_conditional_expression"> <source>Convert to conditional expression</source> <target state="translated">Převést na podmíněný výraz</target> <note /> </trans-unit> <trans-unit id="Expression_value_is_never_used"> <source>Expression value is never used</source> <target state="translated">Hodnota výrazu se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Collection_initialization_can_be_simplified"> <source>Collection initialization can be simplified</source> <target state="translated">Inicializace kolekce může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Format_string_contains_invalid_placeholder"> <source>Format string contains invalid placeholder</source> <target state="translated">Formátovací řetězec obsahuje neplatný zástupný symbol.</target> <note /> </trans-unit> <trans-unit id="GetHashCode_implementation_can_be_simplified"> <source>'GetHashCode' implementation can be simplified</source> <target state="translated">Implementace GetHashCode může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Interpolation_can_be_simplified"> <source>Interpolation can be simplified</source> <target state="translated">Interpolace může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Invalid_format_string"> <source>Invalid format string</source> <target state="translated">Neplatný formátovací řetězec</target> <note /> </trans-unit> <trans-unit id="Invalid_global_SuppressMessageAttribute"> <source>Invalid global 'SuppressMessageAttribute'</source> <target state="translated">Neplatný globální atribut SuppressMessageAttribute</target> <note /> </trans-unit> <trans-unit id="Invalid_or_missing_target_for_SuppressMessageAttribute"> <source>Invalid or missing target for 'SuppressMessageAttribute'</source> <target state="translated">Atribut SuppressMessageAttribute není platný nebo pro něj chybí cíl.</target> <note /> </trans-unit> <trans-unit id="Invalid_scope_for_SuppressMessageAttribute"> <source>Invalid scope for 'SuppressMessageAttribute'</source> <target state="translated">Neplatný obor pro SuppressMessageAttribute</target> <note /> </trans-unit> <trans-unit id="Make_field_readonly"> <source>Make field readonly</source> <target state="translated">Nastavit pole jen pro čtení</target> <note /> </trans-unit> <trans-unit id="Member_access_should_be_qualified"> <source>Member access should be qualified.</source> <target state="translated">Přístup členů by měl být kvalifikovaný.</target> <note /> </trans-unit> <trans-unit id="Add_missing_cases"> <source>Add missing cases</source> <target state="translated">Přidat chybějící malá a velká písmena</target> <note /> </trans-unit> <trans-unit id="Member_name_can_be_simplified"> <source>Member name can be simplified</source> <target state="translated">Název člena může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="Modifiers_are_not_ordered"> <source>Modifiers are not ordered</source> <target state="translated">Modifikátory nejsou seřazené.</target> <note /> </trans-unit> <trans-unit id="Namespace_0_does_not_match_folder_structure_expected_1"> <source>Namespace "{0}" does not match folder structure, expected "{1}"</source> <target state="translated">Namespace {0} neodpovídá struktuře složek, očekávalo se {1}.</target> <note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note> </trans-unit> <trans-unit id="Namespace_does_not_match_folder_structure"> <source>Namespace does not match folder structure</source> <target state="translated">Namespace neodpovídá struktuře složek.</target> <note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note> </trans-unit> <trans-unit id="Naming_Styles"> <source>Naming Styles</source> <target state="translated">Styly pojmenování</target> <note /> </trans-unit> <trans-unit id="Naming_rule_violation_0"> <source>Naming rule violation: {0}</source> <target state="translated">Porušení pravidla pojmenování: {0}</target> <note>{0} is the rule title, {1} is the way in which the rule was violated</note> </trans-unit> <trans-unit id="Null_check_can_be_simplified"> <source>Null check can be simplified</source> <target state="translated">Kontrola hodnot null může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Order_modifiers"> <source>Order modifiers</source> <target state="translated">Seřadit modifikátory</target> <note /> </trans-unit> <trans-unit id="Parameter_0_can_be_removed_if_it_is_not_part_of_a_shipped_public_API_its_initial_value_is_never_used"> <source>Parameter '{0}' can be removed if it is not part of a shipped public API; its initial value is never used</source> <target state="translated">Parametr {0} je možné odebrat, pokud není součástí dodaného veřejného rozhraní API. Jeho počáteční hodnota se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Parameter_0_can_be_removed_its_initial_value_is_never_used"> <source>Parameter '{0}' can be removed; its initial value is never used</source> <target state="translated">Parametr {0} je možné odebrat, jeho počáteční hodnota se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Object_initialization_can_be_simplified"> <source>Object initialization can be simplified</source> <target state="translated">Inicializace objektu může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Parentheses_can_be_removed"> <source>Parentheses can be removed</source> <target state="translated">Je možné odebrat závorky.</target> <note /> </trans-unit> <trans-unit id="Parentheses_should_be_added_for_clarity"> <source>Parentheses should be added for clarity</source> <target state="translated">Kvůli srozumitelnosti by se měly přidat závorky.</target> <note /> </trans-unit> <trans-unit id="Populate_switch"> <source>Populate switch</source> <target state="translated">Naplnit přepínač</target> <note /> </trans-unit> <trans-unit id="Prefer_explicitly_provided_tuple_element_name"> <source>Prefer explicitly provided tuple element name</source> <target state="translated">Preferovat výslovně zadaný název prvku řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="Private_member_0_can_be_removed_as_the_value_assigned_to_it_is_never_read"> <source>Private member '{0}' can be removed as the value assigned to it is never read</source> <target state="translated">Soukromý člen {0} se může odebrat, jeho přiřazená hodnota se nikdy nečte.</target> <note /> </trans-unit> <trans-unit id="Private_member_0_is_unused"> <source>Private member '{0}' is unused</source> <target state="translated">Soukromý člen {0} se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Private_method_0_can_be_removed_as_it_is_never_invoked"> <source>Private method '{0}' can be removed as it is never invoked.</source> <target state="translated">Soukromá metoda {0} se může odebrat, protože se nikdy nevolá.</target> <note /> </trans-unit> <trans-unit id="Private_property_0_can_be_converted_to_a_method_as_its_get_accessor_is_never_invoked"> <source>Private property '{0}' can be converted to a method as its get accessor is never invoked.</source> <target state="translated">Privátní vlastnost {0} se dá převést na metodu, protože její přístupový objekt get se nikdy nevyvolá.</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Cast"> <source>Remove Unnecessary Cast</source> <target state="translated">Odebrat nepotřebné přetypování</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_equality"> <source>Remove redundant equality</source> <target state="translated">Odebrat nadbytečnou rovnost</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_parentheses"> <source>Remove unnecessary parentheses</source> <target state="translated">Odebrat nadbytečné závorky</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression"> <source>Remove unnecessary suppression</source> <target state="translated">Odebrat nepotřebné potlačení</target> <note /> </trans-unit> <trans-unit id="Remove_unread_private_members"> <source>Remove unread private members</source> <target state="translated">Odebrat nepřečtené soukromé členy</target> <note /> </trans-unit> <trans-unit id="Remove_unused_member"> <source>Remove unused member</source> <target state="translated">Odebrat nepoužitý člen</target> <note /> </trans-unit> <trans-unit id="Remove_unused_parameter"> <source>Remove unused parameter</source> <target state="translated">Odebrat nepoužívaný parametr</target> <note /> </trans-unit> <trans-unit id="Remove_unused_parameter_0"> <source>Remove unused parameter '{0}'</source> <target state="translated">Odebrat nepoužívaný parametr {0}</target> <note /> </trans-unit> <trans-unit id="Remove_unused_parameter_0_if_it_is_not_part_of_a_shipped_public_API"> <source>Remove unused parameter '{0}' if it is not part of a shipped public API</source> <target state="translated">Odeberte nepoužívaný parametr {0}, pokud není součástí dodávaného veřejného rozhraní API.</target> <note /> </trans-unit> <trans-unit id="Remove_unused_private_members"> <source>Remove unused private members</source> <target state="translated">Odebrat nepoužité soukromé členy</target> <note /> </trans-unit> <trans-unit id="Simplify_LINQ_expression"> <source>Simplify LINQ expression</source> <target state="translated">Zjednodušit výraz LINQ</target> <note /> </trans-unit> <trans-unit id="Simplify_collection_initialization"> <source>Simplify collection initialization</source> <target state="translated">Zjednodušit inicializaci kolekce</target> <note /> </trans-unit> <trans-unit id="Simplify_conditional_expression"> <source>Simplify conditional expression</source> <target state="translated">Zjednodušit podmíněný výraz</target> <note /> </trans-unit> <trans-unit id="Simplify_interpolation"> <source>Simplify interpolation</source> <target state="translated">Zjednodušit interpolaci</target> <note /> </trans-unit> <trans-unit id="Simplify_object_initialization"> <source>Simplify object initialization</source> <target state="translated">Zjednodušit inicializaci objektu</target> <note /> </trans-unit> <trans-unit id="The_file_header_does_not_match_the_required_text"> <source>The file header does not match the required text</source> <target state="translated">Hlavička souboru neodpovídá požadovanému textu.</target> <note /> </trans-unit> <trans-unit id="The_file_header_is_missing_or_not_located_at_the_top_of_the_file"> <source>The file header is missing or not located at the top of the file</source> <target state="translated">Hlavička souboru chybí, nebo není umístěná na začátku souboru.</target> <note /> </trans-unit> <trans-unit id="Unnecessary_assignment_of_a_value"> <source>Unnecessary assignment of a value</source> <target state="translated">Nepotřebné přiřazení hodnoty</target> <note /> </trans-unit> <trans-unit id="Unnecessary_assignment_of_a_value_to_0"> <source>Unnecessary assignment of a value to '{0}'</source> <target state="translated">Nepotřebné přiřazení hodnoty do {0}</target> <note /> </trans-unit> <trans-unit id="Use_System_HashCode"> <source>Use 'System.HashCode'</source> <target state="translated">Použijte System.HashCode.</target> <note /> </trans-unit> <trans-unit id="Use_auto_property"> <source>Use auto property</source> <target state="translated">Použít automatickou vlastnost</target> <note /> </trans-unit> <trans-unit id="Use_coalesce_expression"> <source>Use coalesce expression</source> <target state="translated">Použít slučovací výraz</target> <note /> </trans-unit> <trans-unit id="Use_compound_assignment"> <source>Use compound assignment</source> <target state="translated">Použít složené přiřazení</target> <note /> </trans-unit> <trans-unit id="Use_decrement_operator"> <source>Use '--' operator</source> <target state="translated">Použijte operátor --.</target> <note /> </trans-unit> <trans-unit id="Use_explicitly_provided_tuple_name"> <source>Use explicitly provided tuple name</source> <target state="translated">Použít výslovně zadaný název řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="Use_increment_operator"> <source>Use '++' operator</source> <target state="translated">Použijte operátor ++.</target> <note /> </trans-unit> <trans-unit id="Use_inferred_member_name"> <source>Use inferred member name</source> <target state="translated">Použít odvozený název člena</target> <note /> </trans-unit> <trans-unit id="Use_null_propagation"> <source>Use null propagation</source> <target state="translated">Použít šíření hodnot null</target> <note /> </trans-unit> <trans-unit id="Use_throw_expression"> <source>Use 'throw' expression</source> <target state="translated">Použít výraz throw</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="cs" original="../AnalyzersResources.resx"> <body> <trans-unit id="A_source_file_contains_a_header_that_does_not_match_the_required_text"> <source>A source file contains a header that does not match the required text</source> <target state="translated">Zdrojový soubor obsahuje hlavičku, která neodpovídá požadovanému textu.</target> <note /> </trans-unit> <trans-unit id="A_source_file_is_missing_a_required_header"> <source>A source file is missing a required header.</source> <target state="translated">Ve zdrojovém souboru chybí požadovaná hlavička.</target> <note /> </trans-unit> <trans-unit id="Accessibility_modifiers_required"> <source>Accessibility modifiers required</source> <target state="translated">Vyžadují se modifikátory dostupnosti.</target> <note /> </trans-unit> <trans-unit id="Add_accessibility_modifiers"> <source>Add accessibility modifiers</source> <target state="translated">Přidat Modifikátory dostupnosti</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_for_clarity"> <source>Add parentheses for clarity</source> <target state="translated">Přidat závorky kvůli srozumitelnosti</target> <note /> </trans-unit> <trans-unit id="Add_readonly_modifier"> <source>Add readonly modifier</source> <target state="translated">Přidat modifikátor jen pro čtení</target> <note /> </trans-unit> <trans-unit id="Add_this_or_Me_qualification"> <source>Add 'this' or 'Me' qualification.</source> <target state="translated">Přidat kvalifikaci „this“ nebo „Me“</target> <note /> </trans-unit> <trans-unit id="Avoid_legacy_format_target_0_in_SuppressMessageAttribute"> <source>Avoid legacy format target '{0}' in 'SuppressMessageAttribute'</source> <target state="translated">Vyhněte se starému cíli formátu {0} v SuppressMessageAttribute.</target> <note /> </trans-unit> <trans-unit id="Avoid_legacy_format_target_in_SuppressMessageAttribute"> <source>Avoid legacy format target in 'SuppressMessageAttribute'</source> <target state="translated">Vyhněte se starému cíli formátu v SuppressMessageAttribute.</target> <note /> </trans-unit> <trans-unit id="Avoid_multiple_blank_lines"> <source>Avoid multiple blank lines</source> <target state="translated">Nepoužívejte několik prázdných řádků.</target> <note /> </trans-unit> <trans-unit id="Avoid_unnecessary_value_assignments_in_your_code_as_these_likely_indicate_redundant_value_computations_If_the_value_computation_is_not_redundant_and_you_intend_to_retain_the_assignmentcomma_then_change_the_assignment_target_to_a_local_variable_whose_name_starts_with_an_underscore_and_is_optionally_followed_by_an_integercomma_such_as___comma__1_comma__2_comma_etc"> <source>Avoid unnecessary value assignments in your code, as these likely indicate redundant value computations. If the value computation is not redundant and you intend to retain the assignment, then change the assignment target to a local variable whose name starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source> <target state="translated">Vyhněte se v kódu přiřazením nepotřebných hodnot, protože ta pravděpodobně indikují nadbytečné výpočty hodnot. Pokud výpočet hodnoty není nadbytečný a chcete dané přiřazení zachovat, změňte cíl přiřazení na místní proměnnou, jejíž název začíná podtržítkem, za kterým volitelně následuje celé číslo, například _, _1, _2 atd. Tyto řetězce se považují za názvy speciálních symbolů pro vyřazení.</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters_in_your_code_If_the_parameter_cannot_be_removed_then_change_its_name_so_it_starts_with_an_underscore_and_is_optionally_followed_by_an_integer_such_as__comma__1_comma__2_etc_These_are_treated_as_special_discard_symbol_names"> <source>Avoid unused parameters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source> <target state="translated">Vyhněte se v kódu nepoužitým parametrům. Pokud parametr nelze odebrat, změňte jeho název tak, aby začínal podtržítkem, za kterým volitelně následuje celé číslo, například _, _1, _2 atd. Tyto řetězce se považují za názvy speciálních symbolů pro vyřazení.</target> <note /> </trans-unit> <trans-unit id="Blank_line_required_between_block_and_subsequent_statement"> <source>Blank line required between block and subsequent statement</source> <target state="translated">Mezi blokem a následným příkazem se vyžaduje prázdný řádek.</target> <note /> </trans-unit> <trans-unit id="Change_namespace_to_match_folder_structure"> <source>Change namespace to match folder structure</source> <target state="translated">Změnit namespace tak, aby odpovídal struktuře složek</target> <note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note> </trans-unit> <trans-unit id="Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime"> <source>Changes to expression trees may result in behavior changes at runtime</source> <target state="translated">Změny ve stromech výrazů můžou způsobit změny chování za běhu.</target> <note /> </trans-unit> <trans-unit id="Conditional_expression_can_be_simplified"> <source>Conditional expression can be simplified</source> <target state="translated">Podmínka může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Convert_to_conditional_expression"> <source>Convert to conditional expression</source> <target state="translated">Převést na podmíněný výraz</target> <note /> </trans-unit> <trans-unit id="Expression_value_is_never_used"> <source>Expression value is never used</source> <target state="translated">Hodnota výrazu se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Collection_initialization_can_be_simplified"> <source>Collection initialization can be simplified</source> <target state="translated">Inicializace kolekce může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Format_string_contains_invalid_placeholder"> <source>Format string contains invalid placeholder</source> <target state="translated">Formátovací řetězec obsahuje neplatný zástupný symbol.</target> <note /> </trans-unit> <trans-unit id="GetHashCode_implementation_can_be_simplified"> <source>'GetHashCode' implementation can be simplified</source> <target state="translated">Implementace GetHashCode může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Interpolation_can_be_simplified"> <source>Interpolation can be simplified</source> <target state="translated">Interpolace může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Invalid_format_string"> <source>Invalid format string</source> <target state="translated">Neplatný formátovací řetězec</target> <note /> </trans-unit> <trans-unit id="Invalid_global_SuppressMessageAttribute"> <source>Invalid global 'SuppressMessageAttribute'</source> <target state="translated">Neplatný globální atribut SuppressMessageAttribute</target> <note /> </trans-unit> <trans-unit id="Invalid_or_missing_target_for_SuppressMessageAttribute"> <source>Invalid or missing target for 'SuppressMessageAttribute'</source> <target state="translated">Atribut SuppressMessageAttribute není platný nebo pro něj chybí cíl.</target> <note /> </trans-unit> <trans-unit id="Invalid_scope_for_SuppressMessageAttribute"> <source>Invalid scope for 'SuppressMessageAttribute'</source> <target state="translated">Neplatný obor pro SuppressMessageAttribute</target> <note /> </trans-unit> <trans-unit id="Make_field_readonly"> <source>Make field readonly</source> <target state="translated">Nastavit pole jen pro čtení</target> <note /> </trans-unit> <trans-unit id="Member_access_should_be_qualified"> <source>Member access should be qualified.</source> <target state="translated">Přístup členů by měl být kvalifikovaný.</target> <note /> </trans-unit> <trans-unit id="Add_missing_cases"> <source>Add missing cases</source> <target state="translated">Přidat chybějící malá a velká písmena</target> <note /> </trans-unit> <trans-unit id="Member_name_can_be_simplified"> <source>Member name can be simplified</source> <target state="translated">Název člena může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="Modifiers_are_not_ordered"> <source>Modifiers are not ordered</source> <target state="translated">Modifikátory nejsou seřazené.</target> <note /> </trans-unit> <trans-unit id="Namespace_0_does_not_match_folder_structure_expected_1"> <source>Namespace "{0}" does not match folder structure, expected "{1}"</source> <target state="translated">Namespace {0} neodpovídá struktuře složek, očekávalo se {1}.</target> <note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note> </trans-unit> <trans-unit id="Namespace_does_not_match_folder_structure"> <source>Namespace does not match folder structure</source> <target state="translated">Namespace neodpovídá struktuře složek.</target> <note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note> </trans-unit> <trans-unit id="Naming_Styles"> <source>Naming Styles</source> <target state="translated">Styly pojmenování</target> <note /> </trans-unit> <trans-unit id="Naming_rule_violation_0"> <source>Naming rule violation: {0}</source> <target state="translated">Porušení pravidla pojmenování: {0}</target> <note>{0} is the rule title, {1} is the way in which the rule was violated</note> </trans-unit> <trans-unit id="Null_check_can_be_simplified"> <source>Null check can be simplified</source> <target state="translated">Kontrola hodnot null může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Order_modifiers"> <source>Order modifiers</source> <target state="translated">Seřadit modifikátory</target> <note /> </trans-unit> <trans-unit id="Parameter_0_can_be_removed_if_it_is_not_part_of_a_shipped_public_API_its_initial_value_is_never_used"> <source>Parameter '{0}' can be removed if it is not part of a shipped public API; its initial value is never used</source> <target state="translated">Parametr {0} je možné odebrat, pokud není součástí dodaného veřejného rozhraní API. Jeho počáteční hodnota se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Parameter_0_can_be_removed_its_initial_value_is_never_used"> <source>Parameter '{0}' can be removed; its initial value is never used</source> <target state="translated">Parametr {0} je možné odebrat, jeho počáteční hodnota se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Object_initialization_can_be_simplified"> <source>Object initialization can be simplified</source> <target state="translated">Inicializace objektu může být zjednodušená.</target> <note /> </trans-unit> <trans-unit id="Parentheses_can_be_removed"> <source>Parentheses can be removed</source> <target state="translated">Je možné odebrat závorky.</target> <note /> </trans-unit> <trans-unit id="Parentheses_should_be_added_for_clarity"> <source>Parentheses should be added for clarity</source> <target state="translated">Kvůli srozumitelnosti by se měly přidat závorky.</target> <note /> </trans-unit> <trans-unit id="Populate_switch"> <source>Populate switch</source> <target state="translated">Naplnit přepínač</target> <note /> </trans-unit> <trans-unit id="Prefer_explicitly_provided_tuple_element_name"> <source>Prefer explicitly provided tuple element name</source> <target state="translated">Preferovat výslovně zadaný název prvku řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="Private_member_0_can_be_removed_as_the_value_assigned_to_it_is_never_read"> <source>Private member '{0}' can be removed as the value assigned to it is never read</source> <target state="translated">Soukromý člen {0} se může odebrat, jeho přiřazená hodnota se nikdy nečte.</target> <note /> </trans-unit> <trans-unit id="Private_member_0_is_unused"> <source>Private member '{0}' is unused</source> <target state="translated">Soukromý člen {0} se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="Private_method_0_can_be_removed_as_it_is_never_invoked"> <source>Private method '{0}' can be removed as it is never invoked.</source> <target state="translated">Soukromá metoda {0} se může odebrat, protože se nikdy nevolá.</target> <note /> </trans-unit> <trans-unit id="Private_property_0_can_be_converted_to_a_method_as_its_get_accessor_is_never_invoked"> <source>Private property '{0}' can be converted to a method as its get accessor is never invoked.</source> <target state="translated">Privátní vlastnost {0} se dá převést na metodu, protože její přístupový objekt get se nikdy nevyvolá.</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Cast"> <source>Remove Unnecessary Cast</source> <target state="translated">Odebrat nepotřebné přetypování</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_equality"> <source>Remove redundant equality</source> <target state="translated">Odebrat nadbytečnou rovnost</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_parentheses"> <source>Remove unnecessary parentheses</source> <target state="translated">Odebrat nadbytečné závorky</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression"> <source>Remove unnecessary suppression</source> <target state="translated">Odebrat nepotřebné potlačení</target> <note /> </trans-unit> <trans-unit id="Remove_unread_private_members"> <source>Remove unread private members</source> <target state="translated">Odebrat nepřečtené soukromé členy</target> <note /> </trans-unit> <trans-unit id="Remove_unused_member"> <source>Remove unused member</source> <target state="translated">Odebrat nepoužitý člen</target> <note /> </trans-unit> <trans-unit id="Remove_unused_parameter"> <source>Remove unused parameter</source> <target state="translated">Odebrat nepoužívaný parametr</target> <note /> </trans-unit> <trans-unit id="Remove_unused_parameter_0"> <source>Remove unused parameter '{0}'</source> <target state="translated">Odebrat nepoužívaný parametr {0}</target> <note /> </trans-unit> <trans-unit id="Remove_unused_parameter_0_if_it_is_not_part_of_a_shipped_public_API"> <source>Remove unused parameter '{0}' if it is not part of a shipped public API</source> <target state="translated">Odeberte nepoužívaný parametr {0}, pokud není součástí dodávaného veřejného rozhraní API.</target> <note /> </trans-unit> <trans-unit id="Remove_unused_private_members"> <source>Remove unused private members</source> <target state="translated">Odebrat nepoužité soukromé členy</target> <note /> </trans-unit> <trans-unit id="Simplify_LINQ_expression"> <source>Simplify LINQ expression</source> <target state="translated">Zjednodušit výraz LINQ</target> <note /> </trans-unit> <trans-unit id="Simplify_collection_initialization"> <source>Simplify collection initialization</source> <target state="translated">Zjednodušit inicializaci kolekce</target> <note /> </trans-unit> <trans-unit id="Simplify_conditional_expression"> <source>Simplify conditional expression</source> <target state="translated">Zjednodušit podmíněný výraz</target> <note /> </trans-unit> <trans-unit id="Simplify_interpolation"> <source>Simplify interpolation</source> <target state="translated">Zjednodušit interpolaci</target> <note /> </trans-unit> <trans-unit id="Simplify_object_initialization"> <source>Simplify object initialization</source> <target state="translated">Zjednodušit inicializaci objektu</target> <note /> </trans-unit> <trans-unit id="The_file_header_does_not_match_the_required_text"> <source>The file header does not match the required text</source> <target state="translated">Hlavička souboru neodpovídá požadovanému textu.</target> <note /> </trans-unit> <trans-unit id="The_file_header_is_missing_or_not_located_at_the_top_of_the_file"> <source>The file header is missing or not located at the top of the file</source> <target state="translated">Hlavička souboru chybí, nebo není umístěná na začátku souboru.</target> <note /> </trans-unit> <trans-unit id="Unnecessary_assignment_of_a_value"> <source>Unnecessary assignment of a value</source> <target state="translated">Nepotřebné přiřazení hodnoty</target> <note /> </trans-unit> <trans-unit id="Unnecessary_assignment_of_a_value_to_0"> <source>Unnecessary assignment of a value to '{0}'</source> <target state="translated">Nepotřebné přiřazení hodnoty do {0}</target> <note /> </trans-unit> <trans-unit id="Use_System_HashCode"> <source>Use 'System.HashCode'</source> <target state="translated">Použijte System.HashCode.</target> <note /> </trans-unit> <trans-unit id="Use_auto_property"> <source>Use auto property</source> <target state="translated">Použít automatickou vlastnost</target> <note /> </trans-unit> <trans-unit id="Use_coalesce_expression"> <source>Use coalesce expression</source> <target state="translated">Použít slučovací výraz</target> <note /> </trans-unit> <trans-unit id="Use_compound_assignment"> <source>Use compound assignment</source> <target state="translated">Použít složené přiřazení</target> <note /> </trans-unit> <trans-unit id="Use_decrement_operator"> <source>Use '--' operator</source> <target state="translated">Použijte operátor --.</target> <note /> </trans-unit> <trans-unit id="Use_explicitly_provided_tuple_name"> <source>Use explicitly provided tuple name</source> <target state="translated">Použít výslovně zadaný název řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="Use_increment_operator"> <source>Use '++' operator</source> <target state="translated">Použijte operátor ++.</target> <note /> </trans-unit> <trans-unit id="Use_inferred_member_name"> <source>Use inferred member name</source> <target state="translated">Použít odvozený název člena</target> <note /> </trans-unit> <trans-unit id="Use_null_propagation"> <source>Use null propagation</source> <target state="translated">Použít šíření hodnot null</target> <note /> </trans-unit> <trans-unit id="Use_throw_expression"> <source>Use 'throw' expression</source> <target state="translated">Použít výraz throw</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/CSharpTest/UseInterpolatedVerbatimString/UseInterpolatedVerbatimStringCodeFixTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseInterpolatedVerbatimString; 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.UseInterpolatedVerbatimString { [Trait(Traits.Feature, Traits.Features.CodeActionsUseInterpolatedVerbatimString)] public class CSharpUseInterpolatedVerbatimStringCodeFixTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpUseInterpolatedVerbatimStringCodeFixTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUseInterpolatedVerbatimStringCodeFixProvider()); [Fact] public async Task Simple() { await TestInRegularAndScript1Async( @"class C { void M() { var s = @[||]$""hello""; } }", @"class C { void M() { var s = $@""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task AfterString() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var s = @$""hello""[||]; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task InCall() { await TestInRegularAndScript1Async( @"class C { void M(string x) { var s = M(@[||]$""hello""); } }", @"class C { void M(string x) { var s = M($@""hello""); } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task FixAllInDocument() { await TestInRegularAndScript1Async( @"class C { void M() { var s = {|FixAllInDocument:@$""|}hello""; var s2 = @$""hello""; } }", @"class C { void M() { var s = $@""hello""; var s2 = $@""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task MissingOnInterpolatedVerbatimString() { await TestMissingAsync( @"class C { void M() { var s = $[||]@""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task MissingInCSharp8() { await TestMissingAsync( @"class C { void M() { var s = @[||]$""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp8))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseInterpolatedVerbatimString; 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.UseInterpolatedVerbatimString { [Trait(Traits.Feature, Traits.Features.CodeActionsUseInterpolatedVerbatimString)] public class CSharpUseInterpolatedVerbatimStringCodeFixTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpUseInterpolatedVerbatimStringCodeFixTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUseInterpolatedVerbatimStringCodeFixProvider()); [Fact] public async Task Simple() { await TestInRegularAndScript1Async( @"class C { void M() { var s = @[||]$""hello""; } }", @"class C { void M() { var s = $@""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task AfterString() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var s = @$""hello""[||]; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task InCall() { await TestInRegularAndScript1Async( @"class C { void M(string x) { var s = M(@[||]$""hello""); } }", @"class C { void M(string x) { var s = M($@""hello""); } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task FixAllInDocument() { await TestInRegularAndScript1Async( @"class C { void M() { var s = {|FixAllInDocument:@$""|}hello""; var s2 = @$""hello""; } }", @"class C { void M() { var s = $@""hello""; var s2 = $@""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task MissingOnInterpolatedVerbatimString() { await TestMissingAsync( @"class C { void M() { var s = $[||]@""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact] public async Task MissingInCSharp8() { await TestMissingAsync( @"class C { void M() { var s = @[||]$""hello""; } }", parameters: new TestParameters().WithParseOptions(new CSharpParseOptions(LanguageVersion.CSharp8))); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/Syntax/LexicalAndXml/DisabledRegionTests.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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DisabledRegionTests : CSharpTestBase { [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledError_DiagnosticsAndEffect() { var source = @" #if false #error ""error1"" #endif #error ""error2"" class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_ErrorDirective, @"""error2""").WithArguments(@"""error2""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledWarning_DiagnosticsAndEffect() { var source = @" #if false #warning ""warning1"" #endif #warning ""warning2"" class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.WRN_WarningDirective, @"""warning2""").WithArguments(@"""warning2""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledLine_Diagnostics() { var source = @" #if false #line #line 0 #endif #line #line 0 class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_InvalidLineNumber, ""), Diagnostic(ErrorCode.ERR_InvalidLineNumber, "0")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledPragma_Diagnostics() { var source = @" #if false #pragma #pragma warning #pragma warning disable ""something"" #pragma warning disable 0 #pragma warning disable -1 #pragma checksum #pragma checksum ""file"" #pragma checksum ""file"" ""guid"" #pragma checksum ""file"" ""guid"" ""bytes"" #endif #pragma #pragma warning #pragma warning disable ""something2"" #pragma warning disable 1 #pragma warning disable -2 #pragma checksum #pragma checksum ""file"" #pragma checksum ""file"" ""guid"" #pragma checksum ""file"" ""guid"" ""bytes"" class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.WRN_IllegalPragma, ""), Diagnostic(ErrorCode.WRN_IllegalPPWarning, ""), Diagnostic(ErrorCode.WRN_IdentifierOrNumericLiteralExpected, "\"something2\""), Diagnostic(ErrorCode.WRN_IdentifierOrNumericLiteralExpected, "-"), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, ""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, ""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, @"""guid"""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, ""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, @"""guid"""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, @"""bytes""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledReference_Diagnostics() { var source = @" #if false #r #endif #r class C { } "; ParserErrorMessageTests.ParseAndValidate(source, TestOptions.Script, Diagnostic(ErrorCode.ERR_ExpectedPPFile, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledDefine_Effect() { var source = @" #if false #define goo #endif #if goo #warning ""warning"" #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledDefine_Diagnostics() { var source = @" #if false #define #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_IdentifierExpected, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledUndef_Effect() { var source = @" #define goo #if false #undef goo #endif #if goo #warning ""warning"" #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.WRN_WarningDirective, @"""warning""").WithArguments(@"""warning""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledUndef_Diagnostics() { var source = @" #if false #undef #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_IdentifierExpected, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledRegion_Diagnostics() { var source = @" #if false #region #endif class C { } "; // CONSIDER: it would be nicer not to double-report this. // (It's happening because the #endif doesn't pop the region // off the directive stack, so it's still there when we clean // up.) // NOTE: we deliberately suppress the "missing endif" that // dev10 would have reported - we only report the first error // when unwinding the stack. ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_EndRegionDirectiveExpected, "#endif"), Diagnostic(ErrorCode.ERR_EndRegionDirectiveExpected, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledEndRegion_Diagnostics() { var source = @" #if false #endregion #endif class C { } "; // Deliberately refined from ERR_UnexpectedDirective in Dev10. ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_EndifDirectiveExpected, "#endregion")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledIf_Effect() { var source = @" #if false #if true #error error #endif #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledIf_Diagnostics() { var source = @" #if false #if true #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_EndifDirectiveExpected, "")); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DisabledRegionTests : CSharpTestBase { [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledError_DiagnosticsAndEffect() { var source = @" #if false #error ""error1"" #endif #error ""error2"" class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_ErrorDirective, @"""error2""").WithArguments(@"""error2""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledWarning_DiagnosticsAndEffect() { var source = @" #if false #warning ""warning1"" #endif #warning ""warning2"" class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.WRN_WarningDirective, @"""warning2""").WithArguments(@"""warning2""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledLine_Diagnostics() { var source = @" #if false #line #line 0 #endif #line #line 0 class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_InvalidLineNumber, ""), Diagnostic(ErrorCode.ERR_InvalidLineNumber, "0")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledPragma_Diagnostics() { var source = @" #if false #pragma #pragma warning #pragma warning disable ""something"" #pragma warning disable 0 #pragma warning disable -1 #pragma checksum #pragma checksum ""file"" #pragma checksum ""file"" ""guid"" #pragma checksum ""file"" ""guid"" ""bytes"" #endif #pragma #pragma warning #pragma warning disable ""something2"" #pragma warning disable 1 #pragma warning disable -2 #pragma checksum #pragma checksum ""file"" #pragma checksum ""file"" ""guid"" #pragma checksum ""file"" ""guid"" ""bytes"" class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.WRN_IllegalPragma, ""), Diagnostic(ErrorCode.WRN_IllegalPPWarning, ""), Diagnostic(ErrorCode.WRN_IdentifierOrNumericLiteralExpected, "\"something2\""), Diagnostic(ErrorCode.WRN_IdentifierOrNumericLiteralExpected, "-"), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, ""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, ""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, @"""guid"""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, ""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, @"""guid"""), Diagnostic(ErrorCode.WRN_IllegalPPChecksum, @"""bytes""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledReference_Diagnostics() { var source = @" #if false #r #endif #r class C { } "; ParserErrorMessageTests.ParseAndValidate(source, TestOptions.Script, Diagnostic(ErrorCode.ERR_ExpectedPPFile, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledDefine_Effect() { var source = @" #if false #define goo #endif #if goo #warning ""warning"" #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledDefine_Diagnostics() { var source = @" #if false #define #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_IdentifierExpected, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledUndef_Effect() { var source = @" #define goo #if false #undef goo #endif #if goo #warning ""warning"" #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.WRN_WarningDirective, @"""warning""").WithArguments(@"""warning""")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledUndef_Diagnostics() { var source = @" #if false #undef #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_IdentifierExpected, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledRegion_Diagnostics() { var source = @" #if false #region #endif class C { } "; // CONSIDER: it would be nicer not to double-report this. // (It's happening because the #endif doesn't pop the region // off the directive stack, so it's still there when we clean // up.) // NOTE: we deliberately suppress the "missing endif" that // dev10 would have reported - we only report the first error // when unwinding the stack. ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_EndRegionDirectiveExpected, "#endif"), Diagnostic(ErrorCode.ERR_EndRegionDirectiveExpected, "")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledEndRegion_Diagnostics() { var source = @" #if false #endregion #endif class C { } "; // Deliberately refined from ERR_UnexpectedDirective in Dev10. ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_EndifDirectiveExpected, "#endregion")); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledIf_Effect() { var source = @" #if false #if true #error error #endif #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledIf_Diagnostics() { var source = @" #if false #if true #endif class C { } "; ParserErrorMessageTests.ParseAndValidate(source, Diagnostic(ErrorCode.ERR_EndifDirectiveExpected, "")); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/EditorFeatures/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeGeneration { [UseExportProvider] public class SyntaxGeneratorTests { [Fact] public async Task TestNameOfBindsWithoutErrors() { var g = CSharpSyntaxGenerator.Instance; using var workspace = TestWorkspace.CreateCSharp(@" class C { string M() { return ""a""; } }"); var solution = workspace.CurrentSolution; var document = solution.Projects.Single().Documents.Single(); var root = await document.GetSyntaxRootAsync(); // validate that if we change `return "a";` to `return nameof(M);` that this binds // without a problem. We need to do special work in SyntaxGenerator.NameOfExpression to // make this happen. var statement = root.DescendantNodes().Single(n => n is ReturnStatementSyntax); var replacement = g.ReturnStatement(g.NameOfExpression(g.IdentifierName("M"))); var newRoot = root.ReplaceNode(statement, replacement); var newDocument = document.WithSyntaxRoot(newRoot); var semanticModel = await newDocument.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); } [Fact] public async Task TestNameOfBindsWithoutErrors_SpeculativeModel() { var g = CSharpSyntaxGenerator.Instance; using var workspace = TestWorkspace.CreateCSharp(@" class C { string M() { return ""a""; } }"); var solution = workspace.CurrentSolution; var document = solution.Projects.Single().Documents.Single(); var root = await document.GetSyntaxRootAsync(); // validate that if we change `return "a";` to `return nameof(M);` that this binds // without a problem. We need to do special work in SyntaxGenerator.NameOfExpression to // make this happen. var statement = root.DescendantNodes().Single(n => n is ReturnStatementSyntax); var semanticModel = await document.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); var replacement = (ReturnStatementSyntax)g.ReturnStatement(g.NameOfExpression(g.IdentifierName("M"))); Assert.True(semanticModel.TryGetSpeculativeSemanticModel( statement.SpanStart, replacement, out var speculativeModel)); // Make sure even in the speculative model that the compiler understands that this is a // the special `nameof` construct. var typeInfo = speculativeModel.GetTypeInfo(replacement.Expression); Assert.Equal(SpecialType.System_String, typeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, typeInfo.ConvertedType.SpecialType); var constantValue = speculativeModel.GetConstantValue(replacement.Expression); Assert.True(constantValue.HasValue); Assert.Equal("M", constantValue.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeGeneration { [UseExportProvider] public class SyntaxGeneratorTests { [Fact] public async Task TestNameOfBindsWithoutErrors() { var g = CSharpSyntaxGenerator.Instance; using var workspace = TestWorkspace.CreateCSharp(@" class C { string M() { return ""a""; } }"); var solution = workspace.CurrentSolution; var document = solution.Projects.Single().Documents.Single(); var root = await document.GetSyntaxRootAsync(); // validate that if we change `return "a";` to `return nameof(M);` that this binds // without a problem. We need to do special work in SyntaxGenerator.NameOfExpression to // make this happen. var statement = root.DescendantNodes().Single(n => n is ReturnStatementSyntax); var replacement = g.ReturnStatement(g.NameOfExpression(g.IdentifierName("M"))); var newRoot = root.ReplaceNode(statement, replacement); var newDocument = document.WithSyntaxRoot(newRoot); var semanticModel = await newDocument.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); } [Fact] public async Task TestNameOfBindsWithoutErrors_SpeculativeModel() { var g = CSharpSyntaxGenerator.Instance; using var workspace = TestWorkspace.CreateCSharp(@" class C { string M() { return ""a""; } }"); var solution = workspace.CurrentSolution; var document = solution.Projects.Single().Documents.Single(); var root = await document.GetSyntaxRootAsync(); // validate that if we change `return "a";` to `return nameof(M);` that this binds // without a problem. We need to do special work in SyntaxGenerator.NameOfExpression to // make this happen. var statement = root.DescendantNodes().Single(n => n is ReturnStatementSyntax); var semanticModel = await document.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); var replacement = (ReturnStatementSyntax)g.ReturnStatement(g.NameOfExpression(g.IdentifierName("M"))); Assert.True(semanticModel.TryGetSpeculativeSemanticModel( statement.SpanStart, replacement, out var speculativeModel)); // Make sure even in the speculative model that the compiler understands that this is a // the special `nameof` construct. var typeInfo = speculativeModel.GetTypeInfo(replacement.Expression); Assert.Equal(SpecialType.System_String, typeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, typeInfo.ConvertedType.SpecialType); var constantValue = speculativeModel.GetConstantValue(replacement.Expression); Assert.True(constantValue.HasValue); Assert.Equal("M", constantValue.Value); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/CSharp/Test/IOperation/Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests</RootNamespace> <TargetFrameworks>net5.0;net472</TargetFrameworks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests</RootNamespace> <TargetFrameworks>net5.0;net472</TargetFrameworks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/AnalyzerFileWatcherService.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.ComponentModel.Composition; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Export(typeof(AnalyzerFileWatcherService))] internal sealed class AnalyzerFileWatcherService { private static readonly object s_analyzerChangedErrorId = new(); private readonly VisualStudioWorkspaceImpl _workspace; private readonly HostDiagnosticUpdateSource _updateSource; private readonly IVsFileChangeEx _fileChangeService; private readonly Dictionary<string, FileChangeTracker> _fileChangeTrackers = new(StringComparer.OrdinalIgnoreCase); /// <summary> /// Holds a list of assembly modified times that we can use to detect a file change prior to the <see cref="FileChangeTracker"/> being in place. /// Once it's in place and subscribed, we'll remove the entry because any further changes will be detected that way. /// </summary> private readonly Dictionary<string, DateTime> _assemblyUpdatedTimesUtc = new(StringComparer.OrdinalIgnoreCase); private readonly object _guard = new(); private readonly DiagnosticDescriptor _analyzerChangedRule = new( id: IDEDiagnosticIds.AnalyzerChangedId, title: ServicesVSResources.AnalyzerChangedOnDisk, messageFormat: ServicesVSResources.The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted, category: FeaturesResources.Roslyn_HostError, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AnalyzerFileWatcherService( VisualStudioWorkspaceImpl workspace, HostDiagnosticUpdateSource hostDiagnosticUpdateSource, SVsServiceProvider serviceProvider) { _workspace = workspace; _updateSource = hostDiagnosticUpdateSource; _fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx)); } internal void RemoveAnalyzerAlreadyLoadedDiagnostics(ProjectId projectId, string analyzerPath) => _updateSource.ClearDiagnosticsForProject(projectId, Tuple.Create(s_analyzerChangedErrorId, analyzerPath)); private void RaiseAnalyzerChangedWarning(ProjectId projectId, string analyzerPath) { var messageArguments = new string[] { analyzerPath }; var project = _workspace.CurrentSolution.GetProject(projectId); if (project != null && DiagnosticData.TryCreate(_analyzerChangedRule, messageArguments, project, out var diagnostic)) { _updateSource.UpdateDiagnosticsForProject(projectId, Tuple.Create(s_analyzerChangedErrorId, analyzerPath), SpecializedCollections.SingletonEnumerable(diagnostic)); } } private DateTime? GetLastUpdateTimeUtc(string fullPath) { try { var creationTimeUtc = File.GetCreationTimeUtc(fullPath); var writeTimeUtc = File.GetLastWriteTimeUtc(fullPath); return writeTimeUtc > creationTimeUtc ? writeTimeUtc : creationTimeUtc; } catch (IOException) { return null; } catch (UnauthorizedAccessException) { return null; } } internal void TrackFilePathAndReportErrorIfChanged(string filePath, ProjectId projectId) { lock (_guard) { if (!_fileChangeTrackers.TryGetValue(filePath, out var tracker)) { tracker = new FileChangeTracker(_fileChangeService, filePath); tracker.UpdatedOnDisk += Tracker_UpdatedOnDisk; _ = tracker.StartFileChangeListeningAsync(); _fileChangeTrackers.Add(filePath, tracker); } if (_assemblyUpdatedTimesUtc.TryGetValue(filePath, out var assemblyUpdatedTime)) { var currentFileUpdateTime = GetLastUpdateTimeUtc(filePath); if (currentFileUpdateTime != null) { if (currentFileUpdateTime != assemblyUpdatedTime) { RaiseAnalyzerChangedWarning(projectId, filePath); } // If the the tracker is in place, at this point we can stop checking any further for this assembly if (tracker.PreviousCallToStartFileChangeHasAsynchronouslyCompleted) { _assemblyUpdatedTimesUtc.Remove(filePath); } } } else { // We don't have an assembly updated time. This means we either haven't ever checked it, or we have a file watcher in place. // If the file watcher is in place, then nothing further to do. Otherwise we'll add the update time to the map for future checking if (!tracker.PreviousCallToStartFileChangeHasAsynchronouslyCompleted) { var currentFileUpdateTime = GetLastUpdateTimeUtc(filePath); if (currentFileUpdateTime != null) { _assemblyUpdatedTimesUtc[filePath] = currentFileUpdateTime.Value; } } } } } private void Tracker_UpdatedOnDisk(object sender, EventArgs e) { var tracker = (FileChangeTracker)sender; var filePath = tracker.FilePath; lock (_guard) { // Once we've created a diagnostic for a given analyzer file, there's // no need to keep watching it. _fileChangeTrackers.Remove(filePath); } tracker.Dispose(); tracker.UpdatedOnDisk -= Tracker_UpdatedOnDisk; // Traverse the chain of requesting assemblies to get back to the original analyzer // assembly. foreach (var project in _workspace.CurrentSolution.Projects) { var analyzerFileReferences = project.AnalyzerReferences.OfType<AnalyzerFileReference>(); if (analyzerFileReferences.Any(a => a.FullPath.Equals(filePath, StringComparison.OrdinalIgnoreCase))) { RaiseAnalyzerChangedWarning(project.Id, filePath); } } } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Export(typeof(AnalyzerFileWatcherService))] internal sealed class AnalyzerFileWatcherService { private static readonly object s_analyzerChangedErrorId = new(); private readonly VisualStudioWorkspaceImpl _workspace; private readonly HostDiagnosticUpdateSource _updateSource; private readonly IVsFileChangeEx _fileChangeService; private readonly Dictionary<string, FileChangeTracker> _fileChangeTrackers = new(StringComparer.OrdinalIgnoreCase); /// <summary> /// Holds a list of assembly modified times that we can use to detect a file change prior to the <see cref="FileChangeTracker"/> being in place. /// Once it's in place and subscribed, we'll remove the entry because any further changes will be detected that way. /// </summary> private readonly Dictionary<string, DateTime> _assemblyUpdatedTimesUtc = new(StringComparer.OrdinalIgnoreCase); private readonly object _guard = new(); private readonly DiagnosticDescriptor _analyzerChangedRule = new( id: IDEDiagnosticIds.AnalyzerChangedId, title: ServicesVSResources.AnalyzerChangedOnDisk, messageFormat: ServicesVSResources.The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted, category: FeaturesResources.Roslyn_HostError, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AnalyzerFileWatcherService( VisualStudioWorkspaceImpl workspace, HostDiagnosticUpdateSource hostDiagnosticUpdateSource, SVsServiceProvider serviceProvider) { _workspace = workspace; _updateSource = hostDiagnosticUpdateSource; _fileChangeService = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx)); } internal void RemoveAnalyzerAlreadyLoadedDiagnostics(ProjectId projectId, string analyzerPath) => _updateSource.ClearDiagnosticsForProject(projectId, Tuple.Create(s_analyzerChangedErrorId, analyzerPath)); private void RaiseAnalyzerChangedWarning(ProjectId projectId, string analyzerPath) { var messageArguments = new string[] { analyzerPath }; var project = _workspace.CurrentSolution.GetProject(projectId); if (project != null && DiagnosticData.TryCreate(_analyzerChangedRule, messageArguments, project, out var diagnostic)) { _updateSource.UpdateDiagnosticsForProject(projectId, Tuple.Create(s_analyzerChangedErrorId, analyzerPath), SpecializedCollections.SingletonEnumerable(diagnostic)); } } private DateTime? GetLastUpdateTimeUtc(string fullPath) { try { var creationTimeUtc = File.GetCreationTimeUtc(fullPath); var writeTimeUtc = File.GetLastWriteTimeUtc(fullPath); return writeTimeUtc > creationTimeUtc ? writeTimeUtc : creationTimeUtc; } catch (IOException) { return null; } catch (UnauthorizedAccessException) { return null; } } internal void TrackFilePathAndReportErrorIfChanged(string filePath, ProjectId projectId) { lock (_guard) { if (!_fileChangeTrackers.TryGetValue(filePath, out var tracker)) { tracker = new FileChangeTracker(_fileChangeService, filePath); tracker.UpdatedOnDisk += Tracker_UpdatedOnDisk; _ = tracker.StartFileChangeListeningAsync(); _fileChangeTrackers.Add(filePath, tracker); } if (_assemblyUpdatedTimesUtc.TryGetValue(filePath, out var assemblyUpdatedTime)) { var currentFileUpdateTime = GetLastUpdateTimeUtc(filePath); if (currentFileUpdateTime != null) { if (currentFileUpdateTime != assemblyUpdatedTime) { RaiseAnalyzerChangedWarning(projectId, filePath); } // If the the tracker is in place, at this point we can stop checking any further for this assembly if (tracker.PreviousCallToStartFileChangeHasAsynchronouslyCompleted) { _assemblyUpdatedTimesUtc.Remove(filePath); } } } else { // We don't have an assembly updated time. This means we either haven't ever checked it, or we have a file watcher in place. // If the file watcher is in place, then nothing further to do. Otherwise we'll add the update time to the map for future checking if (!tracker.PreviousCallToStartFileChangeHasAsynchronouslyCompleted) { var currentFileUpdateTime = GetLastUpdateTimeUtc(filePath); if (currentFileUpdateTime != null) { _assemblyUpdatedTimesUtc[filePath] = currentFileUpdateTime.Value; } } } } } private void Tracker_UpdatedOnDisk(object sender, EventArgs e) { var tracker = (FileChangeTracker)sender; var filePath = tracker.FilePath; lock (_guard) { // Once we've created a diagnostic for a given analyzer file, there's // no need to keep watching it. _fileChangeTrackers.Remove(filePath); } tracker.Dispose(); tracker.UpdatedOnDisk -= Tracker_UpdatedOnDisk; // Traverse the chain of requesting assemblies to get back to the original analyzer // assembly. foreach (var project in _workspace.CurrentSolution.Projects) { var analyzerFileReferences = project.AnalyzerReferences.OfType<AnalyzerFileReference>(); if (analyzerFileReferences.Any(a => a.FullPath.Equals(filePath, StringComparison.OrdinalIgnoreCase))) { RaiseAnalyzerChangedWarning(project.Id, filePath); } } } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./eng/common/templates/post-build/trigger-subscription.yml
parameters: ChannelId: 0 steps: - task: PowerShell@2 displayName: Triggering subscriptions inputs: filePath: $(Build.SourcesDirectory)/eng/common/post-build/trigger-subscriptions.ps1 arguments: -SourceRepo $(Build.Repository.Uri) -ChannelId ${{ parameters.ChannelId }} -MaestroApiAccessToken $(MaestroAccessToken) -MaestroApiEndPoint $(MaestroApiEndPoint) -MaestroApiVersion $(MaestroApiVersion)
parameters: ChannelId: 0 steps: - task: PowerShell@2 displayName: Triggering subscriptions inputs: filePath: $(Build.SourcesDirectory)/eng/common/post-build/trigger-subscriptions.ps1 arguments: -SourceRepo $(Build.Repository.Uri) -ChannelId ${{ parameters.ChannelId }} -MaestroApiAccessToken $(MaestroAccessToken) -MaestroApiEndPoint $(MaestroApiEndPoint) -MaestroApiVersion $(MaestroApiVersion)
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/Server/VBCSCompilerTests/ClientConnectionHandlerTests.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.IO.Pipes; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Moq; using Roslyn.Test.Utilities; using Xunit; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.Test.Utilities; using static Microsoft.CodeAnalysis.CommandLine.BuildResponse; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class ClientConnectionHandlerTests { [Fact] public async Task ThrowDuringBuild() { var compilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), }; var completionData = await clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); Assert.Equal(CompletionData.RequestError, completionData); } [Fact] public async Task ThrowReadingRequest() { var compilerServerHost = new TestableCompilerServerHost(delegate { Assert.True(false, "Should not reach compilation"); throw new Exception(""); }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => throw new Exception(), }; var completionData = await clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); Assert.Equal(CompletionData.RequestError, completionData); } [Fact] public async Task ThrowWritingResponse() { var compilerServerHost = new TestableCompilerServerHost(delegate { return ProtocolUtil.EmptyBuildResponse; }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var threwException = false; var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), WriteBuildResponseFunc = (response, cancellationToken) => { threwException = true; throw new Exception(""); } }; var completionData = await clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); Assert.Equal(CompletionData.RequestError, completionData); Assert.True(threwException); } /// <summary> /// Make sure that when compilation requests are disallowed we don't actually process them /// </summary> [Fact] public async Task CompilationsDisallowed() { var hitCompilation = false; var compilerServerHost = new TestableCompilerServerHost(delegate { hitCompilation = true; Assert.True(false, "Should not reach compilation when compilations are disallowed"); throw new Exception(""); }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); BuildResponse? response = null; var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), WriteBuildResponseFunc = (r, _) => { response = r; return Task.CompletedTask; } }; var completionData = await clientConnectionHandler.ProcessAsync( Task.FromResult<IClientConnection>(clientConnection), allowCompilationRequests: false); Assert.Equal(CompletionData.RequestCompleted, completionData); Assert.True(response is RejectedBuildResponse); Assert.False(hitCompilation); } /// <summary> /// If a client requests a shutdown nothing else about the request should be processed /// </summary> [Theory] [CombinatorialData] public async Task ShutdownRequest(bool allowCompilationRequests) { var hitCompilation = false; var compilerServerHost = new TestableCompilerServerHost(delegate { hitCompilation = true; throw new Exception(""); }); BuildResponse? response = null; var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(BuildRequest.CreateShutdown()), WriteBuildResponseFunc = (r, _) => { response = r; return Task.CompletedTask; } }; var completionData = await clientConnectionHandler.ProcessAsync( Task.FromResult<IClientConnection>(clientConnection), allowCompilationRequests: allowCompilationRequests); Assert.False(hitCompilation); Assert.Equal(new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), completionData); Assert.True(response is ShutdownBuildResponse); } [Fact] public async Task ClientDisconnectDuringBuild() { using var buildStartedMre = new ManualResetEvent(initialState: false); using var clientClosedMre = new ManualResetEvent(initialState: false); var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { buildStartedMre.Set(); clientClosedMre.WaitOne(); Assert.True(cancellationToken.IsCancellationRequested); return ProtocolUtil.EmptyBuildResponse; }); var disconnectTaskCompletionSource = new TaskCompletionSource<object?>(); var isDisposed = false; var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyBasicBuildRequest), DisconnectTask = disconnectTaskCompletionSource.Task, DisposeFunc = () => { isDisposed = true; }, }; var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var task = clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); // Don't trigger the disconnect until we confirm that the client has issued a // build request. buildStartedMre.WaitOne(); disconnectTaskCompletionSource.TrySetResult(null); var completionData = await task; Assert.Equal(CompletionData.RequestError, completionData); Assert.True(isDisposed); clientClosedMre.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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Moq; using Roslyn.Test.Utilities; using Xunit; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.Test.Utilities; using static Microsoft.CodeAnalysis.CommandLine.BuildResponse; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class ClientConnectionHandlerTests { [Fact] public async Task ThrowDuringBuild() { var compilerServerHost = new TestableCompilerServerHost(delegate { throw new Exception(); }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), }; var completionData = await clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); Assert.Equal(CompletionData.RequestError, completionData); } [Fact] public async Task ThrowReadingRequest() { var compilerServerHost = new TestableCompilerServerHost(delegate { Assert.True(false, "Should not reach compilation"); throw new Exception(""); }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => throw new Exception(), }; var completionData = await clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); Assert.Equal(CompletionData.RequestError, completionData); } [Fact] public async Task ThrowWritingResponse() { var compilerServerHost = new TestableCompilerServerHost(delegate { return ProtocolUtil.EmptyBuildResponse; }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var threwException = false; var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), WriteBuildResponseFunc = (response, cancellationToken) => { threwException = true; throw new Exception(""); } }; var completionData = await clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); Assert.Equal(CompletionData.RequestError, completionData); Assert.True(threwException); } /// <summary> /// Make sure that when compilation requests are disallowed we don't actually process them /// </summary> [Fact] public async Task CompilationsDisallowed() { var hitCompilation = false; var compilerServerHost = new TestableCompilerServerHost(delegate { hitCompilation = true; Assert.True(false, "Should not reach compilation when compilations are disallowed"); throw new Exception(""); }); var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); BuildResponse? response = null; var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), WriteBuildResponseFunc = (r, _) => { response = r; return Task.CompletedTask; } }; var completionData = await clientConnectionHandler.ProcessAsync( Task.FromResult<IClientConnection>(clientConnection), allowCompilationRequests: false); Assert.Equal(CompletionData.RequestCompleted, completionData); Assert.True(response is RejectedBuildResponse); Assert.False(hitCompilation); } /// <summary> /// If a client requests a shutdown nothing else about the request should be processed /// </summary> [Theory] [CombinatorialData] public async Task ShutdownRequest(bool allowCompilationRequests) { var hitCompilation = false; var compilerServerHost = new TestableCompilerServerHost(delegate { hitCompilation = true; throw new Exception(""); }); BuildResponse? response = null; var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(BuildRequest.CreateShutdown()), WriteBuildResponseFunc = (r, _) => { response = r; return Task.CompletedTask; } }; var completionData = await clientConnectionHandler.ProcessAsync( Task.FromResult<IClientConnection>(clientConnection), allowCompilationRequests: allowCompilationRequests); Assert.False(hitCompilation); Assert.Equal(new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), completionData); Assert.True(response is ShutdownBuildResponse); } [Fact] public async Task ClientDisconnectDuringBuild() { using var buildStartedMre = new ManualResetEvent(initialState: false); using var clientClosedMre = new ManualResetEvent(initialState: false); var compilerServerHost = new TestableCompilerServerHost((request, cancellationToken) => { buildStartedMre.Set(); clientClosedMre.WaitOne(); Assert.True(cancellationToken.IsCancellationRequested); return ProtocolUtil.EmptyBuildResponse; }); var disconnectTaskCompletionSource = new TaskCompletionSource<object?>(); var isDisposed = false; var clientConnection = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyBasicBuildRequest), DisconnectTask = disconnectTaskCompletionSource.Task, DisposeFunc = () => { isDisposed = true; }, }; var clientConnectionHandler = new ClientConnectionHandler(compilerServerHost); var task = clientConnectionHandler.ProcessAsync(Task.FromResult<IClientConnection>(clientConnection)); // Don't trigger the disconnect until we confirm that the client has issued a // build request. buildStartedMre.WaitOne(); disconnectTaskCompletionSource.TrySetResult(null); var completionData = await task; Assert.Equal(CompletionData.RequestError, completionData); Assert.True(isDisposed); clientClosedMre.Set(); } } }
-1
dotnet/roslyn
56,534
Method type inference should make inference from explicit lambda return type
Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
cston
"2021-09-19T23:12:22Z"
"2021-09-24T15:06:55Z"
2b7f137ebbfdf33e9eebffe87d036be392815d2b
27613724bd239da606824c33e94f52085993c041
Method type inference should make inference from explicit lambda return type. Update ["type inference"](https://github.com/dotnet/csharplang/blob/main/spec/expressions.md#type-inference) to make an exact inference from an explicit lambda return type. Proposed spec changes **in bold**: > #### The first phase > > For each of the method arguments `Ei`: > > * If `Ei` is an anonymous function and `Ti` is a delegate type or expression tree type, an *explicit parameter type inference* ([Explicit parameter type inferences](expressions.md#explicit-parameter-type-inferences)) is made from `Ei` to `Ti` **and an *explicit return type inference* is made from `Ei` to `Ti`.** > * Otherwise, if `Ei` has a type `U` and `xi` is a value parameter then a *lower-bound inference* is made *from* `U` *to* `Ti`. > * Otherwise, if `Ei` has a type `U` and `xi` is a `ref` or `out` parameter then an *exact inference* is made *from* `U` *to* `Ti`. > * Otherwise, no inference is made for this argument. > #### **Explicit return type inference** > > **An *explicit return type inference* is made *from* an expression `E` *to* a type `T` in the following way:** > > * **If `E` is an anonymous function with explicit return type `Ur` and `T` is a delegate type or expression tree type with return type `Vr` then an *exact inference* ([Exact inferences](expressions.md#exact-inferences)) is made *from* `Ur` *to* `Vr`.** See [LDM notes](https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-06-21.md#method-type-inference-from-return-types). Fixes #54257 Relates to test plan #52192
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/BaseClassTests.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.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class BaseClassTests Inherits BasicTestBase <Fact> Public Sub DirectCircularInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits A End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'A' cannot reference itself in Inherits clause. Inherits A ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B End Class Class B Inherits A End Class </file> </compilation>) Dim expectedErrors = <errors> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritance1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B End Class Class B Inherits A End Class Class C Inherits B End Class </file> </compilation>) Dim expectedErrors = <errors> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class B End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31446: Class 'A' cannot reference its nested type 'A.B' in Inherits clause. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C End Class End Class Class B Inherits A.C End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits F Class C class D end class End Class End Class Class F Inherits A.C.D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'F'. 'F' inherits from 'A.C.D'. 'A.C.D' is nested in 'A.C'. 'A.C' is nested in 'A'.'. Inherits F ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C Inherits F class D end class End Class End Class Class B Inherits E End Class Class E Inherits A.C End Class Class F End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C Inherits F class D end class End Class End Class Class B Inherits E End Class Class E Inherits A.C End Class Class F Inherits A.C.D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ BC30907: This inheritance causes circular dependencies between class 'A.C' and its nested or base type ' 'A.C' inherits from 'F'. 'F' inherits from 'A.C.D'. 'A.C.D' is nested in 'A.C'.'. Inherits F ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InheritanceDependencyGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> namespace n1 Class Program Class A(of T) Inherits A(of Integer) End Class End Class end namespace </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'Program.A(Of T)' cannot reference itself in Inherits clause. Inherits A(of Integer) ~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependencyGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits C(Of String) Class C(Of T) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31446: Class 'A' cannot reference its nested type 'A.C(Of String)' in Inherits clause. Inherits C(Of String) ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependencyGeneric1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A(of T) Inherits B Class C(of U) class D end class End Class End Class Class B Inherits E(of B) End Class Class E(of L) Inherits A(of Integer).C(of Long).D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A(Of T)' and its nested or base type ' 'A(Of T)' inherits from 'B'. 'B' inherits from 'E(Of B)'. 'E(Of B)' inherits from 'A(Of Integer).C(Of Long).D'. 'A(Of Integer).C(Of Long).D' is nested in 'A(Of T).C(Of U)'. 'A(Of T).C(Of U)' is nested in 'A(Of T)'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub DirectCircularInheritanceInInterface1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits A, A End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'A' cannot inherit from itself: 'A' inherits from 'A'. Inherits A, A ~ BC30584: 'A' cannot be inherited more than once. Inherits A, A ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritanceInInterface1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface x1 End interface Interface x2 End interface Interface A Inherits B End interface Interface B Inherits x1, B, x2 End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'B' cannot inherit from itself: 'B' inherits from 'B'. Inherits x1, B, x2 ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B Interface B End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30908: interface 'A' cannot inherit from a type nested within it. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B Interface C End Interface End Interface Interface B Inherits A.C End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between interface 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B class C Interface D Inherits F interface E end interface End Interface end class End Interface Interface B Inherits E End Interface Interface E Inherits A.C.D.E End Interface Interface F End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between interface 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C.D.E'. 'A.C.D.E' is nested in 'A.C.D'. 'A.C.D' is nested in 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceImplementingDependency5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1 inherits s1.cls2 implements s1.cls2.i2 interface i1 end interface End Class structure s1 implements cls1.i1 Class cls2 Interface i2 End Interface End Class end structure </file> </compilation>) ' ' this would be an error if implementing was a dependency ' Dim expectedErrors = <errors> 'BC30907: This inheritance causes circular dependencies between structure 's1' and its nested or base type ' ' 's1' implements 'cls1.i1'. ' 'cls1.i1' is nested in 'cls1'. ' 'cls1' inherits from 's1.cls2'. ' 's1.cls2' is nested in 's1'.'. ' implements cls1.i1 ' ~~~~~~~ ' </errors> CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U)). End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.' is not defined. Inherits B(Of C(Of C(Of U)). ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140_a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U)).C(Of U) End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.C' is not defined. Inherits B(Of C(Of C(Of U)).C(Of U) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140_b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U))).C(Of U) End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'B(Of S).C(Of U)' cannot inherit from itself: 'B(Of S).C(Of U)' inherits from 'B(Of S).C(Of U)'. Inherits B(Of C(Of C(Of U))).C(Of U) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U)). End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.' is not defined. Inherits B(Of C(Of C(Of U)). ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140_a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U)).C(Of U) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.C' is not defined. Inherits B(Of C(Of C(Of U)).C(Of U) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140_b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U))).C(Of U) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'B(Of S).C(Of U)' cannot reference itself in Inherits clause. Inherits B(Of C(Of C(Of U))).C(Of U) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceClassMutualContainment() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1 Inherits i1.cls2 Interface i2 End Interface End Class Interface i1 Inherits cls1.i2 Class cls2 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'cls1' and its nested or base type ' 'cls1' inherits from 'i1.cls2'. 'i1.cls2' is nested in 'i1'. 'i1' inherits from 'cls1.i2'. 'cls1.i2' is nested in 'cls1'.'. Inherits i1.cls2 ~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceClassMutualContainmentGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1(of T) Inherits i1(of Integer).cls2 Interface i2 End Interface End Class Interface i1(of T) Inherits cls1(of T).i2 Class cls2 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'cls1(Of T)' and its nested or base type ' 'cls1(Of T)' inherits from 'i1(Of Integer).cls2'. 'i1(Of Integer).cls2' is nested in 'i1(Of T)'. 'i1(Of T)' inherits from 'cls1(Of T).i2'. 'cls1(Of T).i2' is nested in 'cls1(Of T)'.'. Inherits i1(of Integer).cls2 ~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ImportedCycle1() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C3 Inherits C1 End Class </file> </compilation>, {Net451.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ImportedCycle2() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim C3 = TestReferences.SymbolsTests.CyclicInheritance.Class3 Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C3 Inherits C1 End Class </file> </compilation>, {Net451.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C4 Inherits C3 End Class </file> </compilation>, {Net451.mscorlib, C1, C2, C3}) expectedErrors = <errors> BC30916: Type 'C3' is not supported because it either directly or indirectly inherits from itself. Inherits C3 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub CyclicInterfaces3() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Interface I4 Inherits I1 End Interface </file> </compilation>, {Net451.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself. Inherits I1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) End Sub #If Retargeting Then <Fact(skip:=SkipReason.AlreadyTestingRetargeting)> Public Sub CyclicRetargeted4() #Else <Fact> Public Sub CyclicRetargeted4() #End If Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {Net451.mscorlib, ClassAv1}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B_base) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A_base) Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv2, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsType(Of Retargeting.RetargetingNamedTypeSymbol)(B2) Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Dim expectedErrors = <errors> BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself. Inherits ClassB ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp2, expectedErrors) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim errorBase1 = TryCast(A2.BaseType, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) End Sub <Fact> Public Sub CyclicRetargeted5() Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> 'hi </file> </compilation>, { Net451.mscorlib, ClassAv1, ClassBv1 }) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).[Distinct]().Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B1) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B_base) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A_base) Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv2, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B2) Assert.NotEqual(B1, B2) Assert.Same((DirectCast(B1.ContainingModule, PEModuleSymbol)).Module, DirectCast(B2.ContainingModule, PEModuleSymbol).Module) Assert.Equal(DirectCast(B1, PENamedTypeSymbol).Handle, DirectCast(B2, PENamedTypeSymbol).Handle) Assert.Same(C.BaseType, B2) Dim expectedErrors = <errors> BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself. Inherits ClassB ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp2, expectedErrors) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim errorBase1 = TryCast(A2.BaseType, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted6() #Else <Fact> Public Sub CyclicRetargeted6() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {Net451.mscorlib, ClassAv2}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Dim expectedErrors = <errors> BC30257: Class 'ClassB' cannot inherit from itself: 'ClassB' inherits from 'ClassA'. 'ClassA' inherits from 'ClassB'. Inherits ClassA ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Assert.Same(B2.BaseType, A2) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted7() #Else <Fact> Public Sub CyclicRetargeted7() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> 'hi </file> </compilation>, { Net451.mscorlib, ClassAv2, ClassBv1 }) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).[Distinct]().Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsType(Of PENamedTypeSymbol)(B1) Dim errorBase = TryCast(B_base, ErrorTypeSymbol) Dim er = errorBase.ErrorInfo Assert.Equal("error BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, { Net451.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp) }) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsType(Of PENamedTypeSymbol)(B2) Assert.NotEqual(B1, B2) Assert.Same(DirectCast(B1.ContainingModule, PEModuleSymbol).Module, DirectCast(B2.ContainingModule, PEModuleSymbol).Module) Assert.Equal(DirectCast(B1, PENamedTypeSymbol).Handle, DirectCast(B2, PENamedTypeSymbol).Handle) Assert.Same(C.BaseType, B2) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A2.BaseType) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B2.BaseType) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted8() #Else <Fact> Public Sub CyclicRetargeted8() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {Net451.mscorlib, ClassAv2}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Dim expectedErrors = <errors> BC30257: Class 'ClassB' cannot inherit from itself: 'ClassB' inherits from 'ClassA'. 'ClassA' inherits from 'ClassB'. Inherits ClassA ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Assert.Same(B2.BaseType, A2) End Sub <WorkItem(538503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538503")> <Fact> Public Sub TypeFromBaseInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class B End Class End Interface Interface IC Inherits IA Class D Inherits B End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538500")> <Fact> Public Sub TypeThroughBaseInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IB Inherits IA End Interface Class D Inherits IB.C End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' | / ' . / ' \ / ' . ' | ' . <Fact> Public Sub TypeFromBaseInterfaceAmbiguous() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IADerived Inherits IA End Interface Interface IA1Base Class C End Class End Interface Interface IA1 inherits IA1Base, IADerived End Interface Interface IB Inherits IA1 Class D Inherits C End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C' is ambiguous across the inherited interfaces 'IA1Base' and 'IA'. Inherits C ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceDiamondInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IA1 Inherits IA End Interface Interface IA2 inherits IA, IA1 End Interface Interface IA3 inherits IA, IA1, IA2 End Interface Interface IA4 inherits IA, IA1, IA2, IA3 End Interface Interface IB Inherits IA4, IA3, IA2, IA1, IA Class D Inherits C End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . {C1} ' | ' . ' <Fact> Public Sub TypeFromInterfaceYInheritanceShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface IA Shadows Class C1 End Class End Interface Interface IA1 Inherits IA, I0 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . ' | ' . ' <Fact> Public Sub TypeFromInterfaceYInheritanceNoShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface IA Shadows Class C1 End Class End Interface Interface IA1 Inherits IA, I0 End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C1' is ambiguous across the inherited interfaces 'IA' and 'I0'. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub ' ' .{C1} . ' \ / ' . <- .{C1} ' \ / ' . ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . <- .{C1} ' \ / ' . ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / \ ' . <- .{C1} . ' \ / / ' . _ _ _ / ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IA2 Inherits I1 End Interface Interface IB Inherits IA, IA1, IA2 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / \ ' . <- . . ' \ / / ' . _ _ _ / ' <Fact> Public Sub TypeFromInterfaceAInheritanceNoShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 End Interface Interface IA2 Inherits I1 End Interface Interface IB Inherits IA, IA1, IA2 Class D Inherits C1 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C1' is ambiguous across the inherited interfaces 'I0' and 'I1'. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCycles() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> interface ii1 : inherits ii1,ii2 interface ii2 : inherits ii1 end interface end interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'ii1' cannot inherit from itself: 'ii1' inherits from 'ii1'. interface ii1 : inherits ii1,ii2 ~~~ BC30908: interface 'ii1' cannot inherit from a type nested within it. interface ii1 : inherits ii1,ii2 ~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCantShadowAmbiguity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface DerivedWithoutAmbiguity Inherits Base1 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity End Interface Class Test Dim x as Goo.c1 = Nothing End Class </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'c1' is ambiguous across the inherited interfaces 'Base1' and 'Base2'. Dim x as Goo.c1 = Nothing ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCantShadowAmbiguity1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface Base3 Inherits Base1, Base2 Shadows Class c1 End Class End Interface Interface DerivedWithoutAmbiguity Inherits Base3 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity End Interface Class Test Inherits Goo.c1 End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub TypeFromInterfaceUnreachableAmbiguityIsOk() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface DerivedWithoutAmbiguity Inherits Base1 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity Shadows Class c1 End Class End Interface Class Test Dim x as Goo.c1 = Nothing End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub AccessibilityCheckInInherits1() Dim compilationDef = <compilation name="AccessibilityCheckInInherits1"> <file name="a.vb"> Public Class C(Of T) Protected Class A End Class End Class Public Class E Protected Class D Inherits C(Of D) Public Class B Inherits A End Class End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30509: 'B' cannot inherit from class 'C(Of E.D).A' because it expands the access of the base class to class 'E'. Inherits A ~ </expected>) End Sub <Fact> Public Sub AccessibilityCheckInInherits2() Dim compilationDef = <compilation name="AccessibilityCheckInInherits2"> <file name="a.vb"> Public Class C(Of T) End Class Public Class E Inherits C(Of P) Private Class P End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30921: 'E' cannot inherit from class 'C(Of E.P)' because it expands the access of type 'E.P' to namespace '&lt;Default&gt;'. Inherits C(Of P) ~~~~~~~ </expected>) End Sub <WorkItem(538878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538878")> <Fact> Public Sub ProtectedNestedBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Class B End Class End Class Class D Inherits A Protected Class B End Class End Class Class E Inherits D Protected Class F Inherits B End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(537949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537949")> <Fact> Public Sub ImplementingNestedInherited() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I(Of T) End Interface Class A(Of T) Class B Inherits A(Of B) Implements I(Of B.B) End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538509")> <Fact> Public Sub ImplementingNestedInherited1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B Class C End Class End Class Class A(Of T) Inherits B Implements I(Of C) End Class Interface I(Of T) End Interface Class C Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538811")> <Fact> Public Sub OverloadedViaInterfaceInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Function Goo() As T End Interface Interface IB Inherits IA(Of Integer) Overloads Sub Goo(ByVal x As Integer) End Interface Interface IC Inherits IB, IA(Of String) End Interface Module M Sub Main() Dim x As IC = Nothing Dim s As Integer = x.Goo() End Sub End Module </file> </compilation>) Dim expectedErrors = <errors> BC30521: Overload resolution failed because no accessible 'Goo' is most specific for these arguments: 'Function IA(Of String).Goo() As String': Not most specific. 'Function IA(Of Integer).Goo() As Integer': Not most specific. Dim s As Integer = x.Goo() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub OverloadedViaInterfaceInheritance1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Function Goo() As T End Interface Interface IB Class Goo End Class End Interface Interface IC Inherits IB, IA(Of String) End Interface Class M Sub Main() Dim x As IC Dim s As String = x.Goo().ToLower() End Sub End Class </file> </compilation>) Dim expectedErrors = <errors> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Dim s As String = x.Goo().ToLower() ~ BC30685: 'Goo' is ambiguous across the inherited interfaces 'IB' and 'IA(Of String)'. Dim s As String = x.Goo().ToLower() ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <WorkItem(539775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539775")> <Fact> Public Sub AmbiguousNestedInterfaceInheritedFromMultipleGenericInstantiations() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A(Of T) Interface B Inherits A(Of B), A(Of B()) Interface C Inherits B End Interface End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'B' is ambiguous across the inherited interfaces 'A(Of A(Of T).B)' and 'A(Of A(Of T).B())'. Inherits B ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <WorkItem(538809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538809")> <Fact> Public Sub Bug4532() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Overloads Sub Goo(ByVal x As T) End Interface Interface IC Inherits IA(Of Date), IA(Of Integer) Overloads Sub Goo() End Interface Class M Sub Main() Dim c As IC = Nothing c.Goo() End Sub End Class </file> </compilation>) Dim expectedErrors = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub CircularInheritanceThroughSubstitution() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Class B Inherits A(Of E) End Class Class E Inherits B.E.B End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'A(Of T).E' cannot reference itself in Inherits clause. Inherits B.E.B ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub ''' <summary> ''' The base type of a nested type should not change depending on ''' whether or not the base type of the containing type has been ''' evaluated. ''' </summary> <WorkItem(539744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539744")> <Fact> Public Sub BaseTypeEvaluationOrder() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Public Class X End Class End Class Class B Inherits A(Of B.Y.Error) Public Class Y Inherits X End Class End Class </file> </compilation> If True Then Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim classB = CType(compilation.GlobalNamespace.GetMembers("B").Single(), NamedTypeSymbol) Dim classY = CType(classB.GetMembers("Y").Single(), NamedTypeSymbol) Dim baseB = classB.BaseType Assert.Equal("?", baseB.ToDisplayString()) Assert.True(baseB.IsErrorType()) Dim baseY = classY.BaseType Assert.Equal("X", baseY.ToDisplayString()) Assert.True(baseY.IsErrorType()) End If If True Then Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim classB = CType(compilation.GlobalNamespace.GetMembers("B").Single(), NamedTypeSymbol) Dim classY = CType(classB.GetMembers("Y").Single(), NamedTypeSymbol) Dim baseY = classY.BaseType Assert.Equal("X", baseY.ToDisplayString()) Assert.True(baseY.IsErrorType()) Dim baseB = classB.BaseType Assert.Equal("?", baseB.ToDisplayString()) Assert.True(baseB.IsErrorType()) End If End Sub <Fact> Public Sub CyclicBases2() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class X Inherits Y.N End Class Class Y Inherits X.N End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim g = compilation.GlobalNamespace Dim x = g.GetTypeMembers("X").Single() Dim y = g.GetTypeMembers("Y").Single() Assert.NotEqual(y, x.BaseType) Assert.NotEqual(x, y.BaseType) Assert.Equal(SymbolKind.ErrorType, x.BaseType.Kind) Assert.Equal(SymbolKind.ErrorType, y.BaseType.Kind) Assert.Equal("", x.BaseType.Name) Assert.Equal("X.N", y.BaseType.Name) End Sub <Fact> Public Sub CyclicBases4() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Inherits B(Of A(Of T)) End Class Class B(Of T) Inherits A(Of B(Of T)) Public Function F() As A(Of T) Return Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Assert.Equal(1, compilation.GetDeclarationDiagnostics().Length) End Sub <Fact> Public Sub CyclicBases5() ' bases are cyclic, but you can still find members when binding bases Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Public Class X End Class End Class Class B Inherits A Public Class Y End Class End Class Class Z Inherits A.Y End Class Class W Inherits B.X End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim g = compilation.GlobalNamespace Dim z = g.GetTypeMembers("Z").Single() Dim w = g.GetTypeMembers("W").Single() Dim zBase = z.BaseType Assert.Equal("Y", zBase.Name) Dim wBase = w.BaseType Assert.Equal("X", wBase.Name) End Sub <Fact> Public Sub EricLiCase1() Dim text = <compilation name="Compilation"> <file name="a.vb"> Interface I(Of T) End Interface Class A Public Class B End Class End Class Class C Inherits A Implements I(Of C.B) End Class </file> </compilation> Dim compilation0 = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertNoErrors(compilation0) ' same as in Dev10 End Sub <WorkItem(544454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544454")> <Fact()> Public Sub InterfaceImplementedWithPrivateType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Imports System Imports System.Collections Imports System.Collections.Generic Public Class A Implements IEnumerable(Of A.MyPrivateType) Private Class MyPrivateType End Class Private Function GetEnumerator() As IEnumerator(Of MyPrivateType) Implements IEnumerable(Of MyPrivateType).GetEnumerator Throw New NotImplementedException() End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class </file> </compilation>) Dim c2Source = <compilation name="C2"> <file name="b.vb"> Imports System.Collections.Generic Class Z Public Function goo(a As A) As IEnumerable(Of Object) Return a End Function End Class </file> </compilation> Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(c2Source, {New VisualBasicCompilationReference(compilation)}) 'Works this way, but doesn't when compilation is supplied as metadata compilation.VerifyDiagnostics() c2.VerifyDiagnostics() Dim compilationImage = compilation.EmitToArray(options:=New EmitOptions(metadataOnly:=True)) CompilationUtils.CreateCompilationWithMscorlib40AndReferences(c2Source, {MetadataReference.CreateFromImage(compilationImage)}).VerifyDiagnostics() End Sub <WorkItem(792711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792711")> <Fact> Public Sub Repro792711() Dim source = <compilation> <file name="a.vb"> Public Class Base(Of T) End Class Public Class Derived(Of T) : Inherits Base(Of Derived(Of T)) End Class </file> </compilation> Dim metadataRef = CreateCompilationWithMscorlib40(source).EmitToImageReference(embedInteropTypes:=True) Dim comp = CreateCompilationWithMscorlib40AndReferences(<compilation/>, {metadataRef}) Dim derived = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Assert.Equal(TypeKind.Class, derived.TypeKind) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub Repro862536() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Interface B(Of S) : Inherits A(Of B(Of S).B(Of S)) Interface B(Of U) : Inherits B(Of B(Of U)) End Interface End Interface End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'B.B' is not defined. Interface B(Of S) : Inherits A(Of B(Of S).B(Of S)) ~~~~~~~~~~~~~~~ BC40004: interface 'B' conflicts with interface 'B' in the base interface 'A' and should be declared 'Shadows'. Interface B(Of U) : Inherits B(Of B(Of U)) ~ BC30296: Interface 'A(Of T).B(Of S).B(Of U)' cannot inherit from itself: 'A(Of T).B(Of S).B(Of U)' inherits from 'A(Of T).B(Of S).B(Of U)'. Interface B(Of U) : Inherits B(Of B(Of U)) ~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseInterface() Dim source = <compilation> <file name="a.vb"> Interface C(Of T) : Inherits C(Of C(Of T)) End Interface Interface B : Inherits C(Of Integer).NotFound End Interface </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type C(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'C(Of T)' cannot inherit from itself: 'C(Of T)' inherits from 'C(Of T)'. Interface C(Of T) : Inherits C(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Interface B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseInterfaceChain() Dim source = <compilation> <file name="a.vb"> Interface C(Of T) : Inherits D(Of C(Of T)) End Interface Interface D(Of T) : Inherits C(Of D(Of T)) End Interface Interface B : Inherits C(Of Integer).NotFound End Interface </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type D(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'C(Of T)' cannot inherit from itself: 'C(Of T)' inherits from 'D(Of C(Of T))'. 'D(Of C(Of T))' inherits from 'C(Of T)'. Interface C(Of T) : Inherits D(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Interface B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseClass() Dim source = <compilation> <file name="a.vb"> Class C(Of T) : Inherits C(Of C(Of T)) End Class Class B : Inherits C(Of Integer).NotFound End Class </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type C(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC31447: Class 'C(Of T)' cannot reference itself in Inherits clause. Class C(Of T) : Inherits C(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Class B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact()> Public Sub InterfaceCircularInheritance_01() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Inherits A(Of A(Of T)) Interface B Inherits A(Of B) End Interface End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim a = comp.GetTypeByMetadataName("A`1") Dim interfaces = a.AllInterfaces Assert.True(interfaces.Single.IsErrorType()) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'A(Of T)' cannot inherit from itself: 'A(Of T)' inherits from 'A(Of T)'. Inherits A(Of A(Of T)) ~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact()> Public Sub InterfaceCircularInheritance_02() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Inherits C(Of T) Interface B Inherits A(Of B) End Interface End Interface Interface C(Of T) Inherits A(Of A(Of T)) End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim a = comp.GetTypeByMetadataName("A`1") Dim interfaces = a.AllInterfaces Assert.True(interfaces.Single.IsErrorType()) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'A(Of T)' cannot inherit from itself: 'A(Of T)' inherits from 'C(Of T)'. 'C(Of T)' inherits from 'A(Of T)'. Inherits C(Of T) ~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub Tuple_MissingNestedTypeArgument_01() Dim source = "Interface I(Of T) End Interface Class A Implements I(Of (Object, A.B)) End Class" Dim comp = CreateCompilation(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'A.B' is not defined. Implements I(Of (Object, A.B)) ~~~ ]]></errors>) End Sub <Fact> Public Sub Tuple_MissingNestedTypeArgument_02() Dim source = "Class A(Of T) End Class Class B Inherits A(Of (Object, B.C)) End Class" Dim comp = CreateCompilation(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'B.C' is not defined. Inherits A(Of (Object, B.C)) ~~~ ]]></errors>) End Sub <Fact> Public Sub Tuple_MissingNestedTypeArgument_03() Dim source = "Interface I(Of T) End Interface Class A Implements I(Of System.ValueTuple(Of Object, A.B)) End Class" Dim comp = CreateCompilation(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'A.B' is not defined. Implements I(Of System.ValueTuple(Of Object, A.B)) ~~~ ]]></errors>) 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.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class BaseClassTests Inherits BasicTestBase <Fact> Public Sub DirectCircularInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits A End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'A' cannot reference itself in Inherits clause. Inherits A ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B End Class Class B Inherits A End Class </file> </compilation>) Dim expectedErrors = <errors> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritance1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B End Class Class B Inherits A End Class Class C Inherits B End Class </file> </compilation>) Dim expectedErrors = <errors> BC30257: Class 'A' cannot inherit from itself: 'A' inherits from 'B'. 'B' inherits from 'A'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class B End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31446: Class 'A' cannot reference its nested type 'A.B' in Inherits clause. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C End Class End Class Class B Inherits A.C End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency3() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits F Class C class D end class End Class End Class Class F Inherits A.C.D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'F'. 'F' inherits from 'A.C.D'. 'A.C.D' is nested in 'A.C'. 'A.C' is nested in 'A'.'. Inherits F ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C Inherits F class D end class End Class End Class Class B Inherits E End Class Class E Inherits A.C End Class Class F End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependency5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Class C Inherits F class D end class End Class End Class Class B Inherits E End Class Class E Inherits A.C End Class Class F Inherits A.C.D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ BC30907: This inheritance causes circular dependencies between class 'A.C' and its nested or base type ' 'A.C' inherits from 'F'. 'F' inherits from 'A.C.D'. 'A.C.D' is nested in 'A.C'.'. Inherits F ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InheritanceDependencyGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> namespace n1 Class Program Class A(of T) Inherits A(of Integer) End Class End Class end namespace </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'Program.A(Of T)' cannot reference itself in Inherits clause. Inherits A(of Integer) ~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependencyGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Inherits C(Of String) Class C(Of T) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31446: Class 'A' cannot reference its nested type 'A.C(Of String)' in Inherits clause. Inherits C(Of String) ~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ContainmentDependencyGeneric1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A(of T) Inherits B Class C(of U) class D end class End Class End Class Class B Inherits E(of B) End Class Class E(of L) Inherits A(of Integer).C(of Long).D End Class </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'A(Of T)' and its nested or base type ' 'A(Of T)' inherits from 'B'. 'B' inherits from 'E(Of B)'. 'E(Of B)' inherits from 'A(Of Integer).C(Of Long).D'. 'A(Of Integer).C(Of Long).D' is nested in 'A(Of T).C(Of U)'. 'A(Of T).C(Of U)' is nested in 'A(Of T)'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub DirectCircularInheritanceInInterface1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits A, A End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'A' cannot inherit from itself: 'A' inherits from 'A'. Inherits A, A ~ BC30584: 'A' cannot be inherited more than once. Inherits A, A ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InDirectCircularInheritanceInInterface1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface x1 End interface Interface x2 End interface Interface A Inherits B End interface Interface B Inherits x1, B, x2 End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'B' cannot inherit from itself: 'B' inherits from 'B'. Inherits x1, B, x2 ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B Interface B End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30908: interface 'A' cannot inherit from a type nested within it. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B Interface C End Interface End Interface Interface B Inherits A.C End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between interface 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceContainmentDependency4() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A Inherits B class C Interface D Inherits F interface E end interface End Interface end class End Interface Interface B Inherits E End Interface Interface E Inherits A.C.D.E End Interface Interface F End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between interface 'A' and its nested or base type ' 'A' inherits from 'B'. 'B' inherits from 'E'. 'E' inherits from 'A.C.D.E'. 'A.C.D.E' is nested in 'A.C.D'. 'A.C.D' is nested in 'A.C'. 'A.C' is nested in 'A'.'. Inherits B ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceImplementingDependency5() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1 inherits s1.cls2 implements s1.cls2.i2 interface i1 end interface End Class structure s1 implements cls1.i1 Class cls2 Interface i2 End Interface End Class end structure </file> </compilation>) ' ' this would be an error if implementing was a dependency ' Dim expectedErrors = <errors> 'BC30907: This inheritance causes circular dependencies between structure 's1' and its nested or base type ' ' 's1' implements 'cls1.i1'. ' 'cls1.i1' is nested in 'cls1'. ' 'cls1' inherits from 's1.cls2'. ' 's1.cls2' is nested in 's1'.'. ' implements cls1.i1 ' ~~~~~~~ ' </errors> CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U)). End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.' is not defined. Inherits B(Of C(Of C(Of U)). ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140_a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U)).C(Of U) End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.C' is not defined. Inherits B(Of C(Of C(Of U)).C(Of U) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(850140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850140")> <Fact> Public Sub InterfaceCycleBug850140_b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface B(Of S) Interface C(Of U) Inherits B(Of C(Of C(Of U))).C(Of U) End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'B(Of S).C(Of U)' cannot inherit from itself: 'B(Of S).C(Of U)' inherits from 'B(Of S).C(Of U)'. Inherits B(Of C(Of C(Of U))).C(Of U) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U)). End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.' is not defined. Inherits B(Of C(Of C(Of U)). ~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140_a() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U)).C(Of U) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC30002: Type 'C.C' is not defined. Inherits B(Of C(Of C(Of U)).C(Of U) ~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ClassCycleBug850140_b() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B(Of S) Class C(Of U) Inherits B(Of C(Of C(Of U))).C(Of U) End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'B(Of S).C(Of U)' cannot reference itself in Inherits clause. Inherits B(Of C(Of C(Of U))).C(Of U) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceClassMutualContainment() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1 Inherits i1.cls2 Interface i2 End Interface End Class Interface i1 Inherits cls1.i2 Class cls2 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'cls1' and its nested or base type ' 'cls1' inherits from 'i1.cls2'. 'i1.cls2' is nested in 'i1'. 'i1' inherits from 'cls1.i2'. 'cls1.i2' is nested in 'cls1'.'. Inherits i1.cls2 ~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub InterfaceClassMutualContainmentGeneric() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class cls1(of T) Inherits i1(of Integer).cls2 Interface i2 End Interface End Class Interface i1(of T) Inherits cls1(of T).i2 Class cls2 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30907: This inheritance causes circular dependencies between class 'cls1(Of T)' and its nested or base type ' 'cls1(Of T)' inherits from 'i1(Of Integer).cls2'. 'i1(Of Integer).cls2' is nested in 'i1(Of T)'. 'i1(Of T)' inherits from 'cls1(Of T).i2'. 'cls1(Of T).i2' is nested in 'cls1(Of T)'.'. Inherits i1(of Integer).cls2 ~~~~~~~~~~~~~~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ImportedCycle1() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C3 Inherits C1 End Class </file> </compilation>, {Net451.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ImportedCycle2() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim C3 = TestReferences.SymbolsTests.CyclicInheritance.Class3 Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C3 Inherits C1 End Class </file> </compilation>, {Net451.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) compilation = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Class C4 Inherits C3 End Class </file> </compilation>, {Net451.mscorlib, C1, C2, C3}) expectedErrors = <errors> BC30916: Type 'C3' is not supported because it either directly or indirectly inherits from itself. Inherits C3 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub CyclicInterfaces3() Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1 Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2 Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="Compilation"> <file name="a.vb"> Interface I4 Inherits I1 End Interface </file> </compilation>, {Net451.mscorlib, C1, C2}) Dim expectedErrors = <errors> BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself. Inherits I1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) End Sub #If Retargeting Then <Fact(skip:=SkipReason.AlreadyTestingRetargeting)> Public Sub CyclicRetargeted4() #Else <Fact> Public Sub CyclicRetargeted4() #End If Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {Net451.mscorlib, ClassAv1}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B_base) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A_base) Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv2, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsType(Of Retargeting.RetargetingNamedTypeSymbol)(B2) Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Dim expectedErrors = <errors> BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself. Inherits ClassB ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp2, expectedErrors) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim errorBase1 = TryCast(A2.BaseType, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) End Sub <Fact> Public Sub CyclicRetargeted5() Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> 'hi </file> </compilation>, { Net451.mscorlib, ClassAv1, ClassBv1 }) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).[Distinct]().Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B1) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B_base) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A_base) Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv2, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B2) Assert.NotEqual(B1, B2) Assert.Same((DirectCast(B1.ContainingModule, PEModuleSymbol)).Module, DirectCast(B2.ContainingModule, PEModuleSymbol).Module) Assert.Equal(DirectCast(B1, PENamedTypeSymbol).Handle, DirectCast(B2, PENamedTypeSymbol).Handle) Assert.Same(C.BaseType, B2) Dim expectedErrors = <errors> BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself. Inherits ClassB ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp2, expectedErrors) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim errorBase1 = TryCast(A2.BaseType, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted6() #Else <Fact> Public Sub CyclicRetargeted6() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {Net451.mscorlib, ClassAv2}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Dim expectedErrors = <errors> BC30257: Class 'ClassB' cannot inherit from itself: 'ClassB' inherits from 'ClassA'. 'ClassA' inherits from 'ClassB'. Inherits ClassA ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Assert.Same(B2.BaseType, A2) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted7() #Else <Fact> Public Sub CyclicRetargeted7() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim ClassBv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassB.netmodule Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> 'hi </file> </compilation>, { Net451.mscorlib, ClassAv2, ClassBv1 }) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).[Distinct]().Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Assert.IsType(Of PENamedTypeSymbol)(B1) Dim errorBase = TryCast(B_base, ErrorTypeSymbol) Dim er = errorBase.ErrorInfo Assert.Equal("error BC30916: Type 'ClassB' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, { Net451.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp) }) Dim [global] = Comp2.GlobalNamespace Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.IsType(Of PENamedTypeSymbol)(B2) Assert.NotEqual(B1, B2) Assert.Same(DirectCast(B1.ContainingModule, PEModuleSymbol).Module, DirectCast(B2.ContainingModule, PEModuleSymbol).Module) Assert.Equal(DirectCast(B1, PENamedTypeSymbol).Handle, DirectCast(B2, PENamedTypeSymbol).Handle) Assert.Same(C.BaseType, B2) Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Assert.IsAssignableFrom(Of PENamedTypeSymbol)(A2.BaseType) Assert.IsAssignableFrom(Of PENamedTypeSymbol)(B2.BaseType) End Sub #If retargeting Then <Fact(skip:="Already using Feature")> Public Sub CyclicRetargeted8() #Else <Fact> Public Sub CyclicRetargeted8() #End If Dim ClassAv2 = TestReferences.SymbolsTests.RetargetingCycle.V2.ClassA.dll Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB"> <file name="B.vb"> Public Class ClassB Inherits ClassA End Class </file> </compilation>, {Net451.mscorlib, ClassAv2}) Dim global1 = Comp.GlobalNamespace Dim B1 = global1.GetTypeMembers("ClassB", 0).Single() Dim A1 = global1.GetTypeMembers("ClassA", 0).Single() Dim B_base = B1.BaseType Dim A_base = A1.BaseType Dim expectedErrors = <errors> BC30257: Class 'ClassB' cannot inherit from itself: 'ClassB' inherits from 'ClassA'. 'ClassA' inherits from 'ClassB'. Inherits ClassA ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors) Dim errorBase1 = TryCast(A_base, ErrorTypeSymbol) Dim er = errorBase1.ErrorInfo Assert.Equal("error BC30916: Type 'ClassA' is not supported because it either directly or indirectly inherits from itself.", er.ToString(EnsureEnglishUICulture.PreferredOrNull)) Dim ClassAv1 = TestReferences.SymbolsTests.RetargetingCycle.V1.ClassA.dll Dim Comp2 = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation name="ClassB1"> <file name="B.vb"> Public Class ClassC Inherits ClassB End Class </file> </compilation>, New MetadataReference() {Net451.mscorlib, ClassAv1, New VisualBasicCompilationReference(Comp)}) Dim [global] = Comp2.GlobalNamespace Dim A2 = [global].GetTypeMembers("ClassA", 0).Single() Dim B2 = [global].GetTypeMembers("ClassB", 0).Single() Dim C = [global].GetTypeMembers("ClassC", 0).Single() Assert.Same(B1, (DirectCast(B2, Retargeting.RetargetingNamedTypeSymbol)).UnderlyingNamedType) Assert.Same(C.BaseType, B2) Assert.Same(B2.BaseType, A2) End Sub <WorkItem(538503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538503")> <Fact> Public Sub TypeFromBaseInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class B End Class End Interface Interface IC Inherits IA Class D Inherits B End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538500")> <Fact> Public Sub TypeThroughBaseInterface() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IB Inherits IA End Interface Class D Inherits IB.C End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' | / ' . / ' \ / ' . ' | ' . <Fact> Public Sub TypeFromBaseInterfaceAmbiguous() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IADerived Inherits IA End Interface Interface IA1Base Class C End Class End Interface Interface IA1 inherits IA1Base, IADerived End Interface Interface IB Inherits IA1 Class D Inherits C End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C' is ambiguous across the inherited interfaces 'IA1Base' and 'IA'. Inherits C ~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceDiamondInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA Class C End Class End Interface Interface IA1 Inherits IA End Interface Interface IA2 inherits IA, IA1 End Interface Interface IA3 inherits IA, IA1, IA2 End Interface Interface IA4 inherits IA, IA1, IA2, IA3 End Interface Interface IB Inherits IA4, IA3, IA2, IA1, IA Class D Inherits C End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . {C1} ' | ' . ' <Fact> Public Sub TypeFromInterfaceYInheritanceShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface IA Shadows Class C1 End Class End Interface Interface IA1 Inherits IA, I0 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . ' | ' . ' <Fact> Public Sub TypeFromInterfaceYInheritanceNoShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface IA Shadows Class C1 End Class End Interface Interface IA1 Inherits IA, I0 End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C1' is ambiguous across the inherited interfaces 'IA' and 'I0'. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub ' ' .{C1} . ' \ / ' . <- .{C1} ' \ / ' . ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / ' . <- .{C1} ' \ / ' . ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IB Inherits IA, IA1 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / \ ' . <- .{C1} . ' \ / / ' . _ _ _ / ' <Fact> Public Sub TypeFromInterfaceAInheritanceShadow2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 Shadows Class C1 End Class End Interface Interface IA2 Inherits I1 End Interface Interface IB Inherits IA, IA1, IA2 Class D Inherits C1 End Class End Interface </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub ' ' .{C1} .{C1} ' \ / \ ' . <- . . ' \ / / ' . _ _ _ / ' <Fact> Public Sub TypeFromInterfaceAInheritanceNoShadow() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I0 Shadows Class C1 End Class End Interface Interface I1 Shadows Class C1 End Class End Interface Interface IA Inherits I0 End Interface Interface IA1 Inherits IA, I1 End Interface Interface IA2 Inherits I1 End Interface Interface IB Inherits IA, IA1, IA2 Class D Inherits C1 End Class End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'C1' is ambiguous across the inherited interfaces 'I0' and 'I1'. Inherits C1 ~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCycles() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> interface ii1 : inherits ii1,ii2 interface ii2 : inherits ii1 end interface end interface </file> </compilation>) Dim expectedErrors = <errors> BC30296: Interface 'ii1' cannot inherit from itself: 'ii1' inherits from 'ii1'. interface ii1 : inherits ii1,ii2 ~~~ BC30908: interface 'ii1' cannot inherit from a type nested within it. interface ii1 : inherits ii1,ii2 ~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCantShadowAmbiguity() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface DerivedWithoutAmbiguity Inherits Base1 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity End Interface Class Test Dim x as Goo.c1 = Nothing End Class </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'c1' is ambiguous across the inherited interfaces 'Base1' and 'Base2'. Dim x as Goo.c1 = Nothing ~~~~~~ </errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub TypeFromInterfaceCantShadowAmbiguity1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface Base3 Inherits Base1, Base2 Shadows Class c1 End Class End Interface Interface DerivedWithoutAmbiguity Inherits Base3 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity End Interface Class Test Inherits Goo.c1 End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub TypeFromInterfaceUnreachableAmbiguityIsOk() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface Base1 Shadows Class c1 End Class End Interface Interface Base2 Shadows Class c1 End Class End Interface Interface DerivedWithAmbiguity Inherits Base1, Base2 End Interface Interface DerivedWithoutAmbiguity Inherits Base1 End Interface Interface Goo Inherits DerivedWithAmbiguity, DerivedWithoutAmbiguity Shadows Class c1 End Class End Interface Class Test Dim x as Goo.c1 = Nothing End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub AccessibilityCheckInInherits1() Dim compilationDef = <compilation name="AccessibilityCheckInInherits1"> <file name="a.vb"> Public Class C(Of T) Protected Class A End Class End Class Public Class E Protected Class D Inherits C(Of D) Public Class B Inherits A End Class End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30509: 'B' cannot inherit from class 'C(Of E.D).A' because it expands the access of the base class to class 'E'. Inherits A ~ </expected>) End Sub <Fact> Public Sub AccessibilityCheckInInherits2() Dim compilationDef = <compilation name="AccessibilityCheckInInherits2"> <file name="a.vb"> Public Class C(Of T) End Class Public Class E Inherits C(Of P) Private Class P End Class End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30921: 'E' cannot inherit from class 'C(Of E.P)' because it expands the access of type 'E.P' to namespace '&lt;Default&gt;'. Inherits C(Of P) ~~~~~~~ </expected>) End Sub <WorkItem(538878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538878")> <Fact> Public Sub ProtectedNestedBase() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A Class B End Class End Class Class D Inherits A Protected Class B End Class End Class Class E Inherits D Protected Class F Inherits B End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(537949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537949")> <Fact> Public Sub ImplementingNestedInherited() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface I(Of T) End Interface Class A(Of T) Class B Inherits A(Of B) Implements I(Of B.B) End Class End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538509")> <Fact> Public Sub ImplementingNestedInherited1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class B Class C End Class End Class Class A(Of T) Inherits B Implements I(Of C) End Class Interface I(Of T) End Interface Class C Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <WorkItem(538811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538811")> <Fact> Public Sub OverloadedViaInterfaceInheritance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Function Goo() As T End Interface Interface IB Inherits IA(Of Integer) Overloads Sub Goo(ByVal x As Integer) End Interface Interface IC Inherits IB, IA(Of String) End Interface Module M Sub Main() Dim x As IC = Nothing Dim s As Integer = x.Goo() End Sub End Module </file> </compilation>) Dim expectedErrors = <errors> BC30521: Overload resolution failed because no accessible 'Goo' is most specific for these arguments: 'Function IA(Of String).Goo() As String': Not most specific. 'Function IA(Of Integer).Goo() As Integer': Not most specific. Dim s As Integer = x.Goo() ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub OverloadedViaInterfaceInheritance1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Function Goo() As T End Interface Interface IB Class Goo End Class End Interface Interface IC Inherits IB, IA(Of String) End Interface Class M Sub Main() Dim x As IC Dim s As String = x.Goo().ToLower() End Sub End Class </file> </compilation>) Dim expectedErrors = <errors> BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Dim s As String = x.Goo().ToLower() ~ BC30685: 'Goo' is ambiguous across the inherited interfaces 'IB' and 'IA(Of String)'. Dim s As String = x.Goo().ToLower() ~~~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <WorkItem(539775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539775")> <Fact> Public Sub AmbiguousNestedInterfaceInheritedFromMultipleGenericInstantiations() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface A(Of T) Interface B Inherits A(Of B), A(Of B()) Interface C Inherits B End Interface End Interface End Interface </file> </compilation>) Dim expectedErrors = <errors> BC30685: 'B' is ambiguous across the inherited interfaces 'A(Of A(Of T).B)' and 'A(Of A(Of T).B())'. Inherits B ~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <WorkItem(538809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538809")> <Fact> Public Sub Bug4532() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Interface IA(Of T) Overloads Sub Goo(ByVal x As T) End Interface Interface IC Inherits IA(Of Date), IA(Of Integer) Overloads Sub Goo() End Interface Class M Sub Main() Dim c As IC = Nothing c.Goo() End Sub End Class </file> </compilation>) Dim expectedErrors = <errors> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub CircularInheritanceThroughSubstitution() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Class B Inherits A(Of E) End Class Class E Inherits B.E.B End Class End Class </file> </compilation>) Dim expectedErrors = <errors> BC31447: Class 'A(Of T).E' cannot reference itself in Inherits clause. Inherits B.E.B ~~~ </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub ''' <summary> ''' The base type of a nested type should not change depending on ''' whether or not the base type of the containing type has been ''' evaluated. ''' </summary> <WorkItem(539744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539744")> <Fact> Public Sub BaseTypeEvaluationOrder() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Public Class X End Class End Class Class B Inherits A(Of B.Y.Error) Public Class Y Inherits X End Class End Class </file> </compilation> If True Then Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim classB = CType(compilation.GlobalNamespace.GetMembers("B").Single(), NamedTypeSymbol) Dim classY = CType(classB.GetMembers("Y").Single(), NamedTypeSymbol) Dim baseB = classB.BaseType Assert.Equal("?", baseB.ToDisplayString()) Assert.True(baseB.IsErrorType()) Dim baseY = classY.BaseType Assert.Equal("X", baseY.ToDisplayString()) Assert.True(baseY.IsErrorType()) End If If True Then Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim classB = CType(compilation.GlobalNamespace.GetMembers("B").Single(), NamedTypeSymbol) Dim classY = CType(classB.GetMembers("Y").Single(), NamedTypeSymbol) Dim baseY = classY.BaseType Assert.Equal("X", baseY.ToDisplayString()) Assert.True(baseY.IsErrorType()) Dim baseB = classB.BaseType Assert.Equal("?", baseB.ToDisplayString()) Assert.True(baseB.IsErrorType()) End If End Sub <Fact> Public Sub CyclicBases2() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class X Inherits Y.N End Class Class Y Inherits X.N End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim g = compilation.GlobalNamespace Dim x = g.GetTypeMembers("X").Single() Dim y = g.GetTypeMembers("Y").Single() Assert.NotEqual(y, x.BaseType) Assert.NotEqual(x, y.BaseType) Assert.Equal(SymbolKind.ErrorType, x.BaseType.Kind) Assert.Equal(SymbolKind.ErrorType, y.BaseType.Kind) Assert.Equal("", x.BaseType.Name) Assert.Equal("X.N", y.BaseType.Name) End Sub <Fact> Public Sub CyclicBases4() Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A(Of T) Inherits B(Of A(Of T)) End Class Class B(Of T) Inherits A(Of B(Of T)) Public Function F() As A(Of T) Return Nothing End Function End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Assert.Equal(1, compilation.GetDeclarationDiagnostics().Length) End Sub <Fact> Public Sub CyclicBases5() ' bases are cyclic, but you can still find members when binding bases Dim text = <compilation name="Compilation"> <file name="a.vb"> Class A Inherits B Public Class X End Class End Class Class B Inherits A Public Class Y End Class End Class Class Z Inherits A.Y End Class Class W Inherits B.X End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(text) Dim g = compilation.GlobalNamespace Dim z = g.GetTypeMembers("Z").Single() Dim w = g.GetTypeMembers("W").Single() Dim zBase = z.BaseType Assert.Equal("Y", zBase.Name) Dim wBase = w.BaseType Assert.Equal("X", wBase.Name) End Sub <Fact> Public Sub EricLiCase1() Dim text = <compilation name="Compilation"> <file name="a.vb"> Interface I(Of T) End Interface Class A Public Class B End Class End Class Class C Inherits A Implements I(Of C.B) End Class </file> </compilation> Dim compilation0 = CompilationUtils.CreateCompilationWithMscorlib40(text) CompilationUtils.AssertNoErrors(compilation0) ' same as in Dev10 End Sub <WorkItem(544454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544454")> <Fact()> Public Sub InterfaceImplementedWithPrivateType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Compilation"> <file name="a.vb"> Imports System Imports System.Collections Imports System.Collections.Generic Public Class A Implements IEnumerable(Of A.MyPrivateType) Private Class MyPrivateType End Class Private Function GetEnumerator() As IEnumerator(Of MyPrivateType) Implements IEnumerable(Of MyPrivateType).GetEnumerator Throw New NotImplementedException() End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class </file> </compilation>) Dim c2Source = <compilation name="C2"> <file name="b.vb"> Imports System.Collections.Generic Class Z Public Function goo(a As A) As IEnumerable(Of Object) Return a End Function End Class </file> </compilation> Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(c2Source, {New VisualBasicCompilationReference(compilation)}) 'Works this way, but doesn't when compilation is supplied as metadata compilation.VerifyDiagnostics() c2.VerifyDiagnostics() Dim compilationImage = compilation.EmitToArray(options:=New EmitOptions(metadataOnly:=True)) CompilationUtils.CreateCompilationWithMscorlib40AndReferences(c2Source, {MetadataReference.CreateFromImage(compilationImage)}).VerifyDiagnostics() End Sub <WorkItem(792711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792711")> <Fact> Public Sub Repro792711() Dim source = <compilation> <file name="a.vb"> Public Class Base(Of T) End Class Public Class Derived(Of T) : Inherits Base(Of Derived(Of T)) End Class </file> </compilation> Dim metadataRef = CreateCompilationWithMscorlib40(source).EmitToImageReference(embedInteropTypes:=True) Dim comp = CreateCompilationWithMscorlib40AndReferences(<compilation/>, {metadataRef}) Dim derived = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Assert.Equal(TypeKind.Class, derived.TypeKind) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub Repro862536() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Interface B(Of S) : Inherits A(Of B(Of S).B(Of S)) Interface B(Of U) : Inherits B(Of B(Of U)) End Interface End Interface End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'B.B' is not defined. Interface B(Of S) : Inherits A(Of B(Of S).B(Of S)) ~~~~~~~~~~~~~~~ BC40004: interface 'B' conflicts with interface 'B' in the base interface 'A' and should be declared 'Shadows'. Interface B(Of U) : Inherits B(Of B(Of U)) ~ BC30296: Interface 'A(Of T).B(Of S).B(Of U)' cannot inherit from itself: 'A(Of T).B(Of S).B(Of U)' inherits from 'A(Of T).B(Of S).B(Of U)'. Interface B(Of U) : Inherits B(Of B(Of U)) ~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseInterface() Dim source = <compilation> <file name="a.vb"> Interface C(Of T) : Inherits C(Of C(Of T)) End Interface Interface B : Inherits C(Of Integer).NotFound End Interface </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type C(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'C(Of T)' cannot inherit from itself: 'C(Of T)' inherits from 'C(Of T)'. Interface C(Of T) : Inherits C(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Interface B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseInterfaceChain() Dim source = <compilation> <file name="a.vb"> Interface C(Of T) : Inherits D(Of C(Of T)) End Interface Interface D(Of T) : Inherits C(Of D(Of T)) End Interface Interface B : Inherits C(Of Integer).NotFound End Interface </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type D(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'C(Of T)' cannot inherit from itself: 'C(Of T)' inherits from 'D(Of C(Of T))'. 'D(Of C(Of T))' inherits from 'C(Of T)'. Interface C(Of T) : Inherits D(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Interface B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(862536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862536")> <Fact> Public Sub ExpandingBaseClass() Dim source = <compilation> <file name="a.vb"> Class C(Of T) : Inherits C(Of C(Of T)) End Class Class B : Inherits C(Of Integer).NotFound End Class </file> </compilation> ' Can't find NotFound in C(Of Integer), so we check the base type C(Of C(Of Integer)), etc. Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC31447: Class 'C(Of T)' cannot reference itself in Inherits clause. Class C(Of T) : Inherits C(Of C(Of T)) ~~~~~~~~~~~~~ BC30002: Type 'C.NotFound' is not defined. Class B : Inherits C(Of Integer).NotFound ~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees.Single()) Dim typeC = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").Construct(comp.GetSpecialType(SpecialType.System_Int32)) Assert.Equal(0, model.LookupSymbols(0, typeC, "NotFound").Length) End Sub <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact()> Public Sub InterfaceCircularInheritance_01() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Inherits A(Of A(Of T)) Interface B Inherits A(Of B) End Interface End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim a = comp.GetTypeByMetadataName("A`1") Dim interfaces = a.AllInterfaces Assert.True(interfaces.Single.IsErrorType()) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'A(Of T)' cannot inherit from itself: 'A(Of T)' inherits from 'A(Of T)'. Inherits A(Of A(Of T)) ~~~~~~~~~~~~~ ]]></errors>) End Sub <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact()> Public Sub InterfaceCircularInheritance_02() Dim source = <compilation> <file name="a.vb"> Interface A(Of T) Inherits C(Of T) Interface B Inherits A(Of B) End Interface End Interface Interface C(Of T) Inherits A(Of A(Of T)) End Interface </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim a = comp.GetTypeByMetadataName("A`1") Dim interfaces = a.AllInterfaces Assert.True(interfaces.Single.IsErrorType()) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30296: Interface 'A(Of T)' cannot inherit from itself: 'A(Of T)' inherits from 'C(Of T)'. 'C(Of T)' inherits from 'A(Of T)'. Inherits C(Of T) ~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub Tuple_MissingNestedTypeArgument_01() Dim source = "Interface I(Of T) End Interface Class A Implements I(Of (Object, A.B)) End Class" Dim comp = CreateCompilation(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'A.B' is not defined. Implements I(Of (Object, A.B)) ~~~ ]]></errors>) End Sub <Fact> Public Sub Tuple_MissingNestedTypeArgument_02() Dim source = "Class A(Of T) End Class Class B Inherits A(Of (Object, B.C)) End Class" Dim comp = CreateCompilation(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'B.C' is not defined. Inherits A(Of (Object, B.C)) ~~~ ]]></errors>) End Sub <Fact> Public Sub Tuple_MissingNestedTypeArgument_03() Dim source = "Interface I(Of T) End Interface Class A Implements I(Of System.ValueTuple(Of Object, A.B)) End Class" Dim comp = CreateCompilation(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30002: Type 'A.B' is not defined. Implements I(Of System.ValueTuple(Of Object, A.B)) ~~~ ]]></errors>) End Sub End Class End Namespace
-1